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[] { "zookeeper.host", "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 MyZkHost - Zookeeper Hostname - Default = localhost property file
432 * value - zookeeper.host
436 public static String getMyZkHost() {
441 * Set MyZkHost - Zookeeper Hostname
445 public static void setMyZkHost(String myZkHost) {
446 MusicUtil.myZkHost = myZkHost;
450 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
451 * value - cassandra.host
455 public static String getMyCassaHost() {
460 * Set MyCassHost - Cassandra Hostname
464 public static void setMyCassaHost(String myCassaHost) {
465 MusicUtil.myCassaHost = myCassaHost;
469 * Get DefaultMusicIp - Default = localhost property file value - music.ip
473 public static String getDefaultMusicIp() {
474 return defaultMusicIp;
480 * @param defaultMusicIp
482 public static void setDefaultMusicIp(String defaultMusicIp) {
483 MusicUtil.defaultMusicIp = defaultMusicIp;
490 public static String getTestType() {
491 String testType = "";
493 Scanner fileScanner = new Scanner(new File(""));
494 testType = fileScanner.next();// ignore the my id line
495 @SuppressWarnings("unused")
496 String batchSize = fileScanner.next();// ignore the my public ip
499 } catch (FileNotFoundException e) {
500 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
510 public static void sleep(long time) {
513 } catch (InterruptedException e) {
514 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
515 Thread.currentThread().interrupt();
520 * Utility function to check if the query object is valid.
526 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
528 int noOfValues = queryObject.getValues().size();
530 char[] temp = queryObject.getQuery().toCharArray();
531 for (int i = 0; i < temp.length; i++) {
535 return (noOfValues == noOfParams);
537 return !queryObject.getQuery().isEmpty();
542 public static void setCassName(String cassName) {
543 MusicUtil.cassName = cassName;
546 public static void setCassPwd(String cassPwd) {
547 MusicUtil.cassPwd = cassPwd;
550 @SuppressWarnings("unchecked")
551 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
554 switch (type.getName()) {
556 value = valueObj + "";
560 String valueString = valueObj + "";
561 valueString = valueString.replace("'", "''");
562 value = "'" + valueString + "'";
565 Map<String, Object> otMap = (Map<String, Object>) valueObj;
566 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
570 value = valueObj + "";
581 * @throws MusicTypeConversionException
584 @SuppressWarnings("unchecked")
585 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
586 String valueObjString = valueObj + "";
587 switch (colType.getName()) {
589 return UUID.fromString(valueObjString);
591 return BigInteger.valueOf(Long.parseLong(valueObjString));
593 return Long.parseLong(valueObjString);
595 return Integer.parseInt(valueObjString);
597 return Float.parseFloat(valueObjString);
599 return Double.parseDouble(valueObjString);
601 return Boolean.parseBoolean(valueObjString);
603 return (Map<String, Object>) valueObj;
605 return (List<Object>)valueObj;
609 return valueObjString;
613 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
614 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
620 * Utility function to parse json map into sql like string
623 * @param lineDelimiter
627 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
628 StringBuilder sqlString = new StringBuilder();
630 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
631 Object ot = entry.getValue();
632 String value = ot + "";
633 if (ot instanceof String) {
634 value = "'" + value.replace("'", "''") + "'";
636 sqlString.append("'" + entry.getKey() + "':" + value);
637 if (counter != jMap.size() - 1)
638 sqlString.append(lineDelimiter);
639 counter = counter + 1;
641 return sqlString.toString();
644 @SuppressWarnings("unused")
645 public static String buildVersion(String major, String minor, String patch) {
647 major += "." + minor;
649 major += "." + patch;
656 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
657 * X-latestVerstion will be equal to the latest full version.
658 * X-minorVersion - will be equal to the latest minor version.
659 * X-pathVersion - will be equal to the latest patch version.
660 * Future plans will change this.
667 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
668 ResponseBuilder response = Response.noContent();
669 String versionIn = buildVersion(major,minor,patch);
670 String version = MusicUtil.getVersion();
671 String[] verArray = version.split("\\.",3);
672 if ( minor != null ) {
673 response.header(XMINORVERSION,minor);
675 response.header(XMINORVERSION,verArray[1]);
677 if ( patch != null ) {
678 response.header(XPATCHVERSION,patch);
680 response.header(XPATCHVERSION,verArray[2]);
682 response.header(XLATESTVERSION,version);
683 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
688 public static Map<String,String> extractBasicAuthentication(String authorization){
689 Map<String,String> authValues = new HashMap<>();
690 if(authorization == null) {
691 authValues.put("ERROR", "Authorization cannot be null");
694 authorization = authorization.replaceFirst("Basic", "");
695 String decoded = Base64.base64Decode(authorization);
696 StringTokenizer token = new StringTokenizer(decoded, ":");
697 authValues.put(MusicUtil.USERID, token.nextToken());
698 authValues.put(MusicUtil.PASSWORD,token.nextToken());
703 public static boolean isValidConsistency(String consistency) {
704 for (String string : cosistencyLevel) {
705 if (string.equalsIgnoreCase(consistency))
712 public static ConsistencyLevel getConsistencyLevel(String consistency) {
713 return consistencyName.get(consistency.toUpperCase());
716 public static void loadProperties() throws Exception {
717 Properties prop = new Properties();
718 InputStream input = null;
720 // load the properties file
721 input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
723 } catch (Exception ex) {
724 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
725 throw new Exception();
730 } catch (IOException e) {
735 // get the property value and return it
736 MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
737 String zkHosts = prop.getProperty("zookeeper.host");
738 MusicUtil.setMyZkHost(zkHosts);
739 MusicUtil.setCassName(prop.getProperty("cassandra.user"));
740 MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
741 MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
742 MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
743 MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
744 MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty("cacheobject.maxlife")));
747 public static void setNotifyInterval(int notifyinterval) {
748 MusicUtil.notifyinterval = notifyinterval;
750 public static void setNotifyTimeOut(int notifytimeout) {
751 MusicUtil.notifytimeout = notifytimeout;
754 public static int getNotifyInterval() {
755 return MusicUtil.notifyinterval;
758 public static int getNotifyTimeout() {
759 return MusicUtil.notifytimeout;
762 public static int getCacheObjectMaxLife() {
763 return MusicUtil.cacheObjectMaxLife;
766 public static void setCacheObjectMaxLife(int cacheObjectMaxLife) {
767 MusicUtil.cacheObjectMaxLife = cacheObjectMaxLife;
771 * Given the time of write for an update in a critical section, this method provides a transformed timestamp
772 * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
773 * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
774 * @param the UUID lock reference associated with the write.
775 * @param the long timeOfWrite which is the actual time at which the write took place
776 * @throws MusicServiceException
777 * @throws MusicQueryException
779 public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
780 // TODO: use acquire time instead of music eternity epoch
781 long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
786 public static MusicCoreService getMusicCoreService() {
787 if(getLockUsing().equals(MusicUtil.CASSANDRA))
788 return MusicCassaCore.getInstance();
790 return MusicCassaCore.getInstance();
797 public static Map<String, Object> validateLock(String lockName) {
798 Map<String, Object> resultMap = new HashMap<>();
799 String[] locks = lockName.split("\\.");
800 if(locks.length < 3) {
801 resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
804 String keyspace= locks[0];
805 if(keyspace.startsWith("$"))
806 keyspace = keyspace.substring(1);
807 resultMap.put("keyspace",keyspace);
812 public static void setIsCadi(boolean isCadi) {
813 MusicUtil.isCadi = isCadi;
816 public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
817 PreparedQueryObject updateQuery, String keyspace, String table,
818 Object cqlFormattedPrimaryKeyValue)
821 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
822 // write it back to a quorum
823 Row row = results.one();
824 ColumnDefinitions colInfo = row.getColumnDefinitions();
825 int totalColumns = colInfo.size();
827 StringBuilder fieldValueString = new StringBuilder("");
828 for (Definition definition : colInfo) {
829 String colName = definition.getName();
830 if (colName.equals(primaryKeyName))
832 DataType colType = definition.getType();
833 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
834 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
835 fieldValueString.append(colName + " = ?");
836 updateQuery.addValue(valueString);
837 if (counter != (totalColumns - 1))
838 fieldValueString.append(",");
839 counter = counter + 1;
841 updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
842 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
843 updateQuery.addValue(cqlFormattedPrimaryKeyValue);
845 MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
846 } catch (MusicServiceException | MusicQueryException e) {
847 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
848 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
852 public static boolean getIsCadi() {
853 return MusicUtil.isCadi;
858 * @return a random uuid
860 public static String generateUUID() {
861 String uuid = UUID.randomUUID().toString();
862 logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);