Refactor Cassandra connection process 41/75041/3
authorMohammad Salehe <salehe@cs.toronto.edu>
Tue, 27 Nov 2018 00:58:30 +0000 (19:58 -0500)
committerMohammad Salehe <salehe@cs.toronto.edu>
Sat, 22 Dec 2018 20:07:11 +0000 (15:07 -0500)
Refactor MusicUtil and CassaDataStore to make
Cassandra connection initialization process
more simple and readable

Change-Id: Ied7d3e82dc86dd7d35cd513b13ff0c865dd40b4b
Issue-ID: MUSIC-148
Signed-off-by: Mohammad Salehe <salehe@cs.toronto.edu>
src/main/java/org/onap/music/datastore/MusicDataStore.java
src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java
src/main/java/org/onap/music/main/MusicUtil.java
src/main/java/org/onap/music/testruns/ComparisonPoints1.java

index 4c4e2b8..72385d1 100644 (file)
@@ -28,7 +28,6 @@ import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 
 import com.datastax.driver.core.*;
@@ -46,78 +45,32 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException;
 
 /**
  * @author nelson24
- *
- */
-/**
- * @author bharathb
- *
- */
-/**
- * @author bharathb
- *
- */
-/**
- * @author bharathb
- *
- */
-/**
- * @author bharathb
- *
- */
-/**
- * @author bharathb
- *
- */
-/**
  * @author bharathb
- *
- */
-/**
- * @author bharathb
- *
  */
 public class MusicDataStore {
 
     public static final String CONSISTENCY_LEVEL_ONE = "ONE";
     public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM";
 
+    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
+
     private Session session;
     private Cluster cluster;
 
-    /**
-     * @param session
-     */
-    public void setSession(Session session) {
-        this.session = session;
-    }
-    
-    /**
-     * @param
-     */
     public Session getSession() {
         return session;
     }
 
-    /**
-     * @param cluster
-     */
-    public void setCluster(Cluster cluster) {
-        this.cluster = cluster;
-    }
-
-
-
-    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
 
     /**
-     * 
+     * Constructs DataStore by connecting to local Cassandra
      */
     public MusicDataStore() {
-        connectToCassaCluster();
+        connectToLocalCassandraCluster();
     }
 
-
     /**
+     * Constructs DataStore by providing existing cluster and session
      * @param cluster
      * @param session
      */
@@ -127,20 +80,30 @@ public class MusicDataStore {
     }
 
     /**
-     * 
-     * @param remoteIp
+     * Constructs DataStore by connecting to provided remote Cassandra
+     * @param remoteAddress
      * @throws MusicServiceException
      */
-    public MusicDataStore(String remoteIp) {
+    public MusicDataStore(String remoteAddress) {
         try {
-            connectToCassaCluster(remoteIp);
+            connectToRemoteCassandraCluster(remoteAddress);
         } catch (MusicServiceException e) {
             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
         }
     }
 
+    private void createCassandraSession(String address) throws NoHostAvailableException {
+        cluster = Cluster.builder().withPort(9042)
+                .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
+                .addContactPoint(address).build();
+        Metadata metadata = cluster.getMetadata();
+        logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
+                + metadata.getClusterName() + " at " + address);
+        session = cluster.connect();
+    }
+
     /**
-     * 
+     *
      * @return
      */
     private ArrayList<String> getAllPossibleLocalIps() {
@@ -158,60 +121,38 @@ public class MusicDataStore {
         } catch (SocketException e) {
             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
         }catch(Exception e) {
-               logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
         }
         return allPossibleIps;
     }
 
     /**
-     * This method iterates through all available IP addresses and connects to multiple cassandra
-     * clusters.
+     * This method iterates through all available local IP addresses and tries to connect to first successful one
      */
-    private void connectToCassaCluster() {
-        Iterator<String> it = getAllPossibleLocalIps().iterator();
-        String address = "localhost";
+    private void connectToLocalCassandraCluster() {
+        ArrayList<String> localAddrs = getAllPossibleLocalIps();
+        localAddrs.add(0, "localhost");
         logger.info(EELFLoggerDelegate.applicationLogger,
                         "Connecting to cassa cluster: Iterating through possible ips:"
                                         + getAllPossibleLocalIps());
-        while (it.hasNext()) {
+        for (String address: localAddrs) {
             try {
-                cluster = Cluster.builder().withPort(9042)
-                                .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
-                                .addContactPoint(address).build();
-                Metadata metadata = cluster.getMetadata();
-                logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
-                                + metadata.getClusterName() + " at " + address);
-                session = cluster.connect();
-
+                createCassandraSession(address);
                 break;
             } catch (NoHostAvailableException e) {
-                address = it.next();
                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.HOSTUNAVAILABLE, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
             }
         }
     }
 
-    /**
-     * 
-     */
-    public void close() {
-        session.close();
-    }
-
     /**
      * This method connects to cassandra cluster on specific address.
      * 
      * @param address
      */
-    private void connectToCassaCluster(String address) throws MusicServiceException {
-        cluster = Cluster.builder().withPort(9042)
-                        .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
-                        .addContactPoint(address).build();
-        Metadata metadata = cluster.getMetadata();
-        logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
-                        + metadata.getClusterName() + " at " + address);
+    private void connectToRemoteCassandraCluster(String address) throws MusicServiceException {
         try {
-            session = cluster.connect();
+            createCassandraSession(address);
         } catch (Exception ex) {
             logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE);
             throw new MusicServiceException(
@@ -219,6 +160,13 @@ public class MusicDataStore {
         }
     }
 
+    /**
+     *
+     */
+    public void close() {
+        session.close();
+    }
+
     /**
      * 
      * @param keyspace
index a2d9386..ebd6213 100644 (file)
@@ -36,22 +36,22 @@ public class MusicDataStoreHandle {
        
         public static MusicDataStore mDstoreHandle = null;
         private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStoreHandle.class);
-       
+
     /**
-     * 
-     * @param remoteIp
+     *
+     * @param remoteAddress
      * @return
      */
-    public static MusicDataStore getDSHandle(String remoteIp) {
+    public static MusicDataStore getDSHandle(String remoteAddress) {
         logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle");
         long start = System.currentTimeMillis();
         if (mDstoreHandle == null) {
-               try {
-                       MusicUtil.loadProperties();
-               } catch (Exception e) {
-                       logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
-               }
-            mDstoreHandle = new MusicDataStore(remoteIp);
+            try {
+                MusicUtil.loadProperties();
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
+            }
+            mDstoreHandle = new MusicDataStore(remoteAddress);
         }
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms");
@@ -74,10 +74,10 @@ public class MusicDataStoreHandle {
                        logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
                }
             // Quick Fix - Best to put this into every call to getDSHandle?
-            if (! MusicUtil.getMyCassaHost().equals("localhost") ) {
-                mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
-            } else {
+            if (MusicUtil.getMyCassaHost().equals("localhost")) {
                 mDstoreHandle = new MusicDataStore();
+            } else {
+                mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
             }
         }
         if(mDstoreHandle.getSession() == null) {
index a12a090..238ec96 100755 (executable)
@@ -604,8 +604,8 @@ public class MusicUtil {
      * Given the time of write for an update in a critical section, this method provides a transformed timestamp
      * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
      * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
-     * @param the UUID lock reference associated with the write.
-     * @param the long timeOfWrite which is the actual time at which the write took place
+     * @param ordinal lock reference/ordinal associated with the write.
+     * @param timeOfWrite timestamp which is the actual time at which the write took place
      * @throws MusicServiceException
      * @throws MusicQueryException
      */
index fb51040..5b6c81d 100644 (file)
@@ -7,6 +7,7 @@ import org.onap.music.exceptions.MusicLockingException;
 import org.onap.music.exceptions.MusicQueryException;
 import org.onap.music.exceptions.MusicServiceException;
 import org.onap.music.main.MusicCore;
+import org.onap.music.main.MusicUtil;
 import org.onap.music.util.SamplerHistogramTimeMeasure;
 import org.onap.music.util.TimeMeasure;
 import org.onap.music.util.TimeMeasureInstance;
@@ -234,8 +235,11 @@ public class ComparisonPoints1
         }
     }
 
-       public static void main( String[] args ) throws Exception {
+       public static void main(String[] args) throws Exception {
            TimeMeasureInstance.setInstance(new SamplerHistogramTimeMeasure());
+           if (args.length > 0) {
+               MusicUtil.setMyCassaHost(args[0]);
+           }
            ComparisonPoints1 cp1 = new ComparisonPoints1();
            cp1.initialize();
            Thread.sleep(2000);