various Updates
[music.git] / src / main / java / org / onap / music / main / MusicCore.java
index 9605616..dfc93cc 100644 (file)
@@ -27,11 +27,15 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.StringTokenizer;
 
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.KeeperException.NoNodeException;
 import org.onap.music.datastore.MusicDataStore;
 import org.onap.music.datastore.PreparedQueryObject;
 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
 import org.onap.music.eelf.logging.EELFLoggerDelegate;
-// import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.eelf.logging.format.AppMessages;
+import org.onap.music.eelf.logging.format.ErrorSeverity;
+import org.onap.music.eelf.logging.format.ErrorTypes;
 import org.onap.music.exceptions.MusicLockingException;
 import org.onap.music.exceptions.MusicQueryException;
 import org.onap.music.exceptions.MusicServiceException;
@@ -66,7 +70,7 @@ public class MusicCore {
             this.selectQueryForTheRow = selectQueryForTheRow;
         }
 
-        public boolean testCondition() {
+        public boolean testCondition() throws Exception {
             // first generate the row
             ResultSet results = quorumGet(selectQueryForTheRow);
             Row row = results.one();
@@ -83,7 +87,7 @@ public class MusicCore {
             try {
                 mLockHandle = new MusicLockingService();
             } catch (Exception e) {
-                logger.error(EELFLoggerDelegate.errorLogger,"Failed to aquire Locl store handle" + e.getMessage());
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
                 throw new MusicLockingException("Failed to aquire Locl store handle " + e);
             }
         }
@@ -111,12 +115,24 @@ public class MusicCore {
     /**
      * 
      * @return
+     * @throws MusicServiceException 
      */
-    public static MusicDataStore getDSHandle() {
+    public static MusicDataStore getDSHandle() throws MusicServiceException {
         logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle");
         long start = System.currentTimeMillis();
         if (mDstoreHandle == null) {
-            mDstoreHandle = new MusicDataStore();
+            // Quick Fix - Best to put this into every call to getDSHandle?
+            if (! MusicUtil.getMyCassaHost().equals("localhost") ) {
+                mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
+            } else {
+                mDstoreHandle = new MusicDataStore();
+            }
+        }
+        if(mDstoreHandle.getSession() == null) {
+               String message = "Connection to Cassandra has not been enstablished."
+                               + " Please check connection properites and reboot.";
+               logger.info(EELFLoggerDelegate.applicationLogger, message);
+            throw new MusicServiceException(message);
         }
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms");
@@ -130,7 +146,8 @@ public class MusicCore {
         try {
             lockId = getLockingServiceHandle().createLockId("/" + lockName);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to create Lock Reference " + lockName);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.CREATELOCK+lockName,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+               
         }
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms");
@@ -169,7 +186,7 @@ public class MusicCore {
             logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to get lock state:" + (end - start) + " ms");
             return mls;
         } catch (NullPointerException | MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"No lock object exists as of now.." + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         return null;
     }
@@ -194,14 +211,18 @@ public class MusicCore {
                     }
                 }
             } else
-                logger.debug("There is no lock state object for " + key);
-
+               logger.error(EELFLoggerDelegate.errorLogger,key, AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+          
             /*
              * call the traditional acquire lock now and if the result returned is true, set the
              * begin time-stamp and lease period
              */
             if (acquireLock(key, lockId).getResult() == ResultType.SUCCESS) {
                 mls = getMusicLockState(key);// get latest state
+                if ( mls == null ) {
+                    logger.info(EELFLoggerDelegate.applicationLogger,"Music Lock State is null");
+                    return new ReturnType(ResultType.FAILURE, "Could not acquire lock, Lock State is null");                    
+                }
                 if (mls.getLeaseStartTime() == -1) {// set it again only if it is not set already
                     mls.setLeaseStartTime(System.currentTimeMillis());
                     mls.setLeasePeriod(leasePeriod);
@@ -217,14 +238,15 @@ public class MusicCore {
             }
         } catch (Exception e) {
             StringWriter sw = new StringWriter();
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+            
             String exceptionAsString = sw.toString();
             return new ReturnType(ResultType.FAILURE,
                             "Exception thrown in acquireLockWithLease:\n" + exceptionAsString);
         }
     }
 
-    public static ReturnType acquireLock(String key, String lockId) {
+    public static ReturnType acquireLock(String key, String lockId) throws MusicLockingException {
         /*
          * first check if I am on top. Since ids are not reusable there is no need to check
          * lockStatus If the status is unlocked, then the above call will automatically return
@@ -234,9 +256,10 @@ public class MusicCore {
         try {
             result = getLockingServiceHandle().isMyTurn(lockId);
         } catch (MusicLockingException e2) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to aquireLock lockId " + lockId + " " + e2);
+            logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId + " " + e2);
+            throw new MusicLockingException();
         }
-        if (result == false) {
+        if (!result) {
             logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Not your turn, someone else has the lock");
             try {
                                if (!getLockingServiceHandle().lockIdExists(lockId)) {
@@ -244,7 +267,8 @@ public class MusicCore {
                                        return new ReturnType(ResultType.FAILURE, "Lockid doesn't exist");
                                }
                        } catch (MusicLockingException e) {
-                               logger.error(EELFLoggerDelegate.errorLogger,"Failed to check if lockid exists - lockId " + lockId + " " + e);
+                               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+                                throw new MusicLockingException();
                        }
             logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: returning failure");
             return new ReturnType(ResultType.FAILURE, "Not your turn, someone else has the lock");
@@ -253,7 +277,7 @@ public class MusicCore {
 
         // this is for backward compatibility where locks could also be acquired on just
         // keyspaces or tables.
-        if (isTableOrKeySpaceLock(key) == true) {
+        if (isTableOrKeySpaceLock(key)) {
             logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: A table or keyspace lock so no need to perform sync...so returning true");
             return new ReturnType(ResultType.SUCCESS, "A table or keyspace lock so no need to perform sync...so returning true");
         }
@@ -270,7 +294,7 @@ public class MusicCore {
                 return new ReturnType(ResultType.SUCCESS, "You already have the lock!");
             }
         } catch (NullPointerException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"In acquire lock:No one has tried to acquire the lock yet..");
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
 
         // change status to "being locked". This state transition is necessary to ensure syncing
@@ -286,14 +310,18 @@ public class MusicCore {
         try {
             getLockingServiceHandle().setLockState(key, newMls);
         } catch (MusicLockingException e1) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + key + " " + e1);
+               logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to being_locked");
 
         // do syncing if this was a forced lock release
         if (needToSyncQuorum) {
             logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Since there was a forcible release, need to sync quorum!");
-            syncQuorum(key);
+            try {
+              syncQuorum(key);
+            } catch (Exception e) {
+              logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + e);
+            }
         }
 
         // change status to locked
@@ -303,7 +331,7 @@ public class MusicCore {
         try {
             getLockingServiceHandle().setLockState(key, newMls);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + key + " " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to locked and assigned current lock ref "
                         + lockId + " as holder");
@@ -325,7 +353,7 @@ public class MusicCore {
     }
 
 
-    private static void syncQuorum(String key) {
+    private static void syncQuorum(String key) throws Exception {
         logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---");
         String[] splitString = key.split("\\.");
         String keyspaceName = splitString[0];
@@ -346,8 +374,6 @@ public class MusicCore {
         selectQuery.appendQueryString("SELECT *  FROM " + keyspaceName + "." + tableName + " WHERE "
                         + primaryKeyName + "= ?" + ";");
         selectQuery.addValue(cqlFormattedPrimaryKeyValue);
-        // String selectQuery = "SELECT * FROM "+keyspaceName+"."+tableName+ " WHERE
-        // "+primaryKeyName+"="+cqlFormattedPrimaryKeyValue+";";
         ResultSet results = null;
         try {
             results = getDSHandle().executeCriticalGet(selectQuery);
@@ -356,7 +382,6 @@ public class MusicCore {
             ColumnDefinitions colInfo = row.getColumnDefinitions();
             int totalColumns = colInfo.size();
             int counter = 1;
-            // String fieldValueString="";
             StringBuilder fieldValueString = new StringBuilder("");
             for (Definition definition : colInfo) {
                 String colName = definition.getName();
@@ -365,7 +390,6 @@ public class MusicCore {
                 DataType colType = definition.getType();
                 Object valueObj = getDSHandle().getColValue(row, colName, colType);
                 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
-                // fieldValueString = fieldValueString+ colName+"="+valueString;
                 fieldValueString.append(colName + " = ?");
                 updateQuery.addValue(valueString);
                 if (counter != (totalColumns - 1))
@@ -375,54 +399,15 @@ public class MusicCore {
             updateQuery.appendQueryString("UPDATE " + keyspaceName + "." + tableName + " SET "
                             + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
             updateQuery.addValue(cqlFormattedPrimaryKeyValue);
-            // String updateQuery = "UPDATE "+keyspaceName+"."+tableName+" SET "+fieldValueString+"
-            // WHERE "+primaryKeyName+"="+cqlFormattedPrimaryKeyValue+";";
 
             getDSHandle().executePut(updateQuery, "critical");
         } catch (MusicServiceException | MusicQueryException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to execute update query " + updateQuery + " " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
         }
     }
 
 
-    /**
-     * this function is mainly for the benchmarks to see the effect of lock deletion.
-     * 
-     * @param keyspaceName
-     * @param tableName
-     * @param primaryKey
-     * @param queryObject
-     * @param conditionInfo
-     * @return
-     */
-    public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName,
-                    String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) {
-        long start = System.currentTimeMillis();
-        String key = keyspaceName + "." + tableName + "." + primaryKey;
-        String lockId = createLockReference(key);
-        long lockCreationTime = System.currentTimeMillis();
-        long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
-        ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod);
-        long lockAcqTime = System.currentTimeMillis();
-        if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
-            logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
-            ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey,
-                            queryObject, lockId, conditionInfo);
-            long criticalPutTime = System.currentTimeMillis();
-            deleteLock(key);
-            long lockDeleteTime = System.currentTimeMillis();
-            String timingInfo = "|lock creation time:" + (lockCreationTime - start)
-                            + "|lock accquire time:" + (lockAcqTime - lockCreationTime)
-                            + "|critical put time:" + (criticalPutTime - lockAcqTime)
-                            + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|";
-            criticalPutResult.setTimingInfo(timingInfo);
-            return criticalPutResult;
-        } else {
-            logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
-            deleteLock(key);
-            return lockAcqResult;
-        }
-    }
+
 
     /**
      * 
@@ -434,7 +419,8 @@ public class MusicCore {
         try {
             results = getDSHandle().executeCriticalGet(query);
         } catch (MusicServiceException | MusicQueryException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR);
+        
         }
         return results;
 
@@ -444,8 +430,9 @@ public class MusicCore {
      * 
      * @param results
      * @return
+     * @throws MusicServiceException 
      */
-    public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) {
+    public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) throws MusicServiceException {
         return getDSHandle().marshalData(results);
     }
 
@@ -459,7 +446,7 @@ public class MusicCore {
         try {
             return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + "";
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed whoseTurnIsIt  " + lockName + " " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         return null;
 
@@ -480,9 +467,9 @@ public class MusicCore {
         long start = System.currentTimeMillis();
         try {
             getLockingServiceHandle().unlockAndDeleteId(lockId);
-        } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to Destroy Lock Ref  " + lockId + " " + e);
-        }
+        } catch (MusicLockingException | NoNodeException e) {
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockId  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+        } 
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
     }
@@ -492,7 +479,11 @@ public class MusicCore {
         try {
             getLockingServiceHandle().unlockAndDeleteId(lockId);
         } catch (MusicLockingException e1) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + e1);
+               logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.RELEASELOCK+lockId  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+        } catch (KeeperException.NoNodeException nne) {
+                       logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + nne);
+                       MusicLockState mls = new MusicLockState("Lock doesn't exists. Release lock operation failed.");
+                       return mls;
         }
         String lockName = getLockNameFromId(lockId);
         MusicLockState mls;
@@ -509,24 +500,34 @@ public class MusicCore {
         try {
             getLockingServiceHandle().setLockState(lockName, mls);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockName + " " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.RELEASELOCK+lockId  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to release lock:" + (end - start) + " ms");
         return mls;
     }
+    
+    public static  void  voluntaryReleaseLock(String lockId) throws MusicLockingException{
+               try {
+                       getLockingServiceHandle().unlockAndDeleteId(lockId);
+               } catch (KeeperException.NoNodeException e) {
+                       // ??? No way
+               }
+       }
 
     /**
      * 
      * @param lockName
+     * @throws MusicLockingException 
      */
-    public static void deleteLock(String lockName) {
+    public static void deleteLock(String lockName) throws MusicLockingException {
         long start = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Deleting lock for " + lockName);
         try {
             getLockingServiceHandle().deleteLock("/" + lockName);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to Delete Lock " + lockName + " " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DELTELOCK+lockName  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+               throw new MusicLockingException(e.getMessage());
         }
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to delete lock:" + (end - start) + " ms");
@@ -539,8 +540,9 @@ public class MusicCore {
      * @param keyspace
      * @param tablename
      * @return
+     * @throws MusicServiceException 
      */
-    public static TableMetadata returnColumnMetadata(String keyspace, String tablename) {
+    public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException {
         return getDSHandle().returnColumnMetadata(keyspace, tablename);
     }
 
@@ -553,7 +555,7 @@ public class MusicCore {
         try {
             getLockingServiceHandle().getzkLockHandle().createNode(nodeName);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle "  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
     }
 
@@ -568,7 +570,7 @@ public class MusicCore {
         try {
             getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle "  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName);
         long end = System.currentTimeMillis();
@@ -586,7 +588,7 @@ public class MusicCore {
         try {
             data = getLockingServiceHandle().getzkLockHandle().getNodeData(nodeName);
         } catch (MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,"Failed to get ZK Lock Handle " + e);
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle "  ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
         }
         long end = System.currentTimeMillis();
         logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms");
@@ -611,7 +613,9 @@ public class MusicCore {
         try {
             result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
         } catch (MusicServiceException | MusicQueryException ex) {
+               logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle "  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
             logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + "  " + ex.getCause() + " " + ex);
+            return new ReturnType(ResultType.FAILURE, ex.getMessage());
         }
         if (result) {
             return new ReturnType(ResultType.SUCCESS, "Success");
@@ -637,10 +641,16 @@ public class MusicCore {
             MusicLockState mls = getLockingServiceHandle()
                             .getLockState(keyspaceName + "." + tableName + "." + primaryKey);
             if (mls.getLockHolder().equals(lockId) == true) {
-                if (conditionInfo != null)// check if condition is true
+                if (conditionInfo != null)
+                  try {
                     if (conditionInfo.testCondition() == false)
                         return new ReturnType(ResultType.FAILURE,
                                         "Lock acquired but the condition is not true");
+                  } catch (Exception e) {
+                    return new ReturnType(ResultType.FAILURE,
+                            "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
+                                            + e.getMessage());
+                  }
                 getDSHandle().executePut(queryObject, MusicUtil.CRITICAL);
                 long end = System.currentTimeMillis();
                 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms");
@@ -668,17 +678,17 @@ public class MusicCore {
      * 
      * 
      */
-    public static boolean nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException {
+    public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException {
         // this is mainly for some functions like keyspace creation etc which does not
         // really need the bells and whistles of Music locking.
         boolean result = false;
         try {
             result = getDSHandle().executePut(queryObject, consistency);
         } catch (MusicQueryException | MusicServiceException ex) {
-            logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage());
+               logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
             throw new MusicServiceException(ex.getMessage());
         }
-        return result;
+        return result?ResultType.SUCCESS:ResultType.FAILURE;
     }
 
     /**
@@ -721,7 +731,7 @@ public class MusicCore {
             } else
                 throw new MusicServiceException("YOU DO NOT HAVE THE LOCK");
         } catch (MusicQueryException | MusicServiceException | MusicLockingException e) {
-            logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR  ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
         }
         return results;
     }
@@ -734,22 +744,63 @@ public class MusicCore {
      * @param primaryKey primary key value
      * @param queryObject query object containing prepared query and values
      * @return ReturnType
+     * @throws MusicLockingException 
      */
     public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
-                    PreparedQueryObject queryObject, Condition conditionInfo) {
+                    PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
+
+        long start = System.currentTimeMillis();
+        String key = keyspaceName + "." + tableName + "." + primaryKey;
+        String lockId = createLockReference(key);
+        long lockCreationTime = System.currentTimeMillis();
+        ReturnType lockAcqResult = acquireLock(key, lockId);
+        long lockAcqTime = System.currentTimeMillis();
+        if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
+            logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
+            ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey,
+                            queryObject, lockId, conditionInfo);
+            long criticalPutTime = System.currentTimeMillis();
+            voluntaryReleaseLock(lockId);
+            long lockDeleteTime = System.currentTimeMillis();
+            String timingInfo = "|lock creation time:" + (lockCreationTime - start)
+                            + "|lock accquire time:" + (lockAcqTime - lockCreationTime)
+                            + "|critical put time:" + (criticalPutTime - lockAcqTime)
+                            + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|";
+            criticalPutResult.setTimingInfo(timingInfo);
+            return criticalPutResult;
+        } else {
+            logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
+            destroyLockRef(lockId);
+            return lockAcqResult;
+        }
+    }
+    
+    /**
+     * this function is mainly for the benchmarks to see the effect of lock deletion.
+     * 
+     * @param keyspaceName
+     * @param tableName
+     * @param primaryKey
+     * @param queryObject
+     * @param conditionInfo
+     * @return
+     * @throws MusicLockingException 
+     */
+    public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName,
+                    String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
+
         long start = System.currentTimeMillis();
         String key = keyspaceName + "." + tableName + "." + primaryKey;
         String lockId = createLockReference(key);
         long lockCreationTime = System.currentTimeMillis();
         long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
-        ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod);
+        ReturnType lockAcqResult = acquireLock(key, lockId);
         long lockAcqTime = System.currentTimeMillis();
         if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
             logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
             ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey,
                             queryObject, lockId, conditionInfo);
             long criticalPutTime = System.currentTimeMillis();
-            boolean voluntaryRelease = true;
             deleteLock(key);
             long lockDeleteTime = System.currentTimeMillis();
             String timingInfo = "|lock creation time:" + (lockCreationTime - start)
@@ -760,10 +811,12 @@ public class MusicCore {
             return criticalPutResult;
         } else {
             logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
-            destroyLockRef(lockId);
+            deleteLock(key);
             return lockAcqResult;
         }
     }
+    
+
 
 
     /**
@@ -775,25 +828,48 @@ public class MusicCore {
      * @param queryObject query object containing prepared query and values
      * @return ResultSet
      * @throws MusicServiceException
+     * @throws MusicLockingException 
      */
     public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
-                    PreparedQueryObject queryObject) throws MusicServiceException {
+                    PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
         String key = keyspaceName + "." + tableName + "." + primaryKey;
         String lockId = createLockReference(key);
         long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
-        ReturnType lockAcqResult = acquireLockWithLease(key, lockId, leasePeriod);
+        ReturnType lockAcqResult = acquireLock(key, lockId);
         if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
             logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
             ResultSet result =
                             criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId);
-            boolean voluntaryRelease = true;
-            releaseLock(lockId, voluntaryRelease);
+            voluntaryReleaseLock(lockId);
             return result;
         } else {
+               destroyLockRef(lockId);
             logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
             return null;
         }
     }
+    
+       public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
+                       PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
+               String key = keyspaceName + "." + tableName + "." + primaryKey;
+               String lockId = createLockReference(key);
+               long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
+
+               ReturnType lockAcqResult = acquireLock(key, lockId);
+
+               if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
+                       logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
+                       ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId);
+                       deleteLock(key);
+                       return result;
+               } else {
+                       deleteLock(key);
+                       logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
+                       return null;
+               }
+       }
+    
+    
 
     /**
      * authenticate user logic
@@ -816,34 +892,44 @@ public class MusicCore {
                         operation);
         if (!resultMap.isEmpty())
             return resultMap;
-        boolean isAAF = CachingUtil.isAAFApplication(nameSpace);
-        if (!isAAF && !(operation.equals("createKeySpace"))) {
-               if(aid == null) {
-                       resultMap.put("Exception", "Aid is mandatory for nonAAF applications ");
-                       return resultMap;
-               }
-            resultMap = CachingUtil.authenticateAIDUser(aid, keyspace);
-            if (!resultMap.isEmpty())
-                return resultMap;
+        String isAAFApp = null;
+        try {
+            isAAFApp= CachingUtil.isAAFApplication(nameSpace);
+        } catch(MusicServiceException e) {
+           resultMap.put("Exception", e.getMessage());
+           return resultMap;
+        }
+        if(isAAFApp == null) {
+            resultMap.put("Exception", "Namespace: "+nameSpace+" doesn't exist. Please make sure ns(appName)"
+                    + " is correct and Application is onboarded.");
+            return resultMap;
         }
-        if (aid == null && (userId == null || password == null)) {
+        boolean isAAF = Boolean.valueOf(isAAFApp);
+        if (userId == null || password == null) {
+               logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
             logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId
                             + " :: password: " + password);
             resultMap.put("Exception",
                             "UserId and Password are mandatory for the operation " + operation);
             return resultMap;
         }
-        
+        if(!isAAF && !(operation.equals("createKeySpace"))) {
+            resultMap = CachingUtil.authenticateAIDUser(nameSpace, userId, password, keyspace);
+            if (!resultMap.isEmpty())
+                return resultMap;
+            
+        }
         if (isAAF && nameSpace != null && userId != null && password != null) {
             boolean isValid = true;
             try {
-                isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace);
+                isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace);
             } catch (Exception e) {
+               logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
                 logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace);
                 resultMap.put("Exception", e.getMessage());
             }
             if (!isValid) {
-                logger.error(EELFLoggerDelegate.errorLogger,"User not authenticated with AAF.");
+               logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR  ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
                 resultMap.put("Exception", "User not authenticated...");
             }
             if (!resultMap.isEmpty())
@@ -870,23 +956,27 @@ public class MusicCore {
                 uuid = CachingUtil.generateUUID();
                 resultMap.put("uuid", "new");
             }
-
-            pQuery = new PreparedQueryObject();
-            pQuery.appendQueryString(
-                            "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
-                                            + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), nameSpace));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), password));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
-            pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
-            CachingUtil.updateMusicCache(uuid, keyspace);
-            MusicCore.eventualPut(pQuery);
             resultMap.put("aid", uuid);
         }
 
         return resultMap;
     }
+    
+    /**
+     * @param lockName
+     * @return
+     */
+    public static Map<String, Object> validateLock(String lockName) {
+        Map<String, Object> resultMap = new HashMap<>();
+        String[] locks = lockName.split("\\.");
+        if(locks.length < 3) {
+            resultMap.put("Exception", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
+            return resultMap;
+        }
+        String keyspace= locks[0];
+        if(keyspace.startsWith("$"))
+            keyspace = keyspace.substring(1);
+        resultMap.put("keyspace",keyspace);
+        return resultMap;
+    }
 }