2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (c) 2017 AT&T Intellectual Property
6 * ===================================================================
7 * Modifications Copyright (c) 2018 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.main;
28 import com.datastax.driver.core.ColumnDefinitions;
29 import com.datastax.driver.core.ColumnDefinitions.Definition;
30 import com.datastax.driver.core.ResultSet;
31 import com.datastax.driver.core.Row;
33 import java.io.FileNotFoundException;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.math.BigInteger;
37 import java.nio.ByteBuffer;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.List;
42 import java.util.Properties;
43 import java.util.Scanner;
44 import java.util.StringTokenizer;
45 import java.util.UUID;
46 import java.util.concurrent.ConcurrentHashMap;
47 import java.util.concurrent.ConcurrentMap;
49 import javax.ws.rs.core.Response;
50 import javax.ws.rs.core.Response.ResponseBuilder;
51 import org.onap.music.datastore.MusicDataStoreHandle;
52 import org.onap.music.datastore.PreparedQueryObject;
53 import org.onap.music.eelf.logging.EELFLoggerDelegate;
54 import org.onap.music.eelf.logging.format.AppMessages;
55 import org.onap.music.eelf.logging.format.ErrorSeverity;
56 import org.onap.music.eelf.logging.format.ErrorTypes;
57 import org.onap.music.exceptions.MusicQueryException;
58 import org.onap.music.exceptions.MusicServiceException;
59 import org.onap.music.service.MusicCoreService;
60 import org.onap.music.service.impl.MusicCassaCore;
62 import com.datastax.driver.core.ConsistencyLevel;
63 import com.datastax.driver.core.DataType;
64 import com.sun.jersey.core.util.Base64;
69 * Properties This will take Properties and load them into MusicUtil.
70 * This is a hack for now. Eventually it would bebest to do this in
74 public class MusicUtil {
75 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
77 public static final String ATOMIC = "atomic";
78 public static final String EVENTUAL = "eventual";
79 public static final String CRITICAL = "critical";
80 public static final String EVENTUAL_NB = "eventual_nb";
81 public static final String ALL = "all";
82 public static final String QUORUM = "quorum";
83 public static final String ONE = "one";
84 public static final String ATOMICDELETELOCK = "atomic_delete_lock";
85 public static final String DEFAULTKEYSPACENAME = "TBD";
86 private static final String XLATESTVERSION = "X-latestVersion";
87 private static final String XMINORVERSION = "X-minorVersion";
88 private static final String XPATCHVERSION = "X-patchVersion";
89 public static final String SELECT = "select";
90 public static final String INSERT = "insert";
91 public static final String UPDATE = "update";
92 public static final String UPSERT = "upsert";
93 public static final String USERID = "userId";
94 public static final String PASSWORD = "password";
95 public static final String CASSANDRA = "cassandra";
97 public static final String AUTHORIZATION = "Authorization";
99 private static final String LOCALHOST = "localhost";
100 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
102 private static int myId = 0;
103 private static ArrayList<String> allIds = new ArrayList<>();
104 private static String publicIp = "";
105 private static ArrayList<String> allPublicIps = new ArrayList<>();
106 private static String myZkHost = LOCALHOST;
107 private static String myCassaHost = LOCALHOST;
108 private static String defaultMusicIp = LOCALHOST;
109 private static int cassandraPort = 9042;
110 private static int notifytimeout = 30000;
111 private static int notifyinterval = 5000;
112 private static int cacheObjectMaxLife = -1;
113 private static String lockUsing = MusicUtil.CASSANDRA;
114 private static boolean isCadi = false;
116 private static boolean debug = true;
117 private static String version = "2.3.0";
118 private static String musicRestIp = LOCALHOST;
119 private static String musicPropertiesFilePath = PROPERTIES_FILE;
120 private static long defaultLockLeasePeriod = 6000;
121 private static final String[] propKeys = new String[] { "cassandra.host", "music.ip", "debug",
122 "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
123 "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","admin.username","admin.password","aaf.admin.url",
124 "music.namespace","admin.aaf.role","cassandra.port","lock.using"};
125 private static final String[] cosistencyLevel = new String[] {
126 "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO","THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
127 private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
129 consistencyName.put("ONE",ConsistencyLevel.ONE);
130 consistencyName.put("TWO",ConsistencyLevel.TWO);
131 consistencyName.put("THREE",ConsistencyLevel.THREE);
132 consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
133 consistencyName.put("ALL",ConsistencyLevel.ALL);
134 consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
135 consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
136 consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
137 consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
138 consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
141 private static String cassName = "cassandra";
142 private static String cassPwd;
143 private static String aafEndpointUrl = null;
144 public static ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
145 private static String adminId = "username";
146 private static String adminPass= "password";
147 private static String aafAdminUrl= null;
148 private static String musicNamespace= "com.att.music.api";
149 private static String adminAafRole= "com.att.music.api.admin_api";
151 public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
153 public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
155 public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
158 public static String getLockUsing() {
163 public static void setLockUsing(String lockUsing) {
164 MusicUtil.lockUsing = lockUsing;
167 public static String getAafAdminUrl() {
172 public static void setAafAdminUrl(String aafAdminUrl) {
173 MusicUtil.aafAdminUrl = aafAdminUrl;
177 public static String getMusicNamespace() {
178 return musicNamespace;
182 public static void setMusicNamespace(String musicNamespace) {
183 MusicUtil.musicNamespace = musicNamespace;
187 public static String getAdminAafRole() {
192 public static void setAdminAafRole(String adminAafRole) {
193 MusicUtil.adminAafRole = adminAafRole;
198 public static String getAdminId() {
203 public static void setAdminId(String adminId) {
204 MusicUtil.adminId = adminId;
208 public static String getAdminPass() {
212 public static void setAdminPass(String adminPass) {
213 MusicUtil.adminPass = adminPass;
217 private MusicUtil() {
218 throw new IllegalStateException("Utility Class");
222 * @return cassandra port
224 public static int getCassandraPort() {
225 return cassandraPort;
230 * @param cassandraPort
232 public static void setCassandraPort(int cassandraPort) {
233 MusicUtil.cassandraPort = cassandraPort;
236 * @return the cassName
238 public static String getCassName() {
243 * @return the cassPwd
245 public static String getCassPwd() {
250 * @return the aafEndpointUrl
252 public static String getAafEndpointUrl() {
253 return aafEndpointUrl;
258 * @param aafEndpointUrl
260 public static void setAafEndpointUrl(String aafEndpointUrl) {
261 MusicUtil.aafEndpointUrl = aafEndpointUrl;
268 public static int getMyId() {
276 public static void setMyId(int myId) {
277 MusicUtil.myId = myId;
284 public static List<String> getAllIds() {
292 public static void setAllIds(List<String> allIds) {
293 MusicUtil.allIds = (ArrayList<String>) allIds;
300 public static String getPublicIp() {
308 public static void setPublicIp(String publicIp) {
309 MusicUtil.publicIp = publicIp;
316 public static List<String> getAllPublicIps() {
322 * @param allPublicIps
324 public static void setAllPublicIps(List<String> allPublicIps) {
325 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
329 * Returns An array of property names that should be in the Properties
334 public static String[] getPropkeys() {
339 * Get MusicRestIp - default = localhost property file value - music.rest.ip
343 public static String getMusicRestIp() {
352 public static void setMusicRestIp(String musicRestIp) {
353 MusicUtil.musicRestIp = musicRestIp;
357 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
358 * property file value - music.properties
362 public static String getMusicPropertiesFilePath() {
363 return musicPropertiesFilePath;
367 * Set MusicPropertiesFilePath
369 * @param musicPropertiesFilePath
371 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
372 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
376 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
381 public static long getDefaultLockLeasePeriod() {
382 return defaultLockLeasePeriod;
386 * Set DefaultLockLeasePeriod
388 * @param defaultLockLeasePeriod
390 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
391 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
399 public static void setDebug(boolean debug) {
400 MusicUtil.debug = debug;
404 * Is Debug - Default = true property file value - debug
408 public static boolean isDebug() {
417 public static void setVersion(String version) {
418 MusicUtil.version = version;
422 * Return the version property file value - version
426 public static String getVersion() {
431 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
432 * value - cassandra.host
436 public static String getMyCassaHost() {
441 * Set MyCassHost - Cassandra Hostname
445 public static void setMyCassaHost(String myCassaHost) {
446 MusicUtil.myCassaHost = myCassaHost;
450 * Get DefaultMusicIp - Default = localhost property file value - music.ip
454 public static String getDefaultMusicIp() {
455 return defaultMusicIp;
461 * @param defaultMusicIp
463 public static void setDefaultMusicIp(String defaultMusicIp) {
464 MusicUtil.defaultMusicIp = defaultMusicIp;
471 public static String getTestType() {
472 String testType = "";
474 Scanner fileScanner = new Scanner(new File(""));
475 testType = fileScanner.next();// ignore the my id line
476 @SuppressWarnings("unused")
477 String batchSize = fileScanner.next();// ignore the my public ip
480 } catch (FileNotFoundException e) {
481 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
491 public static void sleep(long time) {
494 } catch (InterruptedException e) {
495 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
496 Thread.currentThread().interrupt();
501 * Utility function to check if the query object is valid.
507 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
509 int noOfValues = queryObject.getValues().size();
511 char[] temp = queryObject.getQuery().toCharArray();
512 for (int i = 0; i < temp.length; i++) {
516 return (noOfValues == noOfParams);
518 return !queryObject.getQuery().isEmpty();
523 public static void setCassName(String cassName) {
524 MusicUtil.cassName = cassName;
527 public static void setCassPwd(String cassPwd) {
528 MusicUtil.cassPwd = cassPwd;
531 @SuppressWarnings("unchecked")
532 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
535 switch (type.getName()) {
537 value = valueObj + "";
541 String valueString = valueObj + "";
542 valueString = valueString.replace("'", "''");
543 value = "'" + valueString + "'";
546 Map<String, Object> otMap = (Map<String, Object>) valueObj;
547 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
551 value = valueObj + "";
562 * @throws MusicTypeConversionException
565 @SuppressWarnings("unchecked")
566 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
567 String valueObjString = valueObj + "";
568 switch (colType.getName()) {
570 return UUID.fromString(valueObjString);
572 return BigInteger.valueOf(Long.parseLong(valueObjString));
574 return Long.parseLong(valueObjString);
576 return Integer.parseInt(valueObjString);
578 return Float.parseFloat(valueObjString);
580 return Double.parseDouble(valueObjString);
582 return Boolean.parseBoolean(valueObjString);
584 return (Map<String, Object>) valueObj;
586 return (List<Object>)valueObj;
590 return valueObjString;
594 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
595 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
601 * Utility function to parse json map into sql like string
604 * @param lineDelimiter
608 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
609 StringBuilder sqlString = new StringBuilder();
611 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
612 Object ot = entry.getValue();
613 String value = ot + "";
614 if (ot instanceof String) {
615 value = "'" + value.replace("'", "''") + "'";
617 sqlString.append("'" + entry.getKey() + "':" + value);
618 if (counter != jMap.size() - 1)
619 sqlString.append(lineDelimiter);
620 counter = counter + 1;
622 return sqlString.toString();
625 @SuppressWarnings("unused")
626 public static String buildVersion(String major, String minor, String patch) {
628 major += "." + minor;
630 major += "." + patch;
637 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
638 * X-latestVerstion will be equal to the latest full version.
639 * X-minorVersion - will be equal to the latest minor version.
640 * X-pathVersion - will be equal to the latest patch version.
641 * Future plans will change this.
648 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
649 ResponseBuilder response = Response.noContent();
650 String versionIn = buildVersion(major,minor,patch);
651 String version = MusicUtil.getVersion();
652 String[] verArray = version.split("\\.",3);
653 if ( minor != null ) {
654 response.header(XMINORVERSION,minor);
656 response.header(XMINORVERSION,verArray[1]);
658 if ( patch != null ) {
659 response.header(XPATCHVERSION,patch);
661 response.header(XPATCHVERSION,verArray[2]);
663 response.header(XLATESTVERSION,version);
664 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
669 public static Map<String,String> extractBasicAuthentication(String authorization){
670 Map<String,String> authValues = new HashMap<>();
671 if(authorization == null) {
672 authValues.put("ERROR", "Authorization cannot be null");
675 authorization = authorization.replaceFirst("Basic", "");
676 String decoded = Base64.base64Decode(authorization);
677 StringTokenizer token = new StringTokenizer(decoded, ":");
678 authValues.put(MusicUtil.USERID, token.nextToken());
679 authValues.put(MusicUtil.PASSWORD,token.nextToken());
684 public static boolean isValidConsistency(String consistency) {
685 for (String string : cosistencyLevel) {
686 if (string.equalsIgnoreCase(consistency))
693 public static ConsistencyLevel getConsistencyLevel(String consistency) {
694 return consistencyName.get(consistency.toUpperCase());
697 public static void loadProperties() throws Exception {
698 Properties prop = new Properties();
699 InputStream input = null;
701 // load the properties file
702 input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
704 } catch (Exception ex) {
705 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
706 throw new Exception();
711 } catch (IOException e) {
716 // get the property value and return it
717 MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
718 MusicUtil.setCassName(prop.getProperty("cassandra.user"));
719 MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
720 MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
721 MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
722 MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
723 MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty("cacheobject.maxlife")));
726 public static void setNotifyInterval(int notifyinterval) {
727 MusicUtil.notifyinterval = notifyinterval;
729 public static void setNotifyTimeOut(int notifytimeout) {
730 MusicUtil.notifytimeout = notifytimeout;
733 public static int getNotifyInterval() {
734 return MusicUtil.notifyinterval;
737 public static int getNotifyTimeout() {
738 return MusicUtil.notifytimeout;
741 public static int getCacheObjectMaxLife() {
742 return MusicUtil.cacheObjectMaxLife;
745 public static void setCacheObjectMaxLife(int cacheObjectMaxLife) {
746 MusicUtil.cacheObjectMaxLife = cacheObjectMaxLife;
750 * Given the time of write for an update in a critical section, this method provides a transformed timestamp
751 * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
752 * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
753 * @param the UUID lock reference associated with the write.
754 * @param the long timeOfWrite which is the actual time at which the write took place
755 * @throws MusicServiceException
756 * @throws MusicQueryException
758 public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
759 // TODO: use acquire time instead of music eternity epoch
760 long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
765 public static MusicCoreService getMusicCoreService() {
766 if(getLockUsing().equals(MusicUtil.CASSANDRA))
767 return MusicCassaCore.getInstance();
769 return MusicCassaCore.getInstance();
776 public static Map<String, Object> validateLock(String lockName) {
777 Map<String, Object> resultMap = new HashMap<>();
778 String[] locks = lockName.split("\\.");
779 if(locks.length < 3) {
780 resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
783 String keyspace= locks[0];
784 if(keyspace.startsWith("$"))
785 keyspace = keyspace.substring(1);
786 resultMap.put("keyspace",keyspace);
791 public static void setIsCadi(boolean isCadi) {
792 MusicUtil.isCadi = isCadi;
795 public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
796 PreparedQueryObject updateQuery, String keyspace, String table,
797 Object cqlFormattedPrimaryKeyValue)
800 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
801 // write it back to a quorum
802 Row row = results.one();
803 ColumnDefinitions colInfo = row.getColumnDefinitions();
804 int totalColumns = colInfo.size();
806 StringBuilder fieldValueString = new StringBuilder("");
807 for (Definition definition : colInfo) {
808 String colName = definition.getName();
809 if (colName.equals(primaryKeyName))
811 DataType colType = definition.getType();
812 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
813 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
814 fieldValueString.append(colName + " = ?");
815 updateQuery.addValue(valueString);
816 if (counter != (totalColumns - 1))
817 fieldValueString.append(",");
818 counter = counter + 1;
820 updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
821 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
822 updateQuery.addValue(cqlFormattedPrimaryKeyValue);
824 MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
825 } catch (MusicServiceException | MusicQueryException e) {
826 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
827 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
831 public static boolean getIsCadi() {
832 return MusicUtil.isCadi;
837 * @return a random uuid
839 public static String generateUUID() {
840 String uuid = UUID.randomUUID().toString();
841 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);