2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (c) 2018-2019 IBM
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.datastore;
28 import java.nio.ByteBuffer;
29 import java.util.HashMap;
32 import org.onap.music.eelf.logging.EELFLoggerDelegate;
33 import org.onap.music.eelf.logging.format.AppMessages;
34 import org.onap.music.eelf.logging.format.ErrorSeverity;
35 import org.onap.music.eelf.logging.format.ErrorTypes;
36 import org.onap.music.exceptions.MusicQueryException;
37 import org.onap.music.exceptions.MusicServiceException;
38 import org.onap.music.lockingservice.cassandra.LockType;
39 import org.onap.music.main.CipherUtil;
40 import org.onap.music.main.MusicUtil;
41 import com.datastax.driver.core.Cluster;
42 import com.datastax.driver.core.ColumnDefinitions;
43 import com.datastax.driver.core.ColumnDefinitions.Definition;
44 import com.datastax.driver.core.ConsistencyLevel;
45 import com.datastax.driver.core.DataType;
46 import com.datastax.driver.core.HostDistance;
47 import com.datastax.driver.core.KeyspaceMetadata;
48 import com.datastax.driver.core.Metadata;
49 import com.datastax.driver.core.PoolingOptions;
50 import com.datastax.driver.core.ResultSet;
51 import com.datastax.driver.core.Row;
52 import com.datastax.driver.core.Session;
53 import com.datastax.driver.core.SimpleStatement;
54 import com.datastax.driver.core.SocketOptions;
55 import com.datastax.driver.core.TableMetadata;
56 import com.datastax.driver.core.exceptions.AlreadyExistsException;
57 import com.datastax.driver.core.exceptions.InvalidQueryException;
58 import com.datastax.driver.extras.codecs.enums.EnumNameCodec;
64 public class MusicDataStore {
66 public static final String CONSISTENCY_LEVEL_ONE = "ONE";
67 public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM";
68 public static final String CONSISTENCY_LEVEL_LOCAL_QUORUM = "LOCAL_QUORUM";
69 private Session session;
70 private Cluster cluster;
74 * Connect to default Cassandra address
76 public MusicDataStore() {
78 connectToCassaCluster(MusicUtil.getMyCassaHost());
79 } catch (MusicServiceException e) {
80 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
89 public MusicDataStore(Cluster cluster, Session session) {
90 this.session = session;
98 public void setSession(Session session) {
99 this.session = session;
105 public Session getSession() {
112 public void setCluster(Cluster cluster) {
113 EnumNameCodec<LockType> lockTypeCodec = new EnumNameCodec<LockType>(LockType.class);
114 cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec);
116 this.cluster = cluster;
119 public Cluster getCluster() {
124 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
130 * @throws MusicServiceException
132 public MusicDataStore(String remoteIp) {
134 connectToCassaCluster(remoteIp);
135 } catch (MusicServiceException e) {
136 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), e);
143 public void close() {
148 * This method connects to cassandra cluster on specific address.
152 private void connectToCassaCluster(String address) throws MusicServiceException {
153 String[] addresses = null;
154 addresses = address.split(",");
155 PoolingOptions poolingOptions = new PoolingOptions();
157 .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
158 .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
161 if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
163 if (MusicUtil.getCipherEncKey() != null && !("").equals(MusicUtil.getCipherEncKey())) {
164 cassPwd = CipherUtil.decryptPKC(MusicUtil.getCassPwd());
166 cassPwd = MusicUtil.getCassPwd();
168 logger.info(EELFLoggerDelegate.applicationLogger,
169 "Building with credentials "+MusicUtil.getCassName()+" & "+ MusicUtil.getCassPwd());
170 cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
171 .withCredentials(MusicUtil.getCassName(), cassPwd)
172 //.withLoadBalancingPolicy(new RoundRobinPolicy())
173 .withoutJMXReporting()
174 .withPoolingOptions(poolingOptions)
176 new SocketOptions().setConnectTimeoutMillis(MusicUtil.getCassandraConnectTimeOutMS())
177 .setReadTimeoutMillis(MusicUtil.getCassandraReadTimeOutMS()))
178 .addContactPoints(addresses).build();
180 cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
181 .withoutJMXReporting()
182 .withPoolingOptions(poolingOptions)
183 .withSocketOptions(new SocketOptions()
184 .setConnectTimeoutMillis(MusicUtil.getCassandraConnectTimeOutMS())
185 .setReadTimeoutMillis(MusicUtil.getCassandraReadTimeOutMS()))
186 .addContactPoints(addresses)
190 this.setCluster(cluster);
191 Metadata metadata = this.cluster.getMetadata();
192 logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
193 + metadata.getClusterName() + " at " + address);
196 session = this.cluster.connect();
197 } catch (Exception ex) {
198 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY,
199 ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE, ex);
200 throw new MusicServiceException(
201 "Error while connecting to Cassandra cluster.. " + ex.getMessage());
212 public DataType returnColumnDataType(String keyspace, String tableName, String columnName) {
213 KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace);
214 TableMetadata table = ks.getTable(tableName);
215 return table.getColumn(columnName).getType();
223 * @return TableMetadata
225 public TableMetadata returnColumnMetadata(String keyspace, String tableName) {
226 KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(keyspace);
227 return ks.getTable(tableName);
234 * @return TableMetadata
236 public KeyspaceMetadata returnKeyspaceMetadata(String keyspace) {
237 return cluster.getMetadata().getKeyspace(keyspace);
242 * Utility function to return the Java specific object type.
249 public Object getColValue(Row row, String colName, DataType colType) {
251 switch (colType.getName()) {
253 return row.getString(colName);
255 return row.getUUID(colName);
257 return row.getVarint(colName);
259 return row.getLong(colName);
261 return row.getInt(colName);
263 return row.getFloat(colName);
265 return row.getDouble(colName);
267 return row.getBool(colName);
269 return row.getMap(colName, String.class, String.class);
271 return row.getList(colName, String.class);
277 public byte[] getBlobValue(Row row, String colName, DataType colType) {
278 ByteBuffer bb = row.getBytes(colName);
282 public boolean doesRowSatisfyCondition(Row row, Map<String, Object> condition) throws Exception {
283 ColumnDefinitions colInfo = row.getColumnDefinitions();
285 for (Map.Entry<String, Object> entry : condition.entrySet()) {
286 String colName = entry.getKey();
287 DataType colType = colInfo.getType(colName);
288 Object columnValue = getColValue(row, colName, colType);
289 Object conditionValue = MusicUtil.convertToActualDataType(colType, entry.getValue());
290 if (columnValue.equals(conditionValue) == false)
297 * Utility function to store ResultSet values in to a MAP for output.
302 public Map<String, HashMap<String, Object>> marshalData(ResultSet results) {
303 Map<String, HashMap<String, Object>> resultMap =
306 for (Row row : results) {
307 ColumnDefinitions colInfo = row.getColumnDefinitions();
308 HashMap<String, Object> resultOutput = new HashMap<>();
309 for (Definition definition : colInfo) {
310 if (!(("vector_ts").equals(definition.getName()))) {
311 if(definition.getType().toString().toLowerCase().contains("blob")) {
312 resultOutput.put(definition.getName(),
313 getBlobValue(row, definition.getName(), definition.getType()));
315 resultOutput.put(definition.getName(),
316 getColValue(row, definition.getName(), definition.getType()));
320 resultMap.put("row " + counter, resultOutput);
327 // Prepared Statements 1802 additions
329 public boolean executePut(PreparedQueryObject queryObject, String consistency)
330 throws MusicServiceException, MusicQueryException {
331 return executePut(queryObject, consistency, 0);
334 * This Method performs DDL and DML operations on Cassandra using specified consistency level
336 * @param queryObject Object containing cassandra prepared query and values.
337 * @param consistency Specify consistency level for data synchronization across cassandra
339 * @return Boolean Indicates operation success or failure
340 * @throws MusicServiceException
341 * @throws MusicQueryException
343 public boolean executePut(PreparedQueryObject queryObject, String consistency,long timeSlot)
344 throws MusicServiceException, MusicQueryException {
346 boolean result = false;
347 long timeOfWrite = System.currentTimeMillis();
348 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
349 logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
350 throw new MusicQueryException("Ill formed queryObject for the request = " + "["
351 + queryObject.getQuery() + "]");
353 logger.debug(EELFLoggerDelegate.applicationLogger,
354 "In preprared Execute Put: the actual insert query:"
355 + queryObject.getQuery() + "; the values"
356 + queryObject.getValues());
357 SimpleStatement preparedInsert = null;
360 preparedInsert = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray());
361 if (consistency.equalsIgnoreCase(MusicUtil.CRITICAL)) {
362 logger.info(EELFLoggerDelegate.applicationLogger, "Executing critical put query");
363 preparedInsert.setConsistencyLevel(ConsistencyLevel.QUORUM);
364 } else if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
365 logger.info(EELFLoggerDelegate.applicationLogger, "Executing simple put query");
366 if(queryObject.getConsistency() == null)
367 preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE);
369 preparedInsert.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency()));
370 } else if (consistency.equalsIgnoreCase(MusicUtil.ONE)) {
371 preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE);
372 } else if (consistency.equalsIgnoreCase(MusicUtil.QUORUM)) {
373 preparedInsert.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
374 } else if (consistency.equalsIgnoreCase(MusicUtil.ALL)) {
375 preparedInsert.setConsistencyLevel(ConsistencyLevel.ALL);
377 long timestamp = MusicUtil.v2sTimeStampInMicroseconds(timeSlot, timeOfWrite);
378 preparedInsert.setDefaultTimestamp(timestamp);
380 ResultSet rs = session.execute(preparedInsert);
381 result = rs.wasApplied();
382 } catch (AlreadyExistsException ae) {
383 throw new MusicServiceException("Already Exists Exception: " + ae.getMessage());
384 } catch (InvalidQueryException e) {
385 if (e.getMessage().contains("unconfigured table")) {
386 throw new MusicServiceException("Invalid Query Exception: " + e.getMessage());
388 logger.info(EELFLoggerDelegate.applicationLogger, "Query Exception: " + e.getMessage(),
389 AppMessages.SESSIONFAILED + " [" + queryObject.getQuery() + "]", ErrorSeverity.INFO,
390 ErrorTypes.QUERYERROR, e);
391 throw new MusicServiceException("Query Exception: " + e.getMessage());
393 } catch (Exception e) {
394 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),
395 AppMessages.SESSIONFAILED + " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR,
396 ErrorTypes.QUERYERROR, e);
397 throw new MusicServiceException("Executing Session Failure for Request = " + "[" + queryObject.getQuery()
398 + "]" + " Reason = " + e.getMessage());
405 * This method performs DDL operations on Cassandra using consistency level ONE.
407 * @param queryObject Object containing cassandra prepared query and values.
409 * @throws MusicServiceException
410 * @throws MusicQueryException
412 public ResultSet executeEventualGet(PreparedQueryObject queryObject)
413 throws MusicServiceException, MusicQueryException {
414 CacheAccess<String, PreparedStatement> queryBank = CachingUtil.getStatementBank();
415 PreparedStatement preparedEventualGet = null;
416 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
417 logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
418 throw new MusicQueryException("Ill formed queryObject for the request = " + "["
419 + queryObject.getQuery() + "]");
421 logger.info(EELFLoggerDelegate.applicationLogger,
422 "Executing Eventual get query:" + queryObject.getQuery());
424 ResultSet results = null;
426 if(queryBank.get(queryObject.getQuery()) != null )
427 preparedEventualGet=queryBank.get(queryObject.getQuery());
429 preparedEventualGet = session.prepare(queryObject.getQuery());
430 CachingUtil.updateStatementBank(queryObject.getQuery(), preparedEventualGet);
432 if(queryObject.getConsistency() == null) {
433 preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE);
435 preparedEventualGet.setConsistencyLevel(MusicUtil.getConsistencyLevel(queryObject.getConsistency()));
437 results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
439 } catch (Exception ex) {
440 logger.error("Exception", ex);
441 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
442 throw new MusicServiceException(ex.getMessage());
449 * This method performs DDL operation on Cassandra using consistency level QUORUM.
451 * @param queryObject Object containing cassandra prepared query and values.
453 * @throws MusicServiceException
454 * @throws MusicQueryException
456 public ResultSet executeCriticalGet(PreparedQueryObject queryObject)
457 throws MusicServiceException, MusicQueryException {
458 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
459 logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
460 throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "["
461 + queryObject.getQuery() + "]");
463 logger.info(EELFLoggerDelegate.applicationLogger,
464 "Executing Critical get query:" + queryObject.getQuery());
465 PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
466 preparedEventualGet.setConsistencyLevel(ConsistencyLevel.QUORUM);
467 ResultSet results = null;
469 results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
470 } catch (Exception ex) {
471 logger.error("Exception", ex);
472 logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
473 throw new MusicServiceException(ex.getMessage());
479 public ResultSet executeGet(PreparedQueryObject queryObject,String consistencyLevel) throws MusicQueryException, MusicServiceException {
480 if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
481 logger.error(EELFLoggerDelegate.errorLogger, "",AppMessages.QUERYERROR+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
482 throw new MusicQueryException("Error processing Prepared Query Object for the request = " + "["
483 + queryObject.getQuery() + "]");
485 ResultSet results = null;
487 SimpleStatement statement = new SimpleStatement(queryObject.getQuery(), queryObject.getValues().toArray());
488 if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_ONE)) {
489 statement.setConsistencyLevel(ConsistencyLevel.ONE);
490 } else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_QUORUM)) {
491 statement.setConsistencyLevel(ConsistencyLevel.QUORUM);
492 } else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_LOCAL_QUORUM)) {
493 statement.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
496 results = session.execute(statement);
498 } catch (Exception ex) {
499 logger.error(EELFLoggerDelegate.errorLogger, "Execute Get Error" + ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject
500 .getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR, ex);
501 throw new MusicServiceException("Execute Get Error" + ex.getMessage());
509 * This method performs DDL operations on Cassandra using consistency level ONE.
511 * @param queryObject Object containing cassandra prepared query and values.
513 public ResultSet executeOneConsistencyGet(PreparedQueryObject queryObject)
514 throws MusicServiceException, MusicQueryException {
515 return executeGet(queryObject, CONSISTENCY_LEVEL_ONE);
520 * This method performs DDL operation on Cassandra using consistency level LOCAL_QUORUM.
522 * @param queryObject Object containing cassandra prepared query and values.
524 public ResultSet executeLocalQuorumConsistencyGet(PreparedQueryObject queryObject)
525 throws MusicServiceException, MusicQueryException {
526 return executeGet(queryObject, CONSISTENCY_LEVEL_LOCAL_QUORUM);
531 * This method performs DDL operation on Cassandra using consistency level QUORUM.
533 * @param queryObject Object containing cassandra prepared query and values.
535 public ResultSet executeQuorumConsistencyGet(PreparedQueryObject queryObject)
536 throws MusicServiceException, MusicQueryException {
537 return executeGet(queryObject, CONSISTENCY_LEVEL_QUORUM);