Upgrade SDC from Titan to Janus Graph
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / janusgraph / JanusGraphClient.java
  * ============LICENSE_END=========================================================
  */
 
-package org.openecomp.sdc.be.dao.titan;
-
-import com.thinkaurelius.titan.core.*;
-import com.thinkaurelius.titan.core.schema.ConsistencyModifier;
-import com.thinkaurelius.titan.core.schema.TitanGraphIndex;
-import com.thinkaurelius.titan.core.schema.TitanManagement;
-import com.thinkaurelius.titan.core.util.TitanCleanup;
-import com.thinkaurelius.titan.diskstorage.ResourceUnavailableException;
-import com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException;
-import com.thinkaurelius.titan.graphdb.database.idassigner.IDPoolExhaustedException;
+package org.openecomp.sdc.be.dao.janusgraph;
+
+import org.janusgraph.core.*;
+import org.janusgraph.core.schema.ConsistencyModifier;
+import org.janusgraph.core.schema.JanusGraphIndex;
+import org.janusgraph.core.schema.JanusGraphManagement;
+import org.janusgraph.diskstorage.BackendException;
+import org.janusgraph.diskstorage.ResourceUnavailableException;
+import org.janusgraph.diskstorage.locking.PermanentLockingException;
+import org.janusgraph.graphdb.database.idassigner.IDPoolExhaustedException;
 import fj.data.Either;
 import org.apache.commons.configuration.BaseConfiguration;
 import org.apache.tinkerpop.gremlin.structure.T;
 import org.apache.tinkerpop.gremlin.structure.Vertex;
 import org.openecomp.sdc.be.config.BeEcompErrorManager;
 import org.openecomp.sdc.be.config.ConfigurationManager;
-import org.openecomp.sdc.be.dao.DAOTitanStrategy;
-import org.openecomp.sdc.be.dao.TitanClientStrategy;
+import org.openecomp.sdc.be.dao.DAOJanusGraphStrategy;
+import org.openecomp.sdc.be.dao.JanusGraphClientStrategy;
 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -47,23 +47,23 @@ import java.util.HashMap;
 import java.util.concurrent.*;
 
 
-@Component("titan-client")
-public class TitanGraphClient {
-       private static Logger logger = LoggerFactory.getLogger(TitanGraphClient.class.getName());
-       private static Logger healthLogger = LoggerFactory.getLogger("titan.healthcheck");
+@Component("janusgraph-client")
+public class JanusGraphClient {
+       private static Logger logger = LoggerFactory.getLogger(JanusGraphClient.class.getName());
+       private static Logger healthLogger = LoggerFactory.getLogger("janusgraph.healthcheck");
 
        private static final String HEALTH_CHECK = GraphPropertiesDictionary.HEALTH_CHECK.getProperty();
        private static final String OK = "GOOD";
 
-       public TitanGraphClient() {
+       public JanusGraphClient() {
        }
 
        private class HealthCheckTask implements Callable<Vertex> {
                @Override
                public Vertex call() {
 
-                       TitanVertex v = (TitanVertex) graph.query().has(HEALTH_CHECK, OK).vertices().iterator().next();
-                       TitanVertexProperty<String> property = v.property("healthcheck", OK + "_" + System.currentTimeMillis());
+                       JanusGraphVertex v = (JanusGraphVertex) graph.query().has(HEALTH_CHECK, OK).vertices().iterator().next();
+                       JanusGraphVertexProperty<String> property = v.property("healthcheck", OK + "_" + System.currentTimeMillis());
                        healthLogger.trace("Health Check Node Found...{}", v.property(HEALTH_CHECK));
                        graph.tx().commit();
 
@@ -74,11 +74,11 @@ public class TitanGraphClient {
        private class HealthCheckScheduledTask implements Runnable {
                @Override
                public void run() {
-                       healthLogger.trace("Executing TITAN Health Check Task - Start");
+                       healthLogger.trace("Executing janusGraph Health Check Task - Start");
                        boolean healthStatus = isGraphOpen();
-                       healthLogger.trace("Executing TITAN Health Check Task - Status = {}", healthStatus);
+                       healthLogger.trace("Executing janusGraph Health Check Task - Status = {}", healthStatus);
                        if (healthStatus != lastHealthState) {
-                               logger.trace("TITAN  Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
+                               logger.trace("janusGraph  Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus);
                                lastHealthState = healthStatus;
                                logAlarm();
                        }
@@ -88,14 +88,14 @@ public class TitanGraphClient {
        private class ReconnectTask implements Runnable {
                @Override
                public void run() {
-                       logger.trace("Trying to reconnect to Titan...");
+                       logger.trace("Trying to reconnect to JanusGraph...");
                        if (graph == null) {
-                               createGraph(titanCfgFile);
+                               createGraph(janusGraphCfgFile);
                        }
                }
        }
 
-       private TitanGraph graph;
+       private JanusGraph graph;
 
        // Health Check Variables
 
@@ -105,7 +105,7 @@ public class TitanGraphClient {
        ExecutorService healthCheckExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
-                       return new Thread(r, "Titan-Health-Check-Thread");
+                       return new Thread(r, "JanusGraph-Health-Check-Thread");
                }
        });
        private long healthCheckReadTimeout = 2;
@@ -121,51 +121,51 @@ public class TitanGraphClient {
        @SuppressWarnings("rawtypes")
        private Future reconnectFuture;
 
-       private String titanCfgFile = null;
-       TitanClientStrategy titanClientStrategy;
+       private String janusGraphCfgFile = null;
+       JanusGraphClientStrategy janusGraphClientStrategy;
 
-       public TitanGraphClient(TitanClientStrategy titanClientStrategy) {
+       public JanusGraphClient(JanusGraphClientStrategy janusGraphClientStrategy) {
                super();
-               this.titanClientStrategy = titanClientStrategy;
+               this.janusGraphClientStrategy = janusGraphClientStrategy;
 
                // Initialize a single threaded scheduler for health-check
                this.healthCheckScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
                        @Override
                        public Thread newThread(Runnable r) {
-                               return new Thread(r, "Titan-Health-Check-Task");
+                               return new Thread(r, "JanusGraph-Health-Check-Task");
                        }
                });
 
-               healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanHealthCheckReadTimeout(2);
-               reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration().getTitanReconnectIntervalInSeconds(3);
+               healthCheckReadTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphHealthCheckReadTimeout(2);
+               reconnectInterval = ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphReconnectIntervalInSeconds(3);
 
-               logger.info("** TitanGraphClient created");
+               logger.info("** JanusGraphClient created");
        }
 
        @PostConstruct
-       public TitanOperationStatus createGraph() {
+       public JanusGraphOperationStatus createGraph() {
 
                logger.info("** createGraph started **");
 
-               if (ConfigurationManager.getConfigurationManager().getConfiguration().getTitanInMemoryGraph()) {
+               if (ConfigurationManager.getConfigurationManager().getConfiguration().getJanusGraphInMemoryGraph()) {
                        BaseConfiguration conf = new BaseConfiguration();
                        conf.setProperty("storage.backend", "inmemory");
-                       graph = TitanFactory.open(conf);
-            createTitanSchema(); 
+                       graph = JanusGraphFactory.open(conf);
+            createJanusGraphSchema();
                        logger.info("** in memory graph created");
-                       return TitanOperationStatus.OK;
+                       return JanusGraphOperationStatus.OK;
                } else {
-                       this.titanCfgFile = titanClientStrategy.getConfigFile();
-                       if (titanCfgFile == null || titanCfgFile.isEmpty()) {
-                               titanCfgFile = "config/titan.properties";
+                       this.janusGraphCfgFile = janusGraphClientStrategy.getConfigFile();
+                       if (janusGraphCfgFile == null || janusGraphCfgFile.isEmpty()) {
+                               janusGraphCfgFile = "config/janusgraph.properties";
                        }
 
                        // yavivi
                        // In case connection failed on init time, schedule a reconnect task
                        // in the BG
-                       TitanOperationStatus status = createGraph(titanCfgFile);
-                       logger.debug("Create Titan graph status {}", status);
-                       if (status != TitanOperationStatus.OK) {
+                       JanusGraphOperationStatus status = createGraph(janusGraphCfgFile);
+                       logger.debug("Create JanusGraph graph status {}", status);
+                       if (status != JanusGraphOperationStatus.OK) {
                                this.startReconnectTask();
                        }
 
@@ -178,7 +178,7 @@ public class TitanGraphClient {
        }
 
        /**
-        * This method will be invoked ONLY on init time in case Titan storage is down.
+        * This method will be invoked ONLY on init time in case JanusGraph storage is down.
         */
        private void startReconnectTask() {
                this.reconnectTask = new ReconnectTask();
@@ -186,7 +186,7 @@ public class TitanGraphClient {
                this.reconnectScheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
                        @Override
                        public Thread newThread(Runnable r) {
-                               return new Thread(r, "Titan-Reconnect-Task");
+                               return new Thread(r, "JanusGraph-Reconnect-Task");
                        }
                });
 
@@ -198,45 +198,49 @@ public class TitanGraphClient {
                if (graph != null) {
                        // graph.shutdown();
                        graph.close();
-                       TitanCleanup.clear(graph);
+                       try {
+                               JanusGraphFactory.drop(graph);
+                       } catch (BackendException e) {
+                               e.printStackTrace();
+                       }
                }
        }
 
        private boolean graphInitialized(){
-               TitanManagement graphMgmt = graph.openManagement();
+               JanusGraphManagement graphMgmt = graph.openManagement();
                return graphMgmt.containsPropertyKey(HEALTH_CHECK) && graphMgmt.containsGraphIndex(HEALTH_CHECK);
        }
        
 
-       public TitanOperationStatus createGraph(String titanCfgFile) {
-               logger.info("** open graph with {} started", titanCfgFile);
+       public JanusGraphOperationStatus createGraph(String janusGraphCfgFile) {
+               logger.info("** open graph with {} started", janusGraphCfgFile);
                try {
-                       logger.info("openGraph : try to load file {}", titanCfgFile);
-                       graph = TitanFactory.open(titanCfgFile);
+                       logger.info("openGraph : try to load file {}", janusGraphCfgFile);
+                       graph = JanusGraphFactory.open(janusGraphCfgFile);
                        if (graph.isClosed() || !graphInitialized()) {
-                               logger.error("titan graph was not initialized");
-                               return TitanOperationStatus.NOT_CREATED;
+                               logger.error("janusgraph graph was not initialized");
+                               return JanusGraphOperationStatus.NOT_CREATED;
                        }
 
                } catch (Exception e) {
                        this.graph = null;
-                       logger.info("createGraph : failed to open Titan graph with configuration file: {}", titanCfgFile);
+                       logger.info("createGraph : failed to open JanusGraph graph with configuration file: {}", janusGraphCfgFile);
                        logger.debug("createGraph : failed with exception.", e);
-                       return TitanOperationStatus.NOT_CONNECTED;
+                       return JanusGraphOperationStatus.NOT_CONNECTED;
                }
 
-               logger.info("** Titan graph created ");
+               logger.info("** JanusGraph graph created ");
 
                // Do some post creation actions
                this.onGraphOpened();
 
-               return TitanOperationStatus.OK;
+               return JanusGraphOperationStatus.OK;
        }
 
        private void onGraphOpened() {
                // if a reconnect task is running, cancel it.
                if (this.reconnectFuture != null) {
-                       logger.info("** Cancelling Titan reconnect task");
+                       logger.info("** Cancelling JanusGraph reconnect task");
                        reconnectFuture.cancel(true);
                }
 
@@ -254,72 +258,72 @@ public class TitanGraphClient {
        }
 
 
-       public Either<TitanGraph, TitanOperationStatus> getGraph() {
+       public Either<JanusGraph, JanusGraphOperationStatus> getGraph() {
                if (graph != null) {
                        return Either.left(graph);
                } else {
-                       return Either.right(TitanOperationStatus.NOT_CREATED);
+                       return Either.right(JanusGraphOperationStatus.NOT_CREATED);
                }
        }
 
-       public TitanOperationStatus commit() {
+       public JanusGraphOperationStatus commit() {
                if (graph != null) {
                        try {
                                graph.tx().commit();
-                               return TitanOperationStatus.OK;
+                               return JanusGraphOperationStatus.OK;
                        } catch (Exception e) {
-                               return handleTitanException(e);
+                               return handleJanusGraphException(e);
                        }
                } else {
-                       return TitanOperationStatus.NOT_CREATED;
+                       return JanusGraphOperationStatus.NOT_CREATED;
                }
        }
 
-       public TitanOperationStatus rollback() {
+       public JanusGraphOperationStatus rollback() {
                if (graph != null) {
                        try {
                                // graph.rollback();
                                graph.tx().rollback();
-                               return TitanOperationStatus.OK;
+                               return JanusGraphOperationStatus.OK;
                        } catch (Exception e) {
-                               return handleTitanException(e);
+                               return handleJanusGraphException(e);
                        }
                } else {
-                       return TitanOperationStatus.NOT_CREATED;
+                       return JanusGraphOperationStatus.NOT_CREATED;
                }
        }
 
-       public static TitanOperationStatus handleTitanException(Exception e) {
-               if (e instanceof TitanConfigurationException) {
-                       return TitanOperationStatus.TITAN_CONFIGURATION;
+       public static JanusGraphOperationStatus handleJanusGraphException(Exception e) {
+               if (e instanceof JanusGraphConfigurationException) {
+                       return JanusGraphOperationStatus.JANUSGRAPH_CONFIGURATION;
                }
                if (e instanceof SchemaViolationException) {
-                       return TitanOperationStatus.TITAN_SCHEMA_VIOLATION;
+                       return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION;
                }
                if (e instanceof PermanentLockingException) {
-                       return TitanOperationStatus.TITAN_SCHEMA_VIOLATION;
+                       return JanusGraphOperationStatus.JANUSGRAPH_SCHEMA_VIOLATION;
                }
                if (e instanceof IDPoolExhaustedException) {
-                       return TitanOperationStatus.GENERAL_ERROR;
+                       return JanusGraphOperationStatus.GENERAL_ERROR;
                }
                if (e instanceof InvalidElementException) {
-                       return TitanOperationStatus.INVALID_ELEMENT;
+                       return JanusGraphOperationStatus.INVALID_ELEMENT;
                }
                if (e instanceof InvalidIDException) {
-                       return TitanOperationStatus.INVALID_ID;
+                       return JanusGraphOperationStatus.INVALID_ID;
                }
                if (e instanceof QueryException) {
-                       return TitanOperationStatus.INVALID_QUERY;
+                       return JanusGraphOperationStatus.INVALID_QUERY;
                }
                if (e instanceof ResourceUnavailableException) {
-                       return TitanOperationStatus.RESOURCE_UNAVAILABLE;
+                       return JanusGraphOperationStatus.RESOURCE_UNAVAILABLE;
                }
                if (e instanceof IllegalArgumentException) {
                        // TODO check the error message??
-                       return TitanOperationStatus.ILLEGAL_ARGUMENT;
+                       return JanusGraphOperationStatus.ILLEGAL_ARGUMENT;
                }
 
-               return TitanOperationStatus.GENERAL_ERROR;
+               return JanusGraphOperationStatus.GENERAL_ERROR;
        }
 
        public boolean getHealth() {
@@ -327,7 +331,7 @@ public class TitanGraphClient {
        }
 
        private boolean isGraphOpen() {
-               healthLogger.trace("Invoking Titan health check ...");
+               healthLogger.trace("Invoking JanusGraph health check ...");
                Vertex v = null;
                if (graph != null) {
                        try {
@@ -340,7 +344,7 @@ public class TitanGraphClient {
                                if (message == null) {
                                        message = e.getClass().getName();
                                }
-                               logger.error("Titan Health Check Failed. {}", message);
+                               logger.error("JanusGraph Health Check Failed. {}", message);
                                return false;
                        }
                        return true;
@@ -351,7 +355,7 @@ public class TitanGraphClient {
 
 
        public static void main(String[] args) throws InterruptedException {
-               TitanGraphClient client = new TitanGraphClient(new DAOTitanStrategy());
+               JanusGraphClient client = new JanusGraphClient(new DAOJanusGraphStrategy());
                client.createGraph();
 
                while (true) {
@@ -363,20 +367,20 @@ public class TitanGraphClient {
        }
 
 
-       private static final String TITAN_HEALTH_CHECK_STR = "titanHealthCheck";
+       private static final String JANUSGRAPH_HEALTH_CHECK = "janusgraphHealthCheck";
 
        private void logAlarm() {
                if (lastHealthState) {
-                       BeEcompErrorManager.getInstance().logBeHealthCheckTitanRecovery(TITAN_HEALTH_CHECK_STR);
+                       BeEcompErrorManager.getInstance().logBeHealthCheckJanusGraphRecovery(JANUSGRAPH_HEALTH_CHECK);
                } else {
-                       BeEcompErrorManager.getInstance().logBeHealthCheckTitanError(TITAN_HEALTH_CHECK_STR);
+                       BeEcompErrorManager.getInstance().logBeHealthCheckJanusGraphError(JANUSGRAPH_HEALTH_CHECK);
                }
        }
        
-       private void createTitanSchema() {
+       private void createJanusGraphSchema() {
                
-               TitanManagement graphMgt = graph.openManagement();
-               TitanGraphIndex index = null;
+               JanusGraphManagement graphMgt = graph.openManagement();
+               JanusGraphIndex index = null;
                for (GraphPropertiesDictionary prop : GraphPropertiesDictionary.values()) {
                        PropertyKey propKey = null;
                        if (!graphMgt.containsPropertyKey(prop.getProperty())) {