2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * Modifications Copyright (c) 2018 IBM.
7 * ===================================================================
8 * Modifications Copyright (c) 2019 Samsung
9 * ===================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
22 * ============LICENSE_END=============================================
23 * ====================================================================
26 package org.onap.music.service.impl;
28 import java.io.StringWriter;
29 import java.util.Collections;
30 import java.util.HashSet;
31 import java.util.List;
34 import java.util.StringTokenizer;
36 import javax.ws.rs.core.MultivaluedMap;
38 import org.onap.music.datastore.Condition;
39 import org.onap.music.datastore.MusicDataStore;
40 import org.onap.music.datastore.MusicDataStoreHandle;
41 import org.onap.music.datastore.PreparedQueryObject;
42 import org.onap.music.datastore.jsonobjects.JsonDelete;
43 import org.onap.music.datastore.jsonobjects.JsonIndex;
44 import org.onap.music.datastore.jsonobjects.JsonInsert;
45 import org.onap.music.datastore.jsonobjects.JsonKeySpace;
46 import org.onap.music.datastore.jsonobjects.JsonSelect;
47 import org.onap.music.datastore.jsonobjects.JsonTable;
48 import org.onap.music.datastore.jsonobjects.JsonUpdate;
49 import org.onap.music.eelf.logging.EELFLoggerDelegate;
50 import org.onap.music.eelf.logging.format.AppMessages;
51 import org.onap.music.eelf.logging.format.ErrorSeverity;
52 import org.onap.music.eelf.logging.format.ErrorTypes;
53 import org.onap.music.exceptions.MusicDeadlockException;
54 import org.onap.music.exceptions.MusicLockingException;
55 import org.onap.music.exceptions.MusicQueryException;
56 import org.onap.music.exceptions.MusicServiceException;
57 import org.onap.music.lockingservice.cassandra.CassaLockStore;
58 import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject;
59 import org.onap.music.lockingservice.cassandra.LockType;
60 import org.onap.music.lockingservice.cassandra.MusicLockState;
61 import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
62 import org.onap.music.main.MusicUtil;
63 import org.onap.music.main.ResultType;
64 import org.onap.music.main.ReturnType;
65 import org.onap.music.service.MusicCoreService;
67 import com.datastax.driver.core.DataType;
68 import com.datastax.driver.core.ResultSet;
69 import com.datastax.driver.core.Row;
70 import com.datastax.driver.core.TableMetadata;
72 public class MusicCassaCore implements MusicCoreService {
74 private static CassaLockStore mLockHandle = null;
75 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCassaCore.class);
76 private static MusicCassaCore musicCassaCoreInstance = null;
77 private static Set<String> set = Collections.synchronizedSet(new HashSet<String>());
79 private MusicCassaCore() {
80 // not going to happen
83 public static CassaLockStore getmLockHandle() {
87 public static void setmLockHandle(CassaLockStore mLockHandle) {
88 MusicCassaCore.mLockHandle = mLockHandle;
91 public static MusicCassaCore getInstance() {
93 if(musicCassaCoreInstance == null) {
94 musicCassaCoreInstance = new MusicCassaCore();
96 return musicCassaCoreInstance;
99 public static CassaLockStore getLockingServiceHandle() throws MusicLockingException {
100 logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle");
101 long start = System.currentTimeMillis();
103 if (mLockHandle == null) {
105 mLockHandle = new CassaLockStore(MusicDataStoreHandle.getDSHandle());
106 } catch (Exception e) {
107 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
108 throw new MusicLockingException("Failed to aquire Locl store handle " + e);
111 long end = System.currentTimeMillis();
112 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire lock store handle:" + (end - start) + " ms");
116 public String createLockReferenceAtomic(String fullyQualifiedKey) throws MusicLockingException {
117 return createLockReferenceAtomic(fullyQualifiedKey, LockType.WRITE);
121 * This will be called for Atomic calls
124 public String createLockReferenceAtomic(String fullyQualifiedKey, LockType locktype) throws MusicLockingException {
125 String[] splitString = fullyQualifiedKey.split("\\.");
126 if (splitString.length < 3) {
127 throw new MusicLockingException("Missing or incorrect lock details. Check table or key name.");
129 String keyspace = splitString[0];
130 String table = splitString[1];
131 String lockName = splitString[2];
133 logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName);
136 String lockReference = null;
137 LockObject peek = null;
139 /** Lets check for an existing lock.
140 * This will allow us to limit the amount of requests going forward.
142 start = System.currentTimeMillis();
144 peek = getLockingServiceHandle().peekLockQueue(keyspace, table, lockName);
145 } catch (MusicServiceException | MusicQueryException e) {
146 //logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),e);
147 throw new MusicLockingException("Error getting lockholder info for key [" + lockName +"]:" + e.getMessage());
150 if(peek!=null && (peek.getLocktype()!=null && peek.getLocktype().equals(LockType.WRITE)) && peek.getAcquireTime()!=null && peek.getLockRef()!=null) {
151 long currentTime = System.currentTimeMillis();
152 if((currentTime-Long.parseLong(peek.getAcquireTime()))<MusicUtil.getDefaultLockLeasePeriod()){
153 //logger.info(EELFLoggerDelegate.applicationLogger,"Lock holder exists and lease not expired. Please try again for key="+lockName);
154 throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. Please try again.");
157 end = System.currentTimeMillis();
158 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to check for lock reference for key [" + lockName + "]:" + (end - start) + " ms");
160 start = System.currentTimeMillis();
161 /* We are Creating a Thread safe set and adding the key to the set.
162 * if a key exists then it wil be passed over and not go to the lock creation.
163 * If a key doesn't exist then it will set the value in the set and continue to create a lock.
165 * This will ensure that no 2 threads using the same key will be able to try to create a lock
166 * This wil in turn squash the amout of LWT Chatter in Cassandra an reduce the amount of
167 * WriteTimeoutExceptions being experiences on single keys.
169 if ( set.add(fullyQualifiedKey)) {
171 lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype,null);
172 set.remove(fullyQualifiedKey);
173 } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
174 set.remove(fullyQualifiedKey);
175 throw new MusicLockingException(e.getMessage());
176 } catch (Exception e) {
177 set.remove(fullyQualifiedKey);
179 logger.error(EELFLoggerDelegate.applicationLogger,"Exception in creatLockEnforced:"+ e.getMessage(),e);
180 throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. " + e.getMessage());
183 throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. Please try again.");
185 end = System.currentTimeMillis();
186 logger.info(EELFLoggerDelegate.debugLogger,"### Set = " + set);
187 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference for key [" + lockName + "]:" + (end - start) + " ms");
188 return lockReference;
190 //return createLockReference(fullyQualifiedKey, locktype, null);
193 public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException {
194 String[] splitString = fullyQualifiedKey.split("\\.");
195 if (splitString.length < 3) {
196 throw new MusicLockingException("Missing or incorrect lock details. Check table or key name.");
198 String keyspace = splitString[0];
199 String table = splitString[1];
200 String lockName = splitString[2];
202 logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName);
205 String lockReference = null;
207 /* Check for a Deadlock */
209 boolean deadlock = getLockingServiceHandle().checkForDeadlock(keyspace, table, lockName, locktype, owner, false);
211 MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + owner + " tried to create lock on " + keyspace + "." + table + "." + lockName);
212 e.setValues(owner, keyspace, table, lockName);
215 } catch (MusicDeadlockException e) {
216 //just threw this, no need to wrap it
218 } catch (MusicServiceException | MusicQueryException e) {
219 logger.error(EELFLoggerDelegate.applicationLogger, e);
220 throw new MusicLockingException("Unable to check for deadlock. " + e.getMessage(), e);
222 end = System.currentTimeMillis();
223 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to check for deadlock for key [" + lockName + "]:" + (end - start) + " ms");
225 start = System.currentTimeMillis();
227 lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype, owner);
228 } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
229 logger.info(EELFLoggerDelegate.applicationLogger,e.getMessage(),e);
230 throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. Please try again: " + e.getMessage());
231 } catch (Exception e) {
232 logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage(),e);
233 throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e);
235 end = System.currentTimeMillis();
236 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference for key [" + lockName + "]:" + (end - start) + " ms");
237 return lockReference;
240 public ReturnType promoteLock(String lockId) throws MusicLockingException {
241 String[] splitString = lockId.split("\\.");
242 String keyspace = splitString[0].substring(1);//remove '$'
243 String table = splitString[1];
244 String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$"));
245 String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end
247 logger.info(EELFLoggerDelegate.applicationLogger,"Attempting to promote lock " + lockId);
250 return getLockingServiceHandle().promoteLock(keyspace, table, primaryKeyValue, lockRef);
251 } catch (MusicServiceException e) {
252 throw new MusicLockingException("Unable to promote lock. ", e);
253 } catch (MusicQueryException e) {
254 throw new MusicLockingException("Unable to promote lock. ", e);
260 public ReturnType acquireLockWithLease(String fullyQualifiedKey, String lockReference, long leasePeriod)
261 throws MusicLockingException, MusicQueryException, MusicServiceException {
262 evictExpiredLockHolder(fullyQualifiedKey,leasePeriod);
263 return acquireLock(fullyQualifiedKey, lockReference);
266 private void evictExpiredLockHolder(String fullyQualifiedKey, long leasePeriod)
267 throws MusicLockingException, MusicQueryException, MusicServiceException {
268 String[] splitString = fullyQualifiedKey.split("\\.");
269 String keyspace = splitString[0];
270 String table = splitString[1];
271 String primaryKeyValue = splitString[2];
273 LockObject currentLockHolderObject = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue);
275 if (!currentLockHolderObject.getIsLockOwner()) { // no lock holder
279 * Release the lock of the previous holder if it has expired. if the update to the acquire time has
280 * not reached due to network delays, simply use the create time as the reference
282 long referenceTime = Math.max(Long.parseLong(currentLockHolderObject.getAcquireTime()),
283 Long.parseLong(currentLockHolderObject.getCreateTime()));
284 if ((System.currentTimeMillis() - referenceTime) > leasePeriod) {
285 forciblyReleaseLock(fullyQualifiedKey, currentLockHolderObject.getLockRef() + "");
286 logger.info(EELFLoggerDelegate.applicationLogger, currentLockHolderObject.getLockRef() + " forcibly released");
290 public ReturnType acquireLock(String fullyQualifiedKey, String lockId)
291 throws MusicLockingException, MusicQueryException, MusicServiceException {
292 String[] splitString = lockId.split("\\.");
293 String keyspace = splitString[0].substring(1);//remove '$'
294 String table = splitString[1];
295 String primaryKeyValue = splitString[2].substring(0, splitString[2].lastIndexOf("$"));
296 String localFullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
297 String lockRef = lockId.substring(lockId.lastIndexOf("$")+1); //lockRef is "$" to end
299 LockObject lockInfo = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue, lockRef);
301 if (!lockInfo.getIsLockOwner()) {
302 return new ReturnType(ResultType.FAILURE, lockId + " is not a lock holder");//not top of the lock store q
305 if (getLockingServiceHandle().checkForDeadlock(keyspace, table, primaryKeyValue, lockInfo.getLocktype(), lockInfo.getOwner(), true)) {
306 MusicDeadlockException e = new MusicDeadlockException("Deadlock detected when " + lockInfo.getOwner() + " tried to create lock on " + keyspace + "." + table + "." + primaryKeyValue);
307 e.setValues(lockInfo.getOwner(), keyspace, table, primaryKeyValue);
311 //check to see if the value of the key has to be synced in case there was a forceful release
312 String syncTable = keyspace+".unsyncedKeys_"+table;
313 String query = "select * from "+syncTable+" where key='"+localFullyQualifiedKey+"';";
314 PreparedQueryObject readQueryObject = new PreparedQueryObject();
315 readQueryObject.appendQueryString(query);
316 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(readQueryObject);
317 if (!results.all().isEmpty()) {
318 logger.info("In acquire lock: Since there was a forcible release, need to sync quorum!");
320 syncQuorum(keyspace, table, primaryKeyValue);
321 } catch (Exception e) {
322 StringWriter sw = new StringWriter();
323 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",
324 ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e);
325 String exceptionAsString = sw.toString();
326 return new ReturnType(ResultType.FAILURE, "Exception thrown while syncing key:\n" + exceptionAsString);
328 String cleanQuery = "delete from " + syncTable + " where key='"+localFullyQualifiedKey+"';";
329 PreparedQueryObject deleteQueryObject = new PreparedQueryObject();
330 deleteQueryObject.appendQueryString(cleanQuery);
331 MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "critical");
334 getLockingServiceHandle().updateLockAcquireTime(keyspace, table, primaryKeyValue, lockRef);
336 return new ReturnType(ResultType.SUCCESS, lockRef+" is the lock holder for the key");
343 * @param tableQueryObject
345 * @return Boolean Indicates success or failure
346 * @throws MusicServiceException
350 public ResultType createTable(String keyspace, String table, PreparedQueryObject tableQueryObject,
351 String consistency) throws MusicServiceException {
352 boolean result = false;
355 // create shadow locking table
356 result = getLockingServiceHandle().createLockQueue(keyspace, table);
358 return ResultType.FAILURE;
362 // create table to track unsynced_keys
363 table = "unsyncedKeys_" + table;
366 "CREATE TABLE IF NOT EXISTS " + keyspace + "." + table + " ( key text,PRIMARY KEY (key) );";
367 PreparedQueryObject queryObject = new PreparedQueryObject();
369 queryObject.appendQueryString(tabQuery);
371 result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual");
373 // create actual table
374 result = MusicDataStoreHandle.getDSHandle().executePut(tableQueryObject, consistency);
375 } catch (MusicQueryException | MusicServiceException | MusicLockingException ex) {
376 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN,
377 ErrorTypes.MUSICSERVICEERROR);
378 throw new MusicServiceException(ex.getMessage());
380 return result ? ResultType.SUCCESS : ResultType.FAILURE;
383 private static void syncQuorum(String keyspace, String table, String primaryKeyValue) throws Exception {
384 logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---");
385 PreparedQueryObject selectQuery = new PreparedQueryObject();
386 PreparedQueryObject updateQuery = new PreparedQueryObject();
388 // get the primary key d
389 TableMetadata tableInfo = MusicDataStoreHandle.returnColumnMetadata(keyspace, table);
390 String primaryKeyName = tableInfo.getPrimaryKey().get(0).getName(); // we only support single
392 DataType primaryKeyType = tableInfo.getPrimaryKey().get(0).getType();
393 Object cqlFormattedPrimaryKeyValue =
394 MusicUtil.convertToActualDataType(primaryKeyType, primaryKeyValue);
396 // get the row of data from a quorum
397 selectQuery.appendQueryString("SELECT * FROM " + keyspace + "." + table + " WHERE "
398 + primaryKeyName + "= ?" + ";");
399 selectQuery.addValue(cqlFormattedPrimaryKeyValue);
400 MusicUtil.writeBackToQuorum(selectQuery, primaryKeyName, updateQuery, keyspace, table,
401 cqlFormattedPrimaryKeyValue);
409 public ResultSet quorumGet(PreparedQueryObject query) {
410 ResultSet results = null;
412 results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(query);
413 } catch (MusicServiceException | MusicQueryException e) {
414 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,
415 ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR, e);
421 public String whoseTurnIsIt(String fullyQualifiedKey) {
422 String[] splitString = fullyQualifiedKey.split("\\.");
423 String keyspace = splitString[0];
424 String table = splitString[1];
425 String primaryKeyValue = splitString[2];
427 LockObject lockOwner = getLockingServiceHandle().peekLockQueue(keyspace, table, primaryKeyValue);
428 if (!lockOwner.getIsLockOwner()) {
431 return "$" + fullyQualifiedKey + "$" + lockOwner.getLockRef();
432 } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
433 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.LOCKINGERROR + fullyQualifiedKey,
434 ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
439 public List<String> getCurrentLockHolders(String fullyQualifiedKey) {
440 String[] splitString = fullyQualifiedKey.split("\\.");
441 String keyspace = splitString[0];
442 String table = splitString[1];
443 String primaryKeyValue = splitString[2];
445 return getLockingServiceHandle().getCurrentLockHolders(keyspace, table, primaryKeyValue);
446 } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
447 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+fullyQualifiedKey ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
454 * @param lockReference
457 public static String getLockNameFromId(String lockReference) {
458 StringTokenizer st = new StringTokenizer(lockReference);
459 return st.nextToken("$");
463 public void destroyLockRef(String lockId) throws MusicLockingException {
464 long start = System.currentTimeMillis();
465 String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
466 String lockRef = lockId.substring(lockId.lastIndexOf('$')+1);
467 String[] splitString = fullyQualifiedKey.split("\\.");
468 String keyspace = splitString[0];
469 String table = splitString[1];
470 String primaryKeyValue = splitString[2];
472 getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockRef,MusicUtil.getRetryCount());
473 } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
474 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockRef,
475 ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR, e);
476 throw new MusicLockingException(e.getMessage());
478 long end = System.currentTimeMillis();
479 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
482 public MusicLockState destroyLockRef(String fullyQualifiedKey, String lockReference) throws MusicLockingException {
483 long start = System.currentTimeMillis();
484 String[] splitString = fullyQualifiedKey.split("\\.");
485 String keyspace = splitString[0];
486 String table = splitString[1];
487 String primaryKeyValue = splitString[2];
489 getLockingServiceHandle().deQueueLockRef(keyspace, table, primaryKeyValue, lockReference,MusicUtil.getRetryCount());
490 } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
491 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK + lockReference,
492 ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR,e);
493 throw new MusicLockingException(e.getMessage());
495 long end = System.currentTimeMillis();
496 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
497 return new MusicLockState(LockStatus.UNLOCKED, "");
501 public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException {
502 String fullyQualifiedKey = lockId.substring(1, lockId.lastIndexOf("$"));
503 String lockRef = lockId.substring(lockId.lastIndexOf('$')+1);
504 if (voluntaryRelease) {
505 return voluntaryReleaseLock(fullyQualifiedKey, lockRef);
507 return forciblyReleaseLock(fullyQualifiedKey, lockRef);
511 public MusicLockState voluntaryReleaseLock(String fullyQualifiedKey, String lockReference)
512 throws MusicLockingException {
513 MusicLockState result = null;
515 result = destroyLockRef(fullyQualifiedKey, lockReference);
516 } catch (Exception ex) {
517 logger.info(EELFLoggerDelegate.applicationLogger,
518 "Exception in voluntaryReleaseLock() for " + fullyQualifiedKey + "ref: " + lockReference);
519 throw new MusicLockingException(ex.getMessage());
524 public MusicLockState forciblyReleaseLock(String fullyQualifiedKey, String lockReference) throws MusicLockingException {
525 String[] splitString = fullyQualifiedKey.split("\\.");
526 String keyspace = splitString[0];
527 String table = splitString[1];
529 //leave a signal that this key could potentially be unsynchronized
530 String syncTable = keyspace+".unsyncedKeys_"+table;
531 PreparedQueryObject queryObject = new PreparedQueryObject();
532 String values = "(?)";
533 queryObject.addValue(fullyQualifiedKey);
534 String insQuery = "insert into "+syncTable+" (key) values "+values+";";
535 queryObject.appendQueryString(insQuery);
537 MusicDataStoreHandle.getDSHandle().executePut(queryObject, "critical");
538 } catch (Exception e) {
539 logger.error("Cannot forcibly release lock: " + fullyQualifiedKey + " " + lockReference + ". "
540 + e.getMessage(), e);
543 //now release the lock
544 return destroyLockRef(fullyQualifiedKey, lockReference);
548 public List<String> releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException {
549 // System.out.println("IN RELEASEALLLOCKSFOROWNER, ");
551 List<String> lockIds = getLockingServiceHandle().getAllLocksForOwner(ownerId, keyspace, table);
552 for (String lockId : lockIds) {
553 // System.out.println(" LOCKID = " + lockId);
554 //return "$" + keyspace + "." + table + "." + lockName + "$" + String.valueOf(lockRef);
555 releaseLock("$" + keyspace + "." + table + "." + lockId, true);
563 * @throws MusicLockingException
566 public void deleteLock(String lockName) throws MusicLockingException {
567 throw new MusicLockingException("Depreciated Method Delete Lock");
570 // Prepared Query Additions.
576 * @throws MusicServiceException
578 public ReturnType eventualPut(PreparedQueryObject queryObject) {
579 boolean result = false;
581 result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
582 } catch (MusicServiceException | MusicQueryException ex) {
583 logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
584 logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex);
585 return new ReturnType(ResultType.FAILURE, ex.getMessage());
588 return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed");
590 return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform");
598 * @throws MusicServiceException
600 public ReturnType eventualPut_nb(PreparedQueryObject queryObject,String keyspace,String tablename,String primaryKey) {
601 boolean result = false;
603 PreparedQueryObject getGaurd = new PreparedQueryObject();
604 getGaurd.appendQueryString("SELECT guard FROM "+keyspace+".lockq_"+tablename+ " WHERE key = ? ;");
605 getGaurd.addValue(primaryKey);
607 ResultSet getGaurdResult = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(getGaurd);
608 Row row = getGaurdResult.one();
610 guard = row.getLong("guard");
611 long timeOfWrite = System.currentTimeMillis();
612 long ts = MusicUtil.v2sTimeStampInMicroseconds(guard, timeOfWrite);
613 String query = queryObject.getQuery();
614 if (!queryObject.getQuery().contains("USING TIMESTAMP")) {
615 if (queryObject.getOperation().equalsIgnoreCase("delete"))
616 query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE ");
618 query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET");
620 queryObject.replaceQueryString(query);
623 } catch (MusicServiceException | MusicQueryException e) {
624 logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage(), e);
627 result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
628 } catch (MusicServiceException | MusicQueryException ex) {
629 logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(),"[ERR512E] Failed to get Lock Handle ",
630 ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
631 logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " ", ex);
632 return new ReturnType(ResultType.FAILURE, ex.getMessage());
635 return new ReturnType(ResultType.SUCCESS, "Eventual Operation Successfully performed");
637 return new ReturnType(ResultType.FAILURE, "Eventual Operation failed to perform");
645 * @param primaryKeyValue
650 public ReturnType criticalPut(String keyspace, String table, String primaryKeyValue,
651 PreparedQueryObject queryObject, String lockId, Condition conditionInfo) {
652 long start = System.currentTimeMillis();
654 String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$"));
655 if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) {
656 return new ReturnType(ResultType.FAILURE,"Lock value '" + keyLock + "' and key value '"
657 + primaryKeyValue + "' not match. Please check your values: "
660 LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue,
661 lockId.substring(lockId.lastIndexOf("$") + 1));
663 if ( lockObject == null ) {
664 return new ReturnType(ResultType.FAILURE, lockId + " does not exist.");
665 } else if (!lockObject.getIsLockOwner()) {
666 return new ReturnType(ResultType.FAILURE, lockId + " is not the lock holder");
667 } else if (lockObject.getLocktype() != LockType.WRITE) {
668 return new ReturnType(ResultType.FAILURE,
669 "Attempting to do write operation, but " + lockId + " is a read lock");
672 if (conditionInfo != null) {
674 if (conditionInfo.testCondition() == false)
675 return new ReturnType(ResultType.FAILURE, "Lock acquired but the condition is not true");
676 } catch (Exception e) {
677 logger.error(EELFLoggerDelegate.errorLogger, e);
678 return new ReturnType(ResultType.FAILURE,
679 "Exception thrown while checking the condition, check its sanctity:\n" + e.getMessage());
682 String query = queryObject.getQuery();
683 long timeOfWrite = System.currentTimeMillis();
684 long lockOrdinal = Long.parseLong(lockId.substring(lockId.lastIndexOf("$") + 1));
685 long ts = MusicUtil.v2sTimeStampInMicroseconds(lockOrdinal, timeOfWrite);
686 // TODO: use Statement instead of modifying query
687 if (!queryObject.getQuery().contains("USING TIMESTAMP")) {
688 if (queryObject.getOperation().equalsIgnoreCase("delete"))
689 query = query.replaceFirst("WHERE", " USING TIMESTAMP " + ts + " WHERE ");
690 else if (queryObject.getOperation().equalsIgnoreCase("insert"))
691 query = query.replaceFirst(";", " USING TIMESTAMP " + ts + " ; ");
693 query = query.replaceFirst("SET", "USING TIMESTAMP " + ts + " SET");
695 queryObject.replaceQueryString(query);
696 MusicDataStore dsHandle = MusicDataStoreHandle.getDSHandle();
697 dsHandle.executePut(queryObject, MusicUtil.CRITICAL);
698 long end = System.currentTimeMillis();
699 logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms");
700 } catch (MusicQueryException | MusicServiceException | MusicLockingException e) {
701 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), e);
702 return new ReturnType(ResultType.FAILURE,
703 "Exception thrown while doing the critical put: "
706 return new ReturnType(ResultType.SUCCESS, "Update performed");
714 * @return Boolean Indicates success or failure
715 * @throws MusicServiceException
719 public ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException,MusicQueryException {
720 // this is mainly for some functions like keyspace creation etc which does not
721 // really need the bells and whistles of Music locking.
722 boolean result = false;
724 result = MusicDataStoreHandle.getDSHandle().executePut(queryObject, consistency);
725 // } catch (MusicQueryException | MusicServiceException ex) {
726 // logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR,
727 // ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR, ex);
728 // throw new MusicServiceException(ex.getMessage(),ex);
730 return result ? ResultType.SUCCESS : ResultType.FAILURE;
734 * This method performs DDL operation on cassandra.
736 * @param queryObject query object containing prepared query and values
738 * @throws MusicServiceException
740 public ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException {
741 ResultSet results = null;
743 results = MusicDataStoreHandle.getDSHandle().executeOneConsistencyGet(queryObject);
744 } catch (MusicQueryException | MusicServiceException e) {
745 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
746 throw new MusicServiceException(e.getMessage());
752 * This method performs DDL operations on cassandra, if the the resource is available. Lock ID
753 * is used to check if the resource is free.
755 * @param keyspace name of the keyspace
756 * @param table name of the table
757 * @param primaryKeyValue primary key value
758 * @param queryObject query object containing prepared query and values
759 * @param lockId lock ID to check if the resource is free to perform the operation.
762 public ResultSet criticalGet(String keyspace, String table, String primaryKeyValue,
763 PreparedQueryObject queryObject, String lockId) throws MusicServiceException {
764 ResultSet results = null;
765 String keyLock = lockId.substring(lockId.lastIndexOf(".") + 1,lockId.lastIndexOf("$"));
767 if (lockId.contains(".") && !keyLock.equals(primaryKeyValue)) {
768 throw new MusicLockingException("Lock value '" + keyLock + "' and key value '"
769 + primaryKeyValue + "' do not match. Please check your values: "
772 LockObject lockObject = getLockingServiceHandle().getLockInfo(keyspace, table, primaryKeyValue,
773 lockId.substring(lockId.lastIndexOf("$") + 1));
774 if (null == lockObject) {
775 throw new MusicLockingException("No Lock Object. Please check if lock name or key is correct."
778 if ( !lockObject.getIsLockOwner()) {
779 return null;// not top of the lock store q
781 results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(queryObject);
782 } catch ( MusicLockingException e ) {
783 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity
784 .WARN, ErrorTypes.MUSICSERVICEERROR);
785 throw new MusicServiceException(
786 "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage());
787 } catch (MusicQueryException | MusicServiceException e) {
788 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity
789 .WARN, ErrorTypes.MUSICSERVICEERROR, e);
790 throw new MusicServiceException(
791 "Cannot perform critical get for key: " + primaryKeyValue + " : " + e.getMessage());
797 * This method performs DML operation on cassandra, when the lock of the dd is acquired.
799 * @param keyspaceName name of the keyspace
800 * @param tableName name of the table
801 * @param primaryKey primary key value
802 * @param queryObject query object containing prepared query and values
804 * @throws MusicLockingException
805 * @throws MusicServiceException
806 * @throws MusicQueryException
808 public ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
809 PreparedQueryObject queryObject, Condition conditionInfo)
810 throws MusicLockingException, MusicQueryException, MusicServiceException {
811 long start = System.currentTimeMillis();
812 String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey;
813 String lockId = createLockReferenceAtomic(fullyQualifiedKey, LockType.WRITE);
814 long lockCreationTime = System.currentTimeMillis();
815 ReturnType lockAcqResult = null;
816 logger.info(EELFLoggerDelegate.applicationLogger,
817 "***Acquiring lock for atomicPut() query : " + queryObject.getQuery() + " : " + primaryKey);
818 logger.info(EELFLoggerDelegate.applicationLogger,
819 "***Acquiring lock for atomicPut() values: " + queryObject.getValues().toString());
820 if (conditionInfo != null) {
821 logger.info(EELFLoggerDelegate.applicationLogger,
822 "***Acquiring lock for atomicPut() conditions: " + conditionInfo.toString());
825 lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod());
826 } catch (MusicLockingException ex) {
827 logger.error(EELFLoggerDelegate.errorLogger,
828 "Exception while acquireLockWithLease() in atomic put for key: " + primaryKey);
829 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage());
830 throw new MusicServiceException(
831 "Cannot perform atomic put for key: " + primaryKey + " : " + ex.getMessage());
833 long lockAcqTime = System.currentTimeMillis();
836 * if (!lockAcqResult.getResult().equals(ResultType.SUCCESS)) { logger.info(EELFLoggerDelegate.
837 * applicationLogger,"unable to acquire lock, id " + lockId);
838 * voluntaryReleaseLock(fullyQualifiedKey,lockId); return lockAcqResult; }
841 logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
842 String lockRef = lockId.substring(lockId.lastIndexOf("$"));
843 ReturnType criticalPutResult = null;
844 if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
845 criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey, queryObject, lockRef, conditionInfo);
846 long criticalPutTime = System.currentTimeMillis();
847 long lockDeleteTime = System.currentTimeMillis();
848 String timingInfo = "|lock creation time:" + (lockCreationTime - start) + "|lock accquire time:"
849 + (lockAcqTime - lockCreationTime) + "|critical put time:" + (criticalPutTime - lockAcqTime)
850 + "|lock delete time:" + (lockDeleteTime - criticalPutTime) + "|";
851 criticalPutResult.setTimingInfo(timingInfo);
853 logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
854 criticalPutResult = lockAcqResult;
857 voluntaryReleaseLock(fullyQualifiedKey, lockId);
858 } catch (MusicLockingException ex) {
859 logger.info(EELFLoggerDelegate.applicationLogger,
860 "Exception occured while deleting lock after atomic put for key: " + primaryKey);
861 criticalPutResult.setMessage(criticalPutResult.getMessage() + "Lock release failed");
863 return criticalPutResult;
869 * This method performs DDL operation on cassasndra, when the lock for the resource is acquired.
871 * @param keyspaceName name of the keyspace
872 * @param tableName name of the table
873 * @param primaryKey primary key value
874 * @param queryObject query object containing prepared query and values
876 * @throws MusicServiceException
877 * @throws MusicLockingException
878 * @throws MusicQueryException
880 public ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
881 PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException, MusicQueryException {
882 String fullyQualifiedKey = keyspaceName + "." + tableName + "." + primaryKey;
883 String lockId = createLockReferenceAtomic(fullyQualifiedKey, LockType.READ);
884 ReturnType lockAcqResult = null;
885 ResultSet result = null;
886 logger.info(EELFLoggerDelegate.applicationLogger, "Acquiring lock for atomicGet() : " + queryObject.getQuery());
888 lockAcqResult = acquireLockWithLease(fullyQualifiedKey, lockId, MusicUtil.getDefaultLockLeasePeriod());
889 } catch (MusicLockingException ex) {
890 logger.error(EELFLoggerDelegate.errorLogger,
891 "Exception while acquireLockWithLease() in atomic get for key: " + primaryKey);
892 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage());
893 throw new MusicServiceException(
894 "Cannot perform atomic get for key: " + primaryKey + " : " + ex.getMessage());
896 if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
897 logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
898 String lockRef = lockId.substring(lockId.lastIndexOf("$"));
899 result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockRef);
901 logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
904 voluntaryReleaseLock(fullyQualifiedKey, lockId);
905 } catch (MusicLockingException ex) {
906 logger.info(EELFLoggerDelegate.applicationLogger,
907 "Exception occured while deleting lock after atomic put for key: " + primaryKey);
908 throw new MusicLockingException(ex.getMessage());
920 public Map<String, Object> validateLock(String lockName) {
921 return MusicUtil.validateLock(lockName);
926 public ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
927 PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
932 public List<String> getLockQueue(String fullyQualifiedKey)
933 throws MusicServiceException, MusicQueryException, MusicLockingException {
934 String[] splitString = fullyQualifiedKey.split("\\.");
935 String keyspace = splitString[0];
936 String table = splitString[1];
937 String primaryKeyValue = splitString[2];
939 return getLockingServiceHandle().getLockQueue(keyspace, table, primaryKeyValue);
942 public long getLockQueueSize(String fullyQualifiedKey)
943 throws MusicServiceException, MusicQueryException, MusicLockingException {
944 String[] splitString = fullyQualifiedKey.split("\\.");
945 String keyspace = splitString[0];
946 String table = splitString[1];
947 String primaryKeyValue = splitString[2];
949 return getLockingServiceHandle().getLockQueueSize(keyspace, table, primaryKeyValue);
954 public ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
955 PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
960 //Methods added for ORM changes
962 public ResultType createKeyspace(JsonKeySpace jsonKeySpaceObject,String consistencyInfo)
963 throws MusicServiceException,MusicQueryException {
964 ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genCreateKeyspaceQuery(), consistencyInfo);
965 logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace Creation Process completed successfully");
970 public ResultType dropKeyspace(JsonKeySpace jsonKeySpaceObject, String consistencyInfo)
971 throws MusicServiceException,MusicQueryException {
972 ResultType result = nonKeyRelatedPut(jsonKeySpaceObject.genDropKeyspaceQuery(),
974 logger.info(EELFLoggerDelegate.applicationLogger, " Keyspace deletion Process completed successfully");
978 public ResultType createTable(JsonTable jsonTableObject, String consistencyInfo)
979 throws MusicServiceException, MusicQueryException {
980 ResultType result = null;
982 result = createTable(jsonTableObject.getKeyspaceName(),
983 jsonTableObject.getTableName(), jsonTableObject.genCreateTableQuery(), consistencyInfo);
985 } catch (MusicServiceException ex) {
986 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(), AppMessages.UNKNOWNERROR, ErrorSeverity.WARN,
987 ErrorTypes.MUSICSERVICEERROR);
988 throw new MusicServiceException(ex.getMessage());
990 logger.info(EELFLoggerDelegate.applicationLogger, " Table Creation Process completed successfully ");
994 public ResultType dropTable(JsonTable jsonTableObject,String consistencyInfo)
995 throws MusicServiceException,MusicQueryException {
996 ResultType result = nonKeyRelatedPut(jsonTableObject.genDropTableQuery(),
998 logger.info(EELFLoggerDelegate.applicationLogger, " Table deletion Process completed successfully ");
1004 public ResultType createIndex(JsonIndex jsonIndexObject, String consistencyInfo)
1005 throws MusicServiceException, MusicQueryException{
1006 ResultType result = nonKeyRelatedPut(jsonIndexObject.genCreateIndexQuery(),
1009 logger.info(EELFLoggerDelegate.applicationLogger, " Index creation Process completed successfully ");
1014 * This method performs DDL operation on cassandra.
1016 * @param queryObject query object containing prepared query and values
1018 * @throws MusicServiceException
1020 public ResultSet select(JsonSelect jsonSelect, MultivaluedMap<String, String> rowParams)
1021 throws MusicServiceException, MusicQueryException {
1022 ResultSet results = null;
1024 results = get(jsonSelect.genSelectQuery(rowParams));
1025 } catch (MusicServiceException e) {
1026 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
1027 throw new MusicServiceException(e.getMessage());
1035 public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap<String, String> rowParams)
1036 throws MusicLockingException, MusicQueryException, MusicServiceException {
1038 ResultSet results = null;
1039 String consistency = "";
1040 if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) {
1041 consistency = jsonInsertObj.getConsistencyInfo().get("type");
1044 String lockId = jsonInsertObj.getConsistencyInfo().get("lockId");
1046 PreparedQueryObject queryObject = jsonInsertObj.genSelectCriticalPreparedQueryObj(rowParams);
1048 if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
1049 results = criticalGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(),
1050 jsonInsertObj.getPrimaryKeyVal(), queryObject,lockId);
1051 } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
1052 results = atomicGet(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(),
1053 jsonInsertObj.getPrimaryKeyVal(), queryObject);
1060 * this is insert row into Table
1062 public ReturnType insertIntoTable(JsonInsert jsonInsertObj)
1063 throws MusicLockingException, MusicQueryException, MusicServiceException {
1065 String consistency = "";
1066 if(null != jsonInsertObj && null != jsonInsertObj.getConsistencyInfo()) {
1067 consistency = jsonInsertObj.getConsistencyInfo().get("type");
1070 ReturnType result = null;
1073 PreparedQueryObject queryObj = null;
1074 queryObj = jsonInsertObj.genInsertPreparedQueryObj();
1076 if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
1077 result = eventualPut(jsonInsertObj.genInsertPreparedQueryObj());
1078 } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
1079 String lockId = jsonInsertObj.getConsistencyInfo().get("lockId");
1080 if(lockId == null) {
1081 logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
1082 + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
1083 return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock "
1084 + "and acquire lock or use ATOMIC instead of CRITICAL");
1086 result = criticalPut(jsonInsertObj.getKeyspaceName(),
1087 jsonInsertObj.getTableName(), jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), lockId,null);
1088 } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
1089 result = atomicPut(jsonInsertObj.getKeyspaceName(), jsonInsertObj.getTableName(),
1090 jsonInsertObj.getPrimaryKeyVal(), jsonInsertObj.genInsertPreparedQueryObj(), null);
1092 } catch (Exception ex) {
1093 logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity
1094 .WARN, ErrorTypes.MUSICSERVICEERROR, ex);
1095 return new ReturnType(ResultType.FAILURE, ex.getMessage());
1102 * This is insert row into Table
1104 public ReturnType updateTable(JsonUpdate jsonUpdateObj, MultivaluedMap<String, String> rowParams)
1105 throws MusicLockingException, MusicQueryException, MusicServiceException {
1107 ReturnType result = null;
1108 String consistency = "";
1109 if(null != jsonUpdateObj && null != jsonUpdateObj.getConsistencyInfo()) {
1110 consistency = jsonUpdateObj.getConsistencyInfo().get("type");
1112 PreparedQueryObject queryObject = jsonUpdateObj.genUpdatePreparedQueryObj(rowParams);
1114 Condition conditionInfo;
1115 if (jsonUpdateObj.getConditions() == null) {
1116 conditionInfo = null;
1118 // to avoid parsing repeatedly, just send the select query to obtain row
1119 PreparedQueryObject selectQuery = new PreparedQueryObject();
1120 selectQuery.appendQueryString("SELECT * FROM " + jsonUpdateObj.getKeyspaceName() + "." + jsonUpdateObj.getTableName() + " WHERE "
1121 + jsonUpdateObj.getRowIdString() + ";");
1122 selectQuery.addValue(jsonUpdateObj.getPrimarKeyValue());
1123 conditionInfo = new Condition(jsonUpdateObj.getConditions(), selectQuery);
1127 if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
1128 result = eventualPut(queryObject);
1129 } else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
1130 String lockId = jsonUpdateObj.getConsistencyInfo().get("lockId");
1131 if(lockId == null) {
1132 logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
1133 + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
1135 return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock "
1136 + "and acquire lock or use ATOMIC instead of CRITICAL");
1138 result = criticalPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(),
1139 queryObject, lockId, conditionInfo);
1140 } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) {
1141 // this function is mainly for the benchmarks
1143 result = atomicPutWithDeleteLock(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(),
1144 jsonUpdateObj.getPrimarKeyValue(), queryObject, conditionInfo);
1145 } catch (MusicLockingException e) {
1146 logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN,
1147 ErrorTypes.GENERALSERVICEERROR, e);
1148 throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString());
1151 } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
1153 result = atomicPut(jsonUpdateObj.getKeyspaceName(), jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue(),
1154 queryObject, conditionInfo);
1155 } catch (MusicLockingException e) {
1156 logger.error(EELFLoggerDelegate.errorLogger,e, AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR, e);
1157 throw new MusicLockingException(AppMessages.UNKNOWNERROR.toString());
1159 } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {
1161 result = eventualPut_nb(queryObject, jsonUpdateObj.getKeyspaceName(),
1162 jsonUpdateObj.getTableName(), jsonUpdateObj.getPrimarKeyValue());
1163 }catch (Exception e) {
1164 return new ReturnType(ResultType.FAILURE, e.getMessage());
1173 * This method is for Delete From Table
1175 public ReturnType deleteFromTable(JsonDelete jsonDeleteObj, MultivaluedMap<String, String> rowParams)
1176 throws MusicLockingException, MusicQueryException, MusicServiceException {
1178 ReturnType result = null;
1179 String consistency = "";
1180 if(null != jsonDeleteObj && null != jsonDeleteObj.getConsistencyInfo()) {
1181 consistency = jsonDeleteObj.getConsistencyInfo().get("type");
1183 PreparedQueryObject queryObject = jsonDeleteObj.genDeletePreparedQueryObj(rowParams);
1185 // get the conditional, if any
1186 Condition conditionInfo;
1187 if (jsonDeleteObj.getConditions() == null) {
1188 conditionInfo = null;
1190 // to avoid parsing repeatedly, just send the select query to obtain row
1191 PreparedQueryObject selectQuery = new PreparedQueryObject();
1192 selectQuery.appendQueryString("SELECT * FROM " + jsonDeleteObj.getKeyspaceName() + "." + jsonDeleteObj.getTableName() + " WHERE "
1193 + jsonDeleteObj.getRowIdString() + ";");
1194 selectQuery.addValue(jsonDeleteObj.getPrimarKeyValue());
1195 conditionInfo = new Condition(jsonDeleteObj.getConditions(), selectQuery);
1198 if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
1199 result = eventualPut(queryObject);
1200 else if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
1201 String lockId = jsonDeleteObj.getConsistencyInfo().get("lockId");
1202 if(lockId == null) {
1203 logger.error(EELFLoggerDelegate.errorLogger,"LockId cannot be null. Create lock reference or"
1204 + " use ATOMIC instead of CRITICAL", ErrorSeverity.FATAL, ErrorTypes.MUSICSERVICEERROR);
1206 return new ReturnType(ResultType.FAILURE, "LockId cannot be null. Create lock "
1207 + "and acquire lock or use ATOMIC instead of CRITICAL");
1209 result = criticalPut(jsonDeleteObj.getKeyspaceName(),
1210 jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(),
1211 queryObject, lockId, conditionInfo);
1212 } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
1213 result = atomicPut(jsonDeleteObj.getKeyspaceName(),
1214 jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue(),
1215 queryObject, conditionInfo);
1216 } else if(consistency.equalsIgnoreCase(MusicUtil.EVENTUAL_NB)) {
1217 result = eventualPut_nb(queryObject, jsonDeleteObj.getKeyspaceName(),
1218 jsonDeleteObj.getTableName(), jsonDeleteObj.getPrimarKeyValue());