You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@atlas.apache.org by ma...@apache.org on 2018/04/05 00:56:15 UTC
[5/5] atlas git commit: ATLAS-2460: implementation of
migration-import to migrate Atlas data in Titan to JanusGraph
ATLAS-2460: implementation of migration-import to migrate Atlas data in Titan to JanusGraph
Signed-off-by: Madhan Neethiraj <ma...@apache.org>
Project: http://git-wip-us.apache.org/repos/asf/atlas/repo
Commit: http://git-wip-us.apache.org/repos/asf/atlas/commit/3ded3ee2
Tree: http://git-wip-us.apache.org/repos/asf/atlas/tree/3ded3ee2
Diff: http://git-wip-us.apache.org/repos/asf/atlas/diff/3ded3ee2
Branch: refs/heads/master
Commit: 3ded3ee2f96d4bd44755792436e6c43865821e87
Parents: 7f5a665
Author: Ashutosh Mestry <am...@hortonworks.com>
Authored: Wed Apr 4 16:22:43 2018 -0700
Committer: Madhan Neethiraj <ma...@apache.org>
Committed: Wed Apr 4 17:55:50 2018 -0700
----------------------------------------------------------------------
.../java/org/apache/atlas/AtlasConstants.java | 3 +
.../org/apache/atlas/repository/Constants.java | 3 +
.../java/org/apache/atlas/service/Services.java | 70 +-
.../atlas/repository/graphdb/AtlasGraph.java | 3 +
.../graphdb/janus/AtlasJanusGraph.java | 6 +
.../graphdb/janus/AtlasJanusGraphDatabase.java | 52 +-
.../janus/migration/AtlasGraphSONReader.java | 314 ++
.../janus/migration/GraphSONTokensTP2.java | 46 +
.../janus/migration/GraphSONUtility.java | 326 ++
.../janus/migration/JsonNodeParsers.java | 199 +
.../janus/migration/JsonNodeProcessManager.java | 222 +
.../janus/migration/MappedElementCache.java | 116 +
.../janus/migration/PostProcessManager.java | 117 +
.../janus/migration/ReaderStatusManager.java | 116 +
.../janus/migration/RelationshipTypeCache.java | 42 +
.../janus/migration/pc/WorkItemBuilder.java | 25 +
.../janus/migration/pc/WorkItemConsumer.java | 94 +
.../janus/migration/pc/WorkItemManager.java | 75 +
.../repository/graphdb/titan0/Titan0Graph.java | 6 +
.../atlas/model/impexp/AtlasExportResult.java | 6 +-
.../atlas/model/impexp/MigrationStatus.java | 92 +
.../apache/atlas/store/AtlasTypeDefStore.java | 4 +
pom.xml | 5 +-
repository/pom.xml | 9 +-
.../graph/GraphBackedSearchIndexer.java | 28 +-
.../impexp/MigrationProgressService.java | 114 +
.../migration/DataMigrationService.java | 145 +
.../migration/RelationshipCacheGenerator.java | 73 +
.../bootstrap/AtlasTypeDefStoreInitializer.java | 61 +-
.../store/graph/v1/AtlasEntityStoreV1.java | 2 +
.../graph/v1/AtlasTypeDefGraphStoreV1.java | 34 +-
.../repository/migration/HiveParititionIT.java | 103 +
.../repository/migration/HiveStocksIT.java | 102 +
.../migration/MigrationBaseAsserts.java | 143 +
.../migration/RelationshipMappingTest.java | 86 +
.../store/graph/v1/AtlasEntityStoreV1Test.java | 3 +
.../graph/v1/AtlasRelationshipStoreV1Test.java | 1 +
.../atlas/utils/TestResourceFileUtils.java | 5 +
.../parts_db/atlas-migration-data.json | 1 +
.../parts_db/atlas-migration-typesdef.json | 1 +
.../resources/stocks-2-0.8-extended-tag.json | 5156 ++++++++++++++++++
repository/src/test/resources/stocks-2.zip | Bin 0 -> 4240 bytes
.../atlas/web/filters/ActiveServerFilter.java | 12 +
.../atlas/web/resources/AdminResource.java | 76 +-
.../atlas/web/security/AtlasSecurityConfig.java | 13 +-
.../apache/atlas/web/service/ServiceState.java | 28 +-
.../atlas/web/resources/AdminResourceTest.java | 4 +-
47 files changed, 8008 insertions(+), 134 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/common/src/main/java/org/apache/atlas/AtlasConstants.java
----------------------------------------------------------------------
diff --git a/common/src/main/java/org/apache/atlas/AtlasConstants.java b/common/src/main/java/org/apache/atlas/AtlasConstants.java
index f5de1df..2b92e6e 100644
--- a/common/src/main/java/org/apache/atlas/AtlasConstants.java
+++ b/common/src/main/java/org/apache/atlas/AtlasConstants.java
@@ -34,4 +34,7 @@ public final class AtlasConstants {
public static final String DEFAULT_ATLAS_REST_ADDRESS = "http://localhost:21000";
public static final int ATLAS_SHUTDOWN_HOOK_PRIORITY = 30;
public static final String DEFAULT_TYPE_VERSION = "1.0";
+
+ public static final String ATLAS_MIGRATION_MODE_FILENAME = "atlas.migration.mode.filename";
+ public static final String ATLAS_SERVICES_ENABLED = "atlas.services.enabled";
}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/common/src/main/java/org/apache/atlas/repository/Constants.java
----------------------------------------------------------------------
diff --git a/common/src/main/java/org/apache/atlas/repository/Constants.java b/common/src/main/java/org/apache/atlas/repository/Constants.java
index 310dddb..01e4915 100644
--- a/common/src/main/java/org/apache/atlas/repository/Constants.java
+++ b/common/src/main/java/org/apache/atlas/repository/Constants.java
@@ -124,6 +124,9 @@ public final class Constants {
public static final String CLASSIFICATION_EDGE_STATE_PROPERTY_KEY = STATE_PROPERTY_KEY;
public static final String CLASSIFICATION_LABEL = "classifiedAs";
+ public static final String VERTEX_ID_IN_IMPORT_KEY = "__vIdInImport";
+ public static final String EDGE_ID_IN_IMPORT_KEY = "__eIdInImport";
+
private Constants() {
}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/common/src/main/java/org/apache/atlas/service/Services.java
----------------------------------------------------------------------
diff --git a/common/src/main/java/org/apache/atlas/service/Services.java b/common/src/main/java/org/apache/atlas/service/Services.java
index 1267dc9..7b36db5 100644
--- a/common/src/main/java/org/apache/atlas/service/Services.java
+++ b/common/src/main/java/org/apache/atlas/service/Services.java
@@ -6,9 +6,9 @@
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,6 +19,7 @@ package org.apache.atlas.service;
import org.apache.atlas.annotation.AtlasService;
import org.apache.commons.configuration.Configuration;
+import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
@@ -28,6 +29,9 @@ import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.util.List;
+import static org.apache.atlas.AtlasConstants.ATLAS_MIGRATION_MODE_FILENAME;
+import static org.apache.atlas.AtlasConstants.ATLAS_SERVICES_ENABLED;
+
/**
* Utility for starting and stopping all services.
*/
@@ -35,45 +39,65 @@ import java.util.List;
@Profile("!test")
public class Services {
public static final Logger LOG = LoggerFactory.getLogger(Services.class);
+ private static final String DATA_MIGRATION_CLASS_NAME_DEFAULT = "DataMigrationService";
private final List<Service> services;
- private final Configuration configuration;
+ private final String dataMigrationClassName;
+ private final boolean servicesEnabled;
+ private final boolean migrationEnabled;
@Inject
public Services(List<Service> services, Configuration configuration) {
- this.services = services;
- this.configuration = configuration;
+ this.services = services;
+ this.dataMigrationClassName = configuration.getString("atlas.migration.class.name", DATA_MIGRATION_CLASS_NAME_DEFAULT);
+ this.servicesEnabled = configuration.getBoolean(ATLAS_SERVICES_ENABLED, true);
+ this.migrationEnabled = StringUtils.isNotEmpty(configuration.getString(ATLAS_MIGRATION_MODE_FILENAME));
}
@PostConstruct
public void start() {
- if (configuration.getBoolean("atlas.services.enabled", true)) {
- try {
- for (Service service : services) {
- LOG.info("Starting service {}", service.getClass().getName());
-
- service.start();
+ try {
+ for (Service svc : services) {
+ if (!isServiceUsed(svc)) {
+ continue;
}
- } catch (Exception e) {
- throw new RuntimeException(e);
+
+ LOG.info("Starting service {}", svc.getClass().getName());
+
+ svc.start();
}
+ } catch (Exception e) {
+ throw new RuntimeException(e);
}
}
@PreDestroy
public void stop() {
- if (configuration.getBoolean("atlas.services.enabled", true)) {
- for (int idx = services.size() - 1; idx >= 0; idx--) {
- Service service = services.get(idx);
+ for (int idx = services.size() - 1; idx >= 0; idx--) {
+ Service svc = services.get(idx);
+ try {
+ if (!isServiceUsed(svc)) {
+ continue;
+ }
- LOG.info("Stopping service {}", service.getClass().getName());
+ LOG.info("Stopping service {}", svc.getClass().getName());
- try {
- service.stop();
- } catch (Throwable e) {
- LOG.warn("Error stopping service {}", service.getClass().getName(), e);
- }
+ svc.stop();
+ } catch (Throwable e) {
+ LOG.warn("Error stopping service {}", svc.getClass().getName(), e);
}
}
}
+
+ private boolean isServiceUsed(Service service) {
+ if (isDataMigrationService(service)) {
+ return migrationEnabled;
+ } else {
+ return !migrationEnabled && servicesEnabled;
+ }
+ }
+
+ private boolean isDataMigrationService(Service svc) {
+ return svc.getClass().getSimpleName().equals(dataMigrationClassName);
+ }
}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraph.java
----------------------------------------------------------------------
diff --git a/graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraph.java b/graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraph.java
index 31d2085..f252dc3 100644
--- a/graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraph.java
+++ b/graphdb/api/src/main/java/org/apache/atlas/repository/graphdb/AtlasGraph.java
@@ -18,6 +18,7 @@
package org.apache.atlas.repository.graphdb;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Set;
@@ -317,4 +318,6 @@ public interface AtlasGraph<V, E> {
* @return
*/
boolean isMultiProperty(String name);
+
+ void loadLegacyGraphSON(Map<String, String> relationshipCache, InputStream fs) throws AtlasBaseException;
}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraph.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraph.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraph.java
index 6820a93..fdef800 100644
--- a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraph.java
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraph.java
@@ -64,6 +64,7 @@ import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
@@ -464,4 +465,9 @@ public class AtlasJanusGraph implements AtlasGraph<AtlasJanusVertex, AtlasJanusE
}
}
}
+
+ @Override
+ public void loadLegacyGraphSON(Map<String, String> relationshipCache, InputStream fs) throws AtlasBaseException {
+ AtlasJanusGraphDatabase.loadLegacyGraphSON(relationshipCache, fs);
+ }
}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraphDatabase.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraphDatabase.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraphDatabase.java
index a006020..c9407bb 100644
--- a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraphDatabase.java
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/AtlasJanusGraphDatabase.java
@@ -20,13 +20,16 @@ package org.apache.atlas.repository.graphdb.janus;
import org.apache.atlas.ApplicationProperties;
import org.apache.atlas.AtlasException;
+import org.apache.atlas.exception.AtlasBaseException;
import org.apache.atlas.repository.graphdb.AtlasGraph;
import org.apache.atlas.repository.graphdb.GraphDatabase;
+import org.apache.atlas.repository.graphdb.janus.migration.AtlasGraphSONReader;
import org.apache.atlas.repository.graphdb.janus.serializer.BigDecimalSerializer;
import org.apache.atlas.repository.graphdb.janus.serializer.BigIntegerSerializer;
import org.apache.atlas.repository.graphdb.janus.serializer.TypeCategorySerializer;
import org.apache.atlas.runner.LocalSolrRunner;
import org.apache.atlas.typesystem.types.DataTypes.TypeCategory;
+import org.apache.atlas.utils.AtlasPerfTracer;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
import org.janusgraph.graphdb.database.serialize.attribute.SerializableSerializer;
@@ -35,22 +38,22 @@ import org.slf4j.LoggerFactory;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.janusgraph.graphdb.tinkerpop.JanusGraphIoRegistry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
+import java.util.Map;
/**
* Default implementation for Graph Provider that doles out Titan Graph.
*/
public class AtlasJanusGraphDatabase implements GraphDatabase<AtlasJanusVertex, AtlasJanusEdge> {
+ private static final Logger LOG = LoggerFactory.getLogger(AtlasJanusGraphDatabase.class);
+ private static final Logger PERF_LOG = AtlasPerfTracer.getPerfLogger("AtlasJanusGraphDatabase");
- private static final Logger LOG = LoggerFactory.getLogger(AtlasJanusGraphDatabase.class);
/**
* Constant for the configuration property that indicates the prefix.
@@ -116,6 +119,20 @@ public class AtlasJanusGraphDatabase implements GraphDatabase<AtlasJanusVertex,
return graphInstance;
}
+ public static JanusGraph getBulkLoadingGraphInstance() {
+ try {
+ Configuration cfg = getConfiguration();
+ cfg.setProperty("storage.batch-loading", true);
+ return JanusGraphFactory.open(cfg);
+ } catch (IllegalArgumentException ex) {
+ LOG.error("getBulkLoadingGraphInstance: Failed!", ex);
+ } catch (AtlasException ex) {
+ LOG.error("getBulkLoadingGraphInstance: Failed!", ex);
+ }
+
+ return null;
+ }
+
public static void unload() {
synchronized (AtlasJanusGraphDatabase.class) {
@@ -215,4 +232,31 @@ public class AtlasJanusGraphDatabase implements GraphDatabase<AtlasJanusVertex,
return ret;
}
+
+ public static void loadLegacyGraphSON(Map<String, String> relationshipCache, InputStream fs) throws AtlasBaseException {
+ AtlasPerfTracer perf = null;
+
+ try {
+ LOG.info("Starting loadLegacyGraphSON...");
+
+ if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
+ perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "loadLegacyGraphSON");
+ }
+
+ AtlasGraphSONReader legacyGraphSONReader = AtlasGraphSONReader.build().
+ relationshipCache(relationshipCache).
+ schemaDB(getGraphInstance()).
+ bulkLoadingDB(getBulkLoadingGraphInstance()).create();
+
+ legacyGraphSONReader.readGraph(fs);
+ } catch (Exception ex) {
+ LOG.error("Error loading loadLegacyGraphSON2", ex);
+
+ throw new AtlasBaseException(ex);
+ } finally {
+ AtlasPerfTracer.log(perf);
+
+ LOG.info("Done! loadLegacyGraphSON.");
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/AtlasGraphSONReader.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/AtlasGraphSONReader.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/AtlasGraphSONReader.java
new file mode 100644
index 0000000..099e6b9
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/AtlasGraphSONReader.java
@@ -0,0 +1,314 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.atlas.ApplicationProperties;
+import org.apache.atlas.AtlasException;
+import org.apache.atlas.repository.graphdb.janus.migration.JsonNodeParsers.ParseElement;
+import org.apache.atlas.repository.graphdb.janus.migration.JsonNodeProcessManager.WorkItemManager;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper;
+import org.apache.tinkerpop.shaded.jackson.core.JsonFactory;
+import org.apache.tinkerpop.shaded.jackson.core.JsonParser;
+import org.apache.tinkerpop.shaded.jackson.core.JsonToken;
+import org.apache.tinkerpop.shaded.jackson.databind.JsonNode;
+import org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper;
+import org.janusgraph.core.JanusGraph;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+public final class AtlasGraphSONReader {
+ private static final Logger LOG = LoggerFactory.getLogger(AtlasGraphSONReader.class);
+
+ private final ObjectMapper mapper;
+ private final RelationshipTypeCache relationshipCache;
+ private final Graph graph;
+ private final Graph bulkLoadGraph;
+ private final int numWorkers;
+ private final int batchSize;
+ private final long suppliedStartIndex;
+ private final String[] propertiesToPostProcess;
+ private GraphSONUtility graphSONUtility;
+ private ReaderStatusManager readerStatusManager;
+ private AtomicLong counter;
+
+ private AtlasGraphSONReader(ObjectMapper mapper, Map<String, String> relationshipLookup, Graph graph,
+ Graph bulkLoadGraph, String[] propertiesToPostProcess, int numWorkers, int batchSize, long suppliedStartIndex) {
+ this.mapper = mapper;
+ this.relationshipCache = new RelationshipTypeCache(relationshipLookup);
+ this.graph = graph;
+ this.bulkLoadGraph = bulkLoadGraph;
+ this.numWorkers = numWorkers;
+ this.batchSize = batchSize;
+ this.suppliedStartIndex = suppliedStartIndex;
+ this.propertiesToPostProcess = propertiesToPostProcess;
+ }
+
+ public void readGraph(final InputStream inputStream) throws IOException {
+ counter = new AtomicLong(0);
+ graphSONUtility = new GraphSONUtility(relationshipCache);
+
+ final long startIndex = initStatusManager();
+ final JsonFactory factory = mapper.getFactory();
+
+ LOG.info("AtlasGraphSONReader.readGraph: numWorkers: {}: batchSize: {}: startIndex: {}", numWorkers, batchSize, startIndex);
+ try (JsonParser parser = factory.createParser(inputStream)) {
+ if (parser.nextToken() != JsonToken.START_OBJECT) {
+ throw new IOException("Expected data to start with an Object");
+ }
+
+ readerStatusManager.update(bulkLoadGraph, counter.get(), ReaderStatusManager.STATUS_IN_PROGRESS);
+
+ while (parser.nextToken() != JsonToken.END_OBJECT) {
+ final String fieldName = parser.getCurrentName() == null ? "" : parser.getCurrentName();
+
+ switch (fieldName) {
+ case GraphSONTokensTP2.MODE:
+ parser.nextToken();
+
+ final String mode = parser.getText();
+
+ if (!mode.equals("EXTENDED")) {
+ throw new IllegalStateException("The legacy GraphSON must be generated with GraphSONMode.EXTENDED");
+ }
+ break;
+
+ case GraphSONTokensTP2.VERTICES:
+ processElement(parser, new JsonNodeParsers.ParseVertex(), startIndex);
+ break;
+
+ case GraphSONTokensTP2.EDGES:
+ processElement(parser, new JsonNodeParsers.ParseEdge(), startIndex);
+ break;
+
+ default:
+ throw new IllegalStateException(String.format("Unexpected token in GraphSON - %s", fieldName));
+ }
+ }
+
+ postProcess(startIndex);
+
+ readerStatusManager.end(bulkLoadGraph, counter.get(), ReaderStatusManager.STATUS_SUCCESS);
+ } catch (Exception ex) {
+ readerStatusManager.end(bulkLoadGraph, counter.get(), ReaderStatusManager.STATUS_FAILED);
+ throw new IOException(ex);
+ } finally {
+ LOG.info("AtlasGraphSONReader.readGraph: Done!: {}", counter.get());
+ }
+ }
+
+ private long initStatusManager() {
+ readerStatusManager = new ReaderStatusManager(graph, bulkLoadGraph);
+
+ return (this.suppliedStartIndex == 0) ? readerStatusManager.getStartIndex() : this.suppliedStartIndex;
+ }
+
+ private void processElement(JsonParser parser, ParseElement parseElement, long startIndex) throws InterruptedException {
+ try {
+ parseElement.setContext(graphSONUtility);
+
+ WorkItemManager wim = JsonNodeProcessManager.create(graph, bulkLoadGraph, parseElement, numWorkers, batchSize, startIndex);
+
+ parser.nextToken();
+
+ while (parser.nextToken() != JsonToken.END_ARRAY) {
+ handleInterrupt(bulkLoadGraph, counter.incrementAndGet());
+
+ final JsonNode node = parser.readValueAsTree();
+
+ if (shouldSkip(startIndex, counter.get()) || parseElement.isTypeNode(node)) {
+ continue;
+ }
+
+ updateStatusConditionally(bulkLoadGraph, counter.get());
+
+ wim.produce(node);
+ }
+
+ wim.shutdown();
+ } catch (InterruptedException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ LOG.error("processElement: {}: failed!", parseElement.getMessage(), ex);
+ } finally {
+ LOG.info("processElement: {}: Done! : [{}]", parseElement.getMessage(), counter);
+
+ readerStatusManager.update(bulkLoadGraph, counter.get());
+ }
+ }
+
+ private void postProcess(long startIndex) {
+ LOG.info("postProcess: Starting...");
+
+ try {
+ PostProcessManager.WorkItemsManager wim = PostProcessManager.create(bulkLoadGraph, graphSONUtility,
+ propertiesToPostProcess, batchSize, numWorkers);
+ GraphTraversal query = bulkLoadGraph.traversal().V();
+
+ while (query.hasNext()) {
+ handleInterrupt(bulkLoadGraph, counter.incrementAndGet());
+
+ if(shouldSkip(startIndex, counter.get())) {
+ continue;
+ }
+
+ Vertex v = (Vertex) query.next();
+
+ updateStatusConditionally(bulkLoadGraph, counter.get());
+
+ wim.produce(v.id());
+ }
+
+ wim.shutdown();
+ } catch (Exception ex) {
+ LOG.error("postProcess: failed!", ex);
+ } finally {
+ LOG.info("postProcess: Done! : [{}]", counter.get());
+
+ readerStatusManager.update(bulkLoadGraph, counter.get());
+ }
+ }
+
+ private boolean shouldSkip(long startIndex, long index) {
+ return (startIndex != 0) && (index <= startIndex);
+ }
+
+ private void handleInterrupt(Graph graph, long counter) throws InterruptedException {
+ if (!Thread.interrupted()) {
+ return;
+ }
+
+ readerStatusManager.update(graph, counter);
+ LOG.error("Thread interrupted: {}", counter);
+ throw new InterruptedException();
+ }
+
+ private void updateStatusConditionally(Graph graph, long counter) {
+ if(counter % batchSize == 0) {
+ readerStatusManager.update(graph, counter);
+ }
+ }
+
+ public static Builder build() throws AtlasException {
+ return new Builder();
+ }
+
+ public final static class Builder {
+ private int batchSize = 500;
+ private Map<String, String> relationshipCache;
+ private Graph graph;
+ private Graph bulkLoadGraph;
+ private int numWorkers;
+ private long suppliedStartIndex;
+ private String[] propertiesToPostProcess;
+
+ private Builder() {
+ }
+
+ private void setDefaults() throws AtlasException {
+ this.startIndex(ApplicationProperties.get().getLong("atlas.migration.mode.start.index", 0L))
+ .numWorkers(ApplicationProperties.get().getInt("atlas.migration.mode.workers", 4))
+ .batchSize(ApplicationProperties.get().getInt("atlas.migration.mode.batch.size", 3000))
+ .propertiesToPostProcess(getPropertiesToPostProcess("atlas.migration.mode.postprocess.properties"));
+ }
+
+ public AtlasGraphSONReader create() throws AtlasException {
+ setDefaults();
+ if(bulkLoadGraph == null) {
+ bulkLoadGraph = graph;
+ }
+
+ final GraphSONMapper.Builder builder = GraphSONMapper.build();
+ final GraphSONMapper mapper = builder.embedTypes(false).create();
+
+ return new AtlasGraphSONReader(mapper.createMapper(), relationshipCache, graph, bulkLoadGraph,
+ propertiesToPostProcess, numWorkers, batchSize, suppliedStartIndex);
+ }
+
+ public Builder relationshipCache(Map<String, String> relationshipCache) {
+ this.relationshipCache = relationshipCache;
+
+ return this;
+ }
+
+ public Builder schemaDB(JanusGraph graph) {
+ this.graph = graph;
+
+ return this;
+ }
+
+ public Builder bulkLoadingDB(Graph graph) {
+ this.bulkLoadGraph = graph;
+
+ return this;
+ }
+
+ public Builder numWorkers(int numWorkers) {
+ if(bulkLoadGraph == null || graph == null) {
+ this.numWorkers = 1;
+
+ LOG.info("numWorkers: {}, since one of the 2 graphs is null.", this.numWorkers);
+ } else {
+ this.numWorkers = numWorkers;
+ }
+
+ return this;
+ }
+
+ public Builder batchSize(int batchSize) {
+ this.batchSize = batchSize;
+
+ return this;
+ }
+
+ public Builder startIndex(long suppliedStartIndex) {
+ this.suppliedStartIndex = suppliedStartIndex;
+
+ return this;
+ }
+
+ public Builder propertiesToPostProcess(String[] list) {
+ this.propertiesToPostProcess = list;
+ return this;
+ }
+
+ private static String[] getPropertiesToPostProcess(String applicationPropertyKey) throws AtlasException {
+ final String HIVE_COLUMNS_PROPERTY = "hive_table.columns";
+ final String HIVE_PARTITION_KEYS_PROPERTY = "hive_table.partitionKeys";
+ final String PROCESS_INPUT_PROPERTY = "Process.inputs";
+ final String PROCESS_OUTPUT_PROPERTY = "Process.outputs";
+ final String USER_PROFILE_OUTPUT_PROPERTY = "__AtlasUserProfile.savedSearches";
+
+ String[] defaultProperties = new String[] { HIVE_COLUMNS_PROPERTY, HIVE_PARTITION_KEYS_PROPERTY,
+ PROCESS_INPUT_PROPERTY, PROCESS_OUTPUT_PROPERTY,
+ USER_PROFILE_OUTPUT_PROPERTY
+ };
+
+ String[] userDefinedList = ApplicationProperties.get().getStringArray(applicationPropertyKey);
+
+ return (userDefinedList == null || userDefinedList.length == 0) ? defaultProperties : userDefinedList;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONTokensTP2.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONTokensTP2.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONTokensTP2.java
new file mode 100644
index 0000000..e8b0758
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONTokensTP2.java
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+public final class GraphSONTokensTP2 {
+ public static final String _ID = "_id";
+ public static final String _LABEL = "_label";
+ public static final String _TYPE = "_type";
+ public static final String _OUT_V = "_outV";
+ public static final String _IN_V = "_inV";
+ public static final String VALUE = "value";
+ public static final String TYPE = "type";
+ public static final String TYPE_LIST = "list";
+ public static final String TYPE_STRING = "string";
+ public static final String TYPE_DOUBLE = "double";
+ public static final String TYPE_INTEGER = "integer";
+ public static final String TYPE_FLOAT = "float";
+ public static final String TYPE_MAP = "map";
+ public static final String TYPE_BOOLEAN = "boolean";
+ public static final String TYPE_LONG = "long";
+ public static final String TYPE_SHORT = "short";
+ public static final String TYPE_BYTE = "byte";
+ public static final String TYPE_UNKNOWN = "unknown";
+ public static final String VERTICES = "vertices";
+ public static final String EDGES = "edges";
+ public static final String MODE = "mode";
+
+ private GraphSONTokensTP2() {
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONUtility.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONUtility.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONUtility.java
new file mode 100644
index 0000000..5120935
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/GraphSONUtility.java
@@ -0,0 +1,326 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.apache.atlas.repository.Constants;
+import org.apache.commons.lang.StringUtils;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Graph.Features.EdgeFeatures;
+import org.apache.tinkerpop.gremlin.structure.Graph.Features.VertexFeatures;
+import org.apache.tinkerpop.gremlin.structure.T;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.shaded.jackson.databind.JsonNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.*;
+
+import static org.apache.atlas.repository.Constants.CLASSIFICATION_EDGE_STATE_PROPERTY_KEY;
+import static org.apache.atlas.repository.Constants.CLASSIFICATION_ENTITY_GUID;
+import static org.apache.atlas.repository.Constants.RELATIONSHIPTYPE_TAG_PROPAGATION_KEY;
+
+class GraphSONUtility {
+ private static final Logger LOG = LoggerFactory.getLogger(GraphSONUtility.class);
+
+ private static final String EMPTY_STRING = "";
+
+ private final RelationshipTypeCache relationshipTypeCache;
+
+ public GraphSONUtility(final RelationshipTypeCache relationshipTypeCache) {
+ this.relationshipTypeCache = relationshipTypeCache;
+ }
+
+ public Map<String, Object> vertexFromJson(Graph g, final JsonNode json) {
+ final Map<String, Object> props = readProperties(json);
+
+ if (props.containsKey(Constants.TYPENAME_PROPERTY_KEY)) {
+ return null;
+ }
+
+ Map<String, Object> schemaUpdate = null;
+ VertexFeatures vertexFeatures = g.features().vertex();
+ Object vertexId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID));
+ Vertex vertex = vertexFeatures.willAllowId(vertexId) ? g.addVertex(T.id, vertexId) : g.addVertex();
+
+ props.put(Constants.VERTEX_ID_IN_IMPORT_KEY, vertexId);
+
+ for (Map.Entry<String, Object> entry : props.entrySet()) {
+ try {
+ vertex.property(vertexFeatures.getCardinality(entry.getKey()), entry.getKey(), entry.getValue());
+ } catch (IllegalArgumentException ex) {
+ schemaUpdate = getSchemaUpdateMap(schemaUpdate);
+
+ if (!schemaUpdate.containsKey("id")) {
+ schemaUpdate.put("id", vertex.id());
+ }
+
+ schemaUpdate.put(entry.getKey(), entry.getValue());
+ }
+ }
+
+ return schemaUpdate;
+ }
+
+ public Map<String, Object> edgeFromJson(Graph g, MappedElementCache cache, final JsonNode json) {
+ final JsonNode nodeLabel = json.get(GraphSONTokensTP2._LABEL);
+ String label = nodeLabel == null ? EMPTY_STRING : nodeLabel.textValue();
+
+ if (label.startsWith("__type.")) {
+ return null;
+ }
+
+ Map<String, Object> schemaUpdate = null;
+ Object edgeId = null;
+
+ try {
+ final Vertex in = getMappedVertex(g, cache, json, GraphSONTokensTP2._IN_V);
+ final Vertex out = getMappedVertex(g, cache, json, GraphSONTokensTP2._OUT_V);
+
+ if (in == null || out == null) {
+ return null;
+ }
+
+ edgeId = getTypedValueFromJsonNode(json.get(GraphSONTokensTP2._ID));
+
+ final Map<String, Object> props = GraphSONUtility.readProperties(json);
+
+ props.put(Constants.EDGE_ID_IN_IMPORT_KEY, edgeId.toString());
+
+ if(addRelationshipTypeForClassification(in, out, label, props)) {
+ label = Constants.CLASSIFICATION_LABEL;
+ } else {
+ addRelationshipTypeName(label, props);
+ }
+
+ EdgeFeatures edgeFeatures = g.features().edge();
+ final Edge edge = edgeFeatures.willAllowId(edgeId) ? out.addEdge(label, in, T.id, edgeId) : out.addEdge(label, in);
+
+ addMandatoryRelationshipProperties(props);
+
+ for (Map.Entry<String, Object> entry : props.entrySet()) {
+ try {
+ edge.property(entry.getKey(), entry.getValue());
+ } catch (IllegalArgumentException ex) {
+ schemaUpdate = getSchemaUpdateMap(schemaUpdate);
+
+ if (!schemaUpdate.containsKey("id")) {
+ schemaUpdate.put("id", edge.id());
+ }
+
+ schemaUpdate.put(entry.getKey(), entry.getValue());
+ }
+ }
+ } catch(IllegalArgumentException ex) {
+ schemaUpdate = getSchemaUpdateMap(schemaUpdate);
+ schemaUpdate.put("oid", edgeId);
+ }
+
+ return schemaUpdate;
+ }
+
+ private Map<String, Object> getSchemaUpdateMap(Map<String, Object> schemaUpdate) {
+ if(schemaUpdate == null) {
+ schemaUpdate = new HashMap<>();
+ }
+
+ return schemaUpdate;
+ }
+
+ private Vertex getMappedVertex(Graph gr, MappedElementCache cache, JsonNode json, String direction) {
+ Object inVId = GraphSONUtility.getTypedValueFromJsonNode(json.get(direction));
+
+ return cache.getMappedVertex(gr, inVId);
+ }
+
+ private boolean addRelationshipTypeForClassification(Vertex in, Vertex out, String label, Map<String, Object> props) {
+ if (in.property(Constants.ENTITY_TYPE_PROPERTY_KEY).isPresent()) {
+ String inTypeName = (String) in.property(Constants.ENTITY_TYPE_PROPERTY_KEY).value();
+
+ if (inTypeName.equals(label)) {
+ if (StringUtils.isNotEmpty(inTypeName)) {
+ props.put(Constants.ENTITY_TYPE_PROPERTY_KEY, inTypeName);
+
+ addEntityGuidToTrait(in, out);
+
+ return true;
+ } else {
+ LOG.info("Could not find typeName for trait: {}", label);
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private void addEntityGuidToTrait(Vertex in, Vertex out) {
+ String entityGuid = "";
+ if (out.property(Constants.GUID_PROPERTY_KEY).isPresent()) {
+ entityGuid = (String) out.property(Constants.GUID_PROPERTY_KEY).value();
+ }
+
+ if(StringUtils.isNotEmpty(entityGuid)) {
+ in.property(CLASSIFICATION_ENTITY_GUID, entityGuid);
+ }
+ }
+
+ private void addRelationshipTypeName(String edgeLabel, Map<String, Object> props) {
+ String typeName = relationshipTypeCache.get(edgeLabel);
+
+ if (StringUtils.isNotEmpty(typeName)) {
+ props.put(Constants.ENTITY_TYPE_PROPERTY_KEY, typeName);
+ } else {
+ LOG.debug("Could not find relationship type for: {}", edgeLabel);
+ }
+ }
+
+ private void addMandatoryRelationshipProperties(Map<String, Object> props) {
+ props.put(Constants.RELATIONSHIP_GUID_PROPERTY_KEY, UUID.randomUUID().toString());
+ props.put(RELATIONSHIPTYPE_TAG_PROPAGATION_KEY, "NONE");
+ props.put(CLASSIFICATION_EDGE_STATE_PROPERTY_KEY, "ACTIVE");
+ }
+
+ public void replaceReferencedEdgeIdForList(Graph g, MappedElementCache cache, Vertex v, String propertyName) {
+ try {
+ if (v.property(Constants.TYPENAME_PROPERTY_KEY).isPresent() || !v.property(propertyName).isPresent()) {
+ return;
+ }
+
+ List list = (List) v.property(propertyName).value();
+ for (int i = 0; i < list.size(); i++) {
+ String id = list.get(i).toString();
+ Object newId = cache.getMappedEdge(g, id);
+
+ if (newId == null) {
+ continue;
+ }
+
+ list.set(i, newId.toString());
+ }
+
+ v.property(propertyName, list);
+ } catch (IllegalArgumentException ex) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("processItem: IllegalArgumentException: v[{}] error!", v.id(), ex);
+ }
+ }
+ }
+
+ static Map<String, Object> readProperties(final JsonNode node) {
+ final Map<String, Object> map = new HashMap<>();
+ final Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
+
+ while (iterator.hasNext()) {
+ final Map.Entry<String, JsonNode> entry = iterator.next();
+
+ if (!isReservedKey(entry.getKey())) {
+ // it generally shouldn't be as such but graphson containing null values can't be shoved into
+ // element property keys or it will result in error
+ final Object o = readProperty(entry.getValue());
+
+ if (o != null) {
+ map.put(entry.getKey(), o);
+ }
+ }
+ }
+
+ return map;
+ }
+
+ private static boolean isReservedKey(final String key) {
+ return key.equals(GraphSONTokensTP2._ID) || key.equals(GraphSONTokensTP2._TYPE) || key.equals(GraphSONTokensTP2._LABEL)
+ || key.equals(GraphSONTokensTP2._OUT_V) || key.equals(GraphSONTokensTP2._IN_V);
+ }
+
+ private static Object readProperty(final JsonNode node) {
+ final Object propertyValue;
+
+ if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_UNKNOWN)) {
+ propertyValue = null;
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_BOOLEAN)) {
+ propertyValue = node.get(GraphSONTokensTP2.VALUE).booleanValue();
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_FLOAT)) {
+ propertyValue = Float.parseFloat(node.get(GraphSONTokensTP2.VALUE).asText());
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_BYTE)) {
+ propertyValue = Byte.parseByte(node.get(GraphSONTokensTP2.VALUE).asText());
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_SHORT)) {
+ propertyValue = Short.parseShort(node.get(GraphSONTokensTP2.VALUE).asText());
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_DOUBLE)) {
+ propertyValue = node.get(GraphSONTokensTP2.VALUE).doubleValue();
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_INTEGER)) {
+ propertyValue = node.get(GraphSONTokensTP2.VALUE).intValue();
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_LONG)) {
+ propertyValue = node.get(GraphSONTokensTP2.VALUE).longValue();
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_STRING)) {
+ propertyValue = node.get(GraphSONTokensTP2.VALUE).textValue();
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_LIST)) {
+ propertyValue = readProperties(node.get(GraphSONTokensTP2.VALUE).elements());
+ } else if (node.get(GraphSONTokensTP2.TYPE).textValue().equals(GraphSONTokensTP2.TYPE_MAP)) {
+ propertyValue = readProperties(node.get(GraphSONTokensTP2.VALUE));
+ } else {
+ propertyValue = node.textValue();
+ }
+
+ return propertyValue;
+ }
+
+ private static List readProperties(final Iterator<JsonNode> listOfNodes) {
+ final List<Object> array = new ArrayList<>();
+
+ while (listOfNodes.hasNext()) {
+ array.add(readProperty(listOfNodes.next()));
+ }
+
+ return array;
+ }
+
+ @VisibleForTesting
+ static Object getTypedValueFromJsonNode(final JsonNode node) {
+ Object theValue = null;
+
+ if (node != null && !node.isNull()) {
+ if (node.isBoolean()) {
+ theValue = node.booleanValue();
+ } else if (node.isDouble()) {
+ theValue = node.doubleValue();
+ } else if (node.isFloatingPointNumber()) {
+ theValue = node.floatValue();
+ } else if (node.isInt()) {
+ theValue = node.intValue();
+ } else if (node.isLong()) {
+ theValue = node.longValue();
+ } else if (node.isTextual()) {
+ theValue = node.textValue();
+ } else if (node.isArray()) {
+ // this is an array so just send it back so that it can be
+ // reprocessed to its primitive components
+ theValue = node;
+ } else if (node.isObject()) {
+ // this is an object so just send it back so that it can be
+ // reprocessed to its primitive components
+ theValue = node;
+ } else {
+ theValue = node.textValue();
+ }
+ }
+
+ return theValue;
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeParsers.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeParsers.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeParsers.java
new file mode 100644
index 0000000..acf8cb2
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeParsers.java
@@ -0,0 +1,199 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.atlas.repository.Constants;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.shaded.jackson.databind.JsonNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+
+import static org.apache.atlas.repository.Constants.EDGE_ID_IN_IMPORT_KEY;
+import static org.apache.atlas.repository.Constants.VERTEX_ID_IN_IMPORT_KEY;
+
+public class JsonNodeParsers {
+ private static final Logger LOG = LoggerFactory.getLogger(JsonNodeParsers.class);
+
+
+ static abstract class ParseElement {
+ protected GraphSONUtility utility;
+
+ abstract String getMessage();
+
+ abstract Object getId(JsonNode node);
+
+ abstract boolean isTypeNode(JsonNode node);
+
+ abstract String getType(JsonNode node);
+
+ public void setContext(GraphSONUtility utility) {
+ this.utility = utility;
+ }
+
+ abstract Map<String, Object> parse(Graph gr, MappedElementCache cache, JsonNode Node);
+
+ public void commit(Graph graph) {
+ graph.tx().commit();
+ }
+
+ abstract Element get(Graph gr, Object id);
+
+ abstract Element getByOriginalId(Graph gr, Object id);
+
+ public Element getByOriginalId(Graph gr, JsonNode node) {
+ return getByOriginalId(gr, getId(node));
+ }
+
+ public Element update(Graph gr, Object id, Map<String,Object> schema) {
+ Element el = get(gr, id);
+
+ for (Map.Entry<String, Object> entry : schema.entrySet()) {
+ el.property(entry.getKey(), entry.getValue());
+ }
+
+ return el;
+ }
+
+ static Object getTypedValueFromJsonNode(final JsonNode node) {
+ Object theValue = null;
+
+ if (node != null && !node.isNull()) {
+ if (node.isBoolean()) {
+ theValue = node.booleanValue();
+ } else if (node.isDouble()) {
+ theValue = node.doubleValue();
+ } else if (node.isFloatingPointNumber()) {
+ theValue = node.floatValue();
+ } else if (node.isInt()) {
+ theValue = node.intValue();
+ } else if (node.isLong()) {
+ theValue = node.longValue();
+ } else if (node.isTextual()) {
+ theValue = node.textValue();
+ } else if (node.isArray()) {
+ // this is an array so just send it back so that it can be
+ // reprocessed to its primitive components
+ theValue = node;
+ } else if (node.isObject()) {
+ // this is an object so just send it back so that it can be
+ // reprocessed to its primitive components
+ theValue = node;
+ } else {
+ theValue = node.textValue();
+ }
+ }
+
+ return theValue;
+ }
+ }
+
+ static class ParseEdge extends ParseElement {
+ private static final String MESSAGE_EDGE = "edge";
+ private static final String TYPE_NAME_NODE_NAME = Constants.VERTEX_TYPE_PROPERTY_KEY;
+
+
+ @Override
+ public String getMessage() {
+ return MESSAGE_EDGE;
+ }
+
+ @Override
+ Object getId(JsonNode node) {
+ return getTypedValueFromJsonNode(node.get(GraphSONTokensTP2._ID));
+ }
+
+ @Override
+ public Map<String, Object> parse(Graph gr, MappedElementCache cache, JsonNode node) {
+ return utility.edgeFromJson(gr, cache, node);
+ }
+
+ @Override
+ Element get(Graph gr, Object id) {
+ return gr.edges(id).next();
+ }
+
+ @Override
+ Element getByOriginalId(Graph gr, Object id) {
+ try {
+ return gr.traversal().E().has(EDGE_ID_IN_IMPORT_KEY, id).next();
+ } catch (Exception ex) {
+ LOG.error("fetchEdge: fetchFromDB failed: {}", id);
+ return null;
+ }
+ }
+
+ @Override
+ public boolean isTypeNode(JsonNode node) {
+ return node.get(GraphSONTokensTP2._LABEL).textValue().startsWith(Constants.TYPENAME_PROPERTY_KEY);
+ }
+
+ @Override
+ public String getType(JsonNode node) {
+ return node.get(GraphSONTokensTP2._LABEL).textValue();
+ }
+ }
+
+ static class ParseVertex extends ParseElement {
+ private static final String NODE_VALUE_KEY = "value";
+ private static final String MESSAGE_VERTEX = "vertex";
+
+ @Override
+ public String getMessage() {
+ return MESSAGE_VERTEX;
+ }
+
+ @Override
+ Object getId(JsonNode node) {
+ return getTypedValueFromJsonNode(node.get(GraphSONTokensTP2._ID));
+ }
+
+ @Override
+ public Map<String, Object> parse(Graph graph, MappedElementCache cache, JsonNode node) {
+ return utility.vertexFromJson(graph, node);
+ }
+
+ @Override
+ Element get(Graph gr, Object id) {
+ return gr.vertices(id).next();
+ }
+
+ @Override
+ Element getByOriginalId(Graph gr, Object id) {
+ try {
+ return gr.traversal().V().has(VERTEX_ID_IN_IMPORT_KEY, id).next();
+ } catch (Exception ex) {
+ LOG.error("getByOriginalId failed: {}", id);
+ return null;
+ }
+ }
+
+ @Override
+ public boolean isTypeNode(JsonNode node) {
+ return node.has(Constants.TYPENAME_PROPERTY_KEY);
+ }
+
+ @Override
+ public String getType(JsonNode node) {
+ return node.has(Constants.ENTITY_TYPE_PROPERTY_KEY) ? node.get(Constants.ENTITY_TYPE_PROPERTY_KEY).get(NODE_VALUE_KEY).toString() : "";
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeProcessManager.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeProcessManager.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeProcessManager.java
new file mode 100644
index 0000000..c1e9d20
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/JsonNodeProcessManager.java
@@ -0,0 +1,222 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.tinkerpop.shaded.jackson.databind.JsonNode;
+import org.apache.atlas.repository.graphdb.janus.migration.pc.WorkItemBuilder;
+import org.apache.atlas.repository.graphdb.janus.migration.pc.WorkItemConsumer;
+import org.apache.atlas.repository.graphdb.janus.migration.JsonNodeParsers.ParseElement;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.concurrent.BlockingQueue;
+
+public class JsonNodeProcessManager {
+ private static class Consumer extends WorkItemConsumer<JsonNode> {
+ private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
+
+ private static final int WAIT_DURATION_AFTER_COMMIT_EXCEPTION = 1000;
+
+ private final Graph graph;
+ protected final Graph bulkLoadGraph;
+ protected final ParseElement parseElement;
+ private final long batchSize;
+ private long counter;
+ private final MappedElementCache cache;
+ private final List<JsonNode> nodes = new ArrayList<>();
+
+ public Consumer(BlockingQueue<JsonNode> workQueue, Graph graph, Graph bulkLoadGraph, ParseElement parseElement, long batchSize) {
+ super(workQueue);
+
+ this.graph = graph;
+ this.bulkLoadGraph = bulkLoadGraph;
+ this.parseElement = parseElement;
+ this.batchSize = batchSize;
+ this.counter = 0;
+ this.cache = new MappedElementCache();
+ }
+
+ @Override
+ public void processItem(JsonNode node) {
+ try {
+ Map<String, Object> result = parseElement.parse(bulkLoadGraph, cache, node);
+
+ if (result == null) {
+ nodes.add(node);
+ commitConditionally(counter++);
+ } else {
+ commitBulk();
+ cache.clearAll();
+ updateSchema(result, node);
+ }
+ } catch (Exception ex) {
+ bulkLoadGraph.tx().rollback();
+ error("Failed! Retrying...", ex);
+ retryBatchCommit();
+ }
+ }
+
+ @Override
+ protected void commitDirty() {
+ super.commitDirty();
+ cache.clearAll();
+ }
+
+ @Override
+ protected void doCommit() {
+ commitBulk();
+ }
+
+ private void commitConditionally(long index) {
+ if (index % batchSize == 0 && nodes.size() > 0) {
+ commitBulk();
+ }
+ }
+
+ private void commitBulk() {
+ commit(bulkLoadGraph, nodes.size());
+ nodes.clear();
+ }
+
+ private void commitRegular() {
+ commit(graph, nodes.size());
+ }
+
+ private void commit(Graph g, int size) {
+ parseElement.commit(g);
+ display("commit-size: {}: Done!", size);
+ }
+
+ private void updateSchema(Map<String, Object> schema, org.apache.tinkerpop.shaded.jackson.databind.JsonNode node) {
+ synchronized (graph) {
+ String typeName = parseElement.getType(node);
+
+ try {
+ display("updateSchema: type: {}: ...", typeName);
+
+ if (schema.containsKey("oid")) {
+ parseElement.parse(graph, cache, node);
+ } else {
+ Object id = schema.get("id");
+ schema.remove("id");
+ parseElement.update(graph, id, schema);
+ }
+
+ commitRegular();
+
+ display("updateSchema: type: {}: Done!", typeName);
+ } catch (NoSuchElementException ex) {
+ parseElement.parse(graph, cache, node);
+ commitRegular();
+ display("updateSchema: NoSuchElementException processed!: type: {}: Done!", typeName);
+ } catch (Exception ex) {
+ graph.tx().rollback();
+ error("updateSchema: failed!: type: " + typeName, ex);
+ }
+ }
+ }
+
+ private void retryBatchCommit() {
+ display("Waiting with [{} nodes] for 1 secs.", nodes.size());
+
+ try {
+ Thread.sleep(WAIT_DURATION_AFTER_COMMIT_EXCEPTION);
+ for (org.apache.tinkerpop.shaded.jackson.databind.JsonNode n : nodes) {
+ parseElement.parse(bulkLoadGraph, cache, n);
+ }
+ commitBulk();
+ display("Done!: After re-adding {}.", nodes.size());
+ } catch (Exception ex) {
+ error("retryBatchCommit: Failed! Potential data loss.", ex);
+ }
+ }
+
+ private void display(String message, Object s1, Object s2) {
+ LOG.info("{}: [{}]: " + message, parseElement.getMessage(), counter, s1, s2);
+ }
+
+ private void display(String message, Object s1) {
+ display(message, s1, "");
+ }
+
+ private void error(String message, Exception ex) {
+ LOG.error("{}: [{}]: " + message, parseElement.getMessage(), counter, ex);
+ }
+ }
+
+ private static class ResumingConsumer extends Consumer {
+ public ResumingConsumer(BlockingQueue<JsonNode> workQueue, Graph graph, Graph bulkLoadGraph, ParseElement parseElement, long batchSize) {
+ super(workQueue, graph, bulkLoadGraph, parseElement, batchSize);
+ }
+
+ @Override
+ public void processItem(JsonNode node) {
+ if (!contains(node)) {
+ super.processItem(node);
+ }
+ }
+
+ private boolean contains(JsonNode node) {
+ return (parseElement.getByOriginalId(bulkLoadGraph, node) != null);
+ }
+ }
+
+ private static class ConsumerBuilder implements WorkItemBuilder<Consumer, JsonNode> {
+ private final Graph graph;
+ private final Graph bulkLoadGraph;
+ private final ParseElement parseElement;
+ private final int batchSize;
+ private final long startIndex;
+
+ public ConsumerBuilder(Graph graph, Graph bulkLoadGraph, ParseElement parseElement, int batchSize, long startIndex) {
+ this.graph = graph;
+ this.bulkLoadGraph = bulkLoadGraph;
+ this.batchSize = batchSize;
+ this.parseElement = parseElement;
+ this.startIndex = startIndex;
+ }
+
+ @Override
+ public Consumer build(BlockingQueue<JsonNode> queue) {
+ if(startIndex == 0) {
+ return new Consumer(queue, graph, bulkLoadGraph, parseElement, batchSize);
+ }
+
+ return new ResumingConsumer(queue, graph, bulkLoadGraph, parseElement, batchSize);
+ }
+ }
+
+ static class WorkItemManager extends org.apache.atlas.repository.graphdb.janus.migration.pc.WorkItemManager {
+ public WorkItemManager(WorkItemBuilder builder, int batchSize, int numWorkers) {
+ super(builder, batchSize, numWorkers);
+ }
+ }
+
+ public static WorkItemManager create(Graph rGraph, Graph bGraph,
+ ParseElement parseElement, int numWorkers, int batchSize, long startIndex) {
+ ConsumerBuilder cb = new ConsumerBuilder(rGraph, bGraph, parseElement, batchSize, startIndex);
+
+ return new WorkItemManager(cb, batchSize, numWorkers);
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/MappedElementCache.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/MappedElementCache.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/MappedElementCache.java
new file mode 100644
index 0000000..fe9e327
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/MappedElementCache.java
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.atlas.utils.LruCache;
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+
+import static org.apache.atlas.repository.Constants.EDGE_ID_IN_IMPORT_KEY;
+import static org.apache.atlas.repository.Constants.VERTEX_ID_IN_IMPORT_KEY;
+
+public class MappedElementCache {
+ private static final Logger LOG = LoggerFactory.getLogger(MappedElementCache.class);
+
+ private final Map<Object, Vertex> lruVertexCache = new LruCache<>(500, 100000);
+ private final Map<String, String> lruEdgeCache = new LruCache<>(500, 100000);
+
+ public Vertex getMappedVertex(Graph gr, Object key) {
+ try {
+ Vertex ret = lruVertexCache.get(key);
+
+ if (ret == null) {
+ synchronized (lruVertexCache) {
+ ret = lruVertexCache.get(key);
+
+ if(ret == null) {
+ ret = fetchVertex(gr, key);
+ lruVertexCache.put(key, ret);
+ }
+ }
+ }
+
+ return ret;
+ } catch (Exception ex) {
+ LOG.error("getMappedVertex: {}", key, ex);
+ return null;
+ }
+ }
+
+ public String getMappedEdge(Graph gr, String key) {
+ try {
+ String ret = lruEdgeCache.get(key);
+
+ if (ret == null) {
+ synchronized (lruEdgeCache) {
+ ret = lruEdgeCache.get(key);
+
+ if (ret == null) {
+ Edge e = fetchEdge(gr, key);
+
+ ret = e.id().toString();
+
+ lruEdgeCache.put(key, ret);
+ }
+ }
+ }
+
+ return ret;
+ } catch (Exception ex) {
+ LOG.error("getMappedEdge: {}", key, ex);
+ return null;
+ }
+ }
+
+ private Vertex fetchVertex(Graph gr, Object key) {
+ try {
+ return gr.traversal().V().has(VERTEX_ID_IN_IMPORT_KEY, key).next();
+ } catch (Exception ex) {
+ LOG.error("fetchVertex: fetchFromDB failed: {}", key);
+ return null;
+ }
+ }
+
+ private Edge fetchEdge(Graph gr, String key) {
+ try {
+ return gr.traversal().E().has(EDGE_ID_IN_IMPORT_KEY, key).next();
+ } catch (Exception ex) {
+ LOG.error("fetchEdge: fetchFromDB failed: {}", key);
+ return null;
+ }
+ }
+
+ public void clearVertexCache() {
+ lruVertexCache.clear();
+ }
+
+ public void clearEdgeCache() {
+ lruEdgeCache.clear();
+ }
+
+ public void clearAll() {
+ clearVertexCache();
+ clearEdgeCache();
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/PostProcessManager.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/PostProcessManager.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/PostProcessManager.java
new file mode 100644
index 0000000..4c5e357
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/PostProcessManager.java
@@ -0,0 +1,117 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.atlas.repository.graphdb.janus.migration.pc.WorkItemBuilder;
+import org.apache.atlas.repository.graphdb.janus.migration.pc.WorkItemConsumer;
+import org.apache.atlas.repository.graphdb.janus.migration.pc.WorkItemManager;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.BlockingQueue;
+
+public class PostProcessManager {
+ private static class Consumer extends WorkItemConsumer<Object> {
+ private static final Logger LOG = LoggerFactory.getLogger(Consumer.class);
+
+ private final Graph bulkLoadGraph;
+ private final GraphSONUtility utility;
+ private final String[] properties;
+ private final MappedElementCache cache;
+ private final int batchSize;
+ private long counter;
+ private long batchCounter;
+
+ public Consumer(BlockingQueue<Object> queue, Graph bulkLoadGraph, GraphSONUtility utility,
+ String[] properties, MappedElementCache cache, int batchSize) {
+ super(queue);
+
+ this.bulkLoadGraph = bulkLoadGraph;
+ this.utility = utility;
+ this.properties = properties;
+ this.cache = cache;
+ this.batchSize = batchSize;
+ this.counter = 0;
+ this.batchCounter = 0;
+ }
+
+ @Override
+ public void processItem(Object vertexId) {
+ batchCounter++;
+ counter++;
+
+ try {
+ Vertex v = bulkLoadGraph.traversal().V(vertexId).next();
+
+ for (String p : properties) {
+ utility.replaceReferencedEdgeIdForList(bulkLoadGraph, cache, v, p);
+ }
+
+ if (batchCounter >= batchSize) {
+ LOG.info("[{}]: batch: {}: commit", counter, batchCounter);
+ commit();
+ batchCounter = 0;
+ }
+ }
+ catch (Exception ex) {
+ LOG.error("processItem: v[{}] error!", vertexId, ex);
+ }
+ }
+
+ @Override
+ protected void doCommit() {
+ bulkLoadGraph.tx().commit();
+ }
+ }
+
+ private static class ConsumerBuilder implements WorkItemBuilder<Consumer, Object> {
+ private final Graph bulkLoadGraph;
+ private final GraphSONUtility utility;
+ private final int batchSize;
+ private final MappedElementCache cache;
+ private final String[] vertexPropertiesToPostProcess;
+
+ public ConsumerBuilder(Graph bulkLoadGraph, GraphSONUtility utility, String[] propertiesToPostProcess, int batchSize) {
+ this.bulkLoadGraph = bulkLoadGraph;
+ this.utility = utility;
+ this.batchSize = batchSize;
+ this.cache = new MappedElementCache();
+ this.vertexPropertiesToPostProcess = propertiesToPostProcess;
+ }
+
+ @Override
+ public Consumer build(BlockingQueue<Object> queue) {
+ return new Consumer(queue, bulkLoadGraph, utility, vertexPropertiesToPostProcess, cache, batchSize);
+ }
+ }
+
+ static class WorkItemsManager extends WorkItemManager<Object, Consumer> {
+ public WorkItemsManager(WorkItemBuilder builder, int batchSize, int numWorkers) {
+ super(builder, batchSize, numWorkers);
+ }
+ }
+
+ public static WorkItemsManager create(Graph bGraph, GraphSONUtility utility, String[] propertiesToPostProcess, int batchSize, int numWorkers) {
+ ConsumerBuilder cb = new ConsumerBuilder(bGraph, utility, propertiesToPostProcess, batchSize);
+
+ return new WorkItemsManager(cb, batchSize, numWorkers);
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/ReaderStatusManager.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/ReaderStatusManager.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/ReaderStatusManager.java
new file mode 100644
index 0000000..67dbf22
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/ReaderStatusManager.java
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.atlas.repository.Constants;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.apache.tinkerpop.gremlin.structure.Graph;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Date;
+
+public class ReaderStatusManager {
+ private static final Logger LOG = LoggerFactory.getLogger(ReaderStatusManager.class);
+
+ private static final String MIGRATION_STATUS_TYPE_NAME = "__MigrationStatus";
+ private static final String CURRENT_INDEX_PROPERTY = "currentIndex";
+ private static final String OPERATION_STATUS_PROPERTY = "operationStatus";
+ private static final String START_TIME_PROPERTY = "startTime";
+ private static final String END_TIME_PROPERTY = "endTime";
+ private static final String TOTAL_COUNT_PROPERTY = "totalCount";
+
+ public static final String STATUS_NOT_STARTED = "NOT STARTED";
+ public static final String STATUS_IN_PROGRESS = "IN PROGRESS";
+ public static final String STATUS_SUCCESS = "SUCCESS";
+ public static final String STATUS_FAILED = "FAILED";
+
+ private Object migrationStatusId = null;
+ private Vertex migrationStatus = null;
+
+ public ReaderStatusManager(Graph graph, Graph bulkLoadGraph) {
+ init(graph, bulkLoadGraph);
+ }
+
+ public void init(Graph graph, Graph bulkLoadGraph) {
+ migrationStatus = fetchUsingTypeName(bulkLoadGraph.traversal());
+ if(migrationStatus == null) {
+ createAndCommit(graph);
+ migrationStatus = fetchUsingId(bulkLoadGraph.traversal());
+ }
+
+ if(migrationStatus == null) {
+ migrationStatus = fetchUsingId(bulkLoadGraph.traversal());
+ }
+ }
+
+ public void end(Graph bGraph, Long counter, String status) {
+ migrationStatus.property(END_TIME_PROPERTY, new Date());
+ migrationStatus.property(TOTAL_COUNT_PROPERTY, counter);
+
+ update(bGraph, counter, status);
+ }
+
+ public void update(Graph graph, Long counter) {
+ migrationStatus.property(CURRENT_INDEX_PROPERTY, counter);
+ graph.tx().commit();
+ }
+
+ public void update(Graph graph, Long counter, String status) {
+ migrationStatus.property(OPERATION_STATUS_PROPERTY, status);
+ update(graph, counter);
+ }
+
+ public void clear() {
+ migrationStatus = null;
+ }
+
+ public long getStartIndex() {
+ return (long) migrationStatus.property(CURRENT_INDEX_PROPERTY).value();
+ }
+
+ private Vertex fetchUsingId(GraphTraversalSource g) {
+ return g.V(migrationStatusId).next();
+ }
+
+ private Vertex fetchUsingTypeName(GraphTraversalSource g) {
+ GraphTraversal src = g.V().has(Constants.ENTITY_TYPE_PROPERTY_KEY, MIGRATION_STATUS_TYPE_NAME);
+ return src.hasNext() ? (Vertex) src.next() : null;
+ }
+
+ private void createAndCommit(Graph rGraph) {
+ Vertex v = rGraph.addVertex();
+
+ long longValue = 0L;
+ v.property(Constants.ENTITY_TYPE_PROPERTY_KEY, MIGRATION_STATUS_TYPE_NAME);
+ v.property(CURRENT_INDEX_PROPERTY, longValue);
+ v.property(TOTAL_COUNT_PROPERTY, longValue);
+ v.property(OPERATION_STATUS_PROPERTY, STATUS_NOT_STARTED);
+ v.property(START_TIME_PROPERTY, new Date());
+ v.property(END_TIME_PROPERTY, new Date());
+
+ migrationStatusId = v.id();
+
+ rGraph.tx().commit();
+
+ LOG.info("migrationStatus vertex created! v[{}]", migrationStatusId);
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/RelationshipTypeCache.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/RelationshipTypeCache.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/RelationshipTypeCache.java
new file mode 100644
index 0000000..48b3595
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/RelationshipTypeCache.java
@@ -0,0 +1,42 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+public class RelationshipTypeCache {
+ private static final Logger LOG = LoggerFactory.getLogger(RelationshipTypeCache.class);
+ private final Map<String, String> relationshipLookup;
+
+ public RelationshipTypeCache(Map<String, String> lookup) {
+ relationshipLookup = lookup;
+ }
+
+ public String get(String label) {
+ return relationshipLookup.get(label);
+ }
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemBuilder.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemBuilder.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemBuilder.java
new file mode 100644
index 0000000..257b633
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemBuilder.java
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration.pc;
+
+import java.util.concurrent.BlockingQueue;
+
+public interface WorkItemBuilder<T extends Runnable, U> {
+ T build(BlockingQueue<U> queue);
+}
http://git-wip-us.apache.org/repos/asf/atlas/blob/3ded3ee2/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemConsumer.java
----------------------------------------------------------------------
diff --git a/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemConsumer.java b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemConsumer.java
new file mode 100644
index 0000000..5de8db9
--- /dev/null
+++ b/graphdb/janus/src/main/java/org/apache/atlas/repository/graphdb/janus/migration/pc/WorkItemConsumer.java
@@ -0,0 +1,94 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.atlas.repository.graphdb.janus.migration.pc;
+
+import com.google.common.base.Stopwatch;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.TimeUnit;
+
+public abstract class WorkItemConsumer<T> implements Runnable {
+ private static final Logger LOG = LoggerFactory.getLogger(WorkItemConsumer.class);
+
+ private static final int POLLING_DURATION_SECONDS = 5;
+
+ private final BlockingQueue<T> queue;
+ private boolean isDirty = false;
+ private long maxCommitTimeSeconds = 0;
+
+ public WorkItemConsumer(BlockingQueue<T> queue) {
+ this.queue = queue;
+ }
+
+ public void run() {
+ while (!Thread.currentThread().isInterrupted()) {
+ try {
+ T item = queue.poll(POLLING_DURATION_SECONDS, TimeUnit.SECONDS);
+
+ if (item == null) {
+ commitDirty();
+ return;
+ }
+
+ isDirty = true;
+
+ processItem(item);
+ } catch (InterruptedException e) {
+ LOG.error("WorkItemConsumer: Interrupted: ", e);
+ }
+ }
+ }
+
+ public long getMaxCommitTimeSeconds() {
+ return (this.maxCommitTimeSeconds > 0 ? this.maxCommitTimeSeconds : 15);
+ }
+
+ protected void commitDirty() {
+ if (!isDirty) {
+ return;
+ }
+
+ LOG.info("isDirty");
+ commit();
+ }
+
+ protected void commit() {
+ Stopwatch sw = Stopwatch.createStarted();
+
+ doCommit();
+
+ sw.stop();
+
+ updateCommitTime(sw.elapsed(TimeUnit.SECONDS));
+
+ isDirty = false;
+ }
+
+ protected abstract void doCommit();
+
+ protected abstract void processItem(T item);
+
+ private void updateCommitTime(long commitTime) {
+ if (this.maxCommitTimeSeconds < commitTime) {
+ this.maxCommitTimeSeconds = commitTime;
+ }
+ }
+}