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;
52 import org.onap.music.datastore.MusicDataStoreHandle;
53 import org.onap.music.datastore.PreparedQueryObject;
54 import org.onap.music.eelf.logging.EELFLoggerDelegate;
55 import org.onap.music.eelf.logging.format.AppMessages;
56 import org.onap.music.eelf.logging.format.ErrorSeverity;
57 import org.onap.music.eelf.logging.format.ErrorTypes;
58 import org.onap.music.exceptions.MusicQueryException;
59 import org.onap.music.exceptions.MusicServiceException;
60 import org.onap.music.service.MusicCoreService;
61 import org.onap.music.service.impl.MusicCassaCore;
62 import org.onap.music.service.impl.MusicZKCore;
64 import com.datastax.driver.core.ConsistencyLevel;
65 import com.datastax.driver.core.DataType;
66 import com.sun.jersey.core.util.Base64;
71 * Properties This will take Properties and load them into MusicUtil.
72 * This is a hack for now. Eventually it would bebest to do this in
76 public class MusicUtil {
77 private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
79 public static final String ATOMIC = "atomic";
80 public static final String EVENTUAL = "eventual";
81 public static final String CRITICAL = "critical";
82 public static final String EVENTUAL_NB = "eventual_nb";
83 public static final String ALL = "all";
84 public static final String QUORUM = "quorum";
85 public static final String ONE = "one";
86 public static final String ATOMICDELETELOCK = "atomic_delete_lock";
87 public static final String DEFAULTKEYSPACENAME = "TBD";
88 private static final String XLATESTVERSION = "X-latestVersion";
89 private static final String XMINORVERSION = "X-minorVersion";
90 private static final String XPATCHVERSION = "X-patchVersion";
91 public static final String SELECT = "select";
92 public static final String INSERT = "insert";
93 public static final String UPDATE = "update";
94 public static final String UPSERT = "upsert";
95 public static final String USERID = "userId";
96 public static final String PASSWORD = "password";
97 public static final String CASSANDRA = "cassandra";
98 public static final String ZOOKEEPER = "zookeeper";
100 public static final String AUTHORIZATION = "Authorization";
102 private static final String LOCALHOST = "localhost";
103 private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
105 private static int myId = 0;
106 private static ArrayList<String> allIds = new ArrayList<>();
107 private static String publicIp = "";
108 private static ArrayList<String> allPublicIps = new ArrayList<>();
109 private static String myZkHost = LOCALHOST;
110 private static String myCassaHost = LOCALHOST;
111 private static String defaultMusicIp = LOCALHOST;
112 private static int cassandraPort = 9042;
113 private static int notifytimeout = 30000;
114 private static int notifyinterval = 5000;
115 private static int cacheObjectMaxLife = -1;
116 private static String lockUsing = MusicUtil.CASSANDRA;
117 private static boolean isCadi = false;
119 private static boolean debug = true;
120 private static String version = "2.3.0";
121 private static String musicRestIp = LOCALHOST;
122 private static String musicPropertiesFilePath = PROPERTIES_FILE;
123 private static long defaultLockLeasePeriod = 6000;
124 private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
125 "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
126 "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","admin.username","admin.password","aaf.admin.url",
127 "music.namespace","admin.aaf.role","cassandra.port","lock.using"};
128 private static final String[] cosistencyLevel = new String[] {
129 "ALL","EACH_QUORUM","QUORUM","LOCAL_QUORUM","ONE","TWO","THREE","LOCAL_ONE","ANY","SERIAL","LOCAL_SERIAL"};
130 private static final Map<String,ConsistencyLevel> consistencyName = new HashMap<>();
132 consistencyName.put("ONE",ConsistencyLevel.ONE);
133 consistencyName.put("TWO",ConsistencyLevel.TWO);
134 consistencyName.put("THREE",ConsistencyLevel.THREE);
135 consistencyName.put("SERIAL",ConsistencyLevel.SERIAL);
136 consistencyName.put("ALL",ConsistencyLevel.ALL);
137 consistencyName.put("EACH_QUORUM",ConsistencyLevel.EACH_QUORUM);
138 consistencyName.put("QUORUM",ConsistencyLevel.QUORUM);
139 consistencyName.put("LOCAL_QUORUM",ConsistencyLevel.LOCAL_QUORUM);
140 consistencyName.put("LOCAL_ONE",ConsistencyLevel.LOCAL_ONE);
141 consistencyName.put("LOCAL_SERIAL",ConsistencyLevel.LOCAL_SERIAL);
144 private static String cassName = "cassandra";
145 private static String cassPwd;
146 private static String aafEndpointUrl = null;
147 public static ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
148 private static String adminId = "username";
149 private static String adminPass= "password";
150 private static String aafAdminUrl= null;
151 private static String musicNamespace= "com.att.music.api";
152 private static String adminAafRole= "com.att.music.api.admin_api";
154 public static final long MusicEternityEpochMillis = 1533081600000L; // Wednesday, August 1, 2018 12:00:00 AM
156 public static final long MaxLockReferenceTimePart = 1000000000000L; // millis after eternity (eq sometime in 2050)
158 public static final long MaxCriticalSectionDurationMillis = 1L * 24 * 60 * 60 * 1000; // 1 day
161 public static String getLockUsing() {
166 public static void setLockUsing(String lockUsing) {
167 MusicUtil.lockUsing = lockUsing;
170 public static String getAafAdminUrl() {
175 public static void setAafAdminUrl(String aafAdminUrl) {
176 MusicUtil.aafAdminUrl = aafAdminUrl;
180 public static String getMusicNamespace() {
181 return musicNamespace;
185 public static void setMusicNamespace(String musicNamespace) {
186 MusicUtil.musicNamespace = musicNamespace;
190 public static String getAdminAafRole() {
195 public static void setAdminAafRole(String adminAafRole) {
196 MusicUtil.adminAafRole = adminAafRole;
201 public static String getAdminId() {
206 public static void setAdminId(String adminId) {
207 MusicUtil.adminId = adminId;
211 public static String getAdminPass() {
215 public static void setAdminPass(String adminPass) {
216 MusicUtil.adminPass = adminPass;
220 private MusicUtil() {
221 throw new IllegalStateException("Utility Class");
225 * @return cassandra port
227 public static int getCassandraPort() {
228 return cassandraPort;
233 * @param cassandraPort
235 public static void setCassandraPort(int cassandraPort) {
236 MusicUtil.cassandraPort = cassandraPort;
239 * @return the cassName
241 public static String getCassName() {
246 * @return the cassPwd
248 public static String getCassPwd() {
253 * @return the aafEndpointUrl
255 public static String getAafEndpointUrl() {
256 return aafEndpointUrl;
261 * @param aafEndpointUrl
263 public static void setAafEndpointUrl(String aafEndpointUrl) {
264 MusicUtil.aafEndpointUrl = aafEndpointUrl;
271 public static int getMyId() {
279 public static void setMyId(int myId) {
280 MusicUtil.myId = myId;
287 public static List<String> getAllIds() {
295 public static void setAllIds(List<String> allIds) {
296 MusicUtil.allIds = (ArrayList<String>) allIds;
303 public static String getPublicIp() {
311 public static void setPublicIp(String publicIp) {
312 MusicUtil.publicIp = publicIp;
319 public static List<String> getAllPublicIps() {
325 * @param allPublicIps
327 public static void setAllPublicIps(List<String> allPublicIps) {
328 MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
332 * Returns An array of property names that should be in the Properties
337 public static String[] getPropkeys() {
342 * Get MusicRestIp - default = localhost property file value - music.rest.ip
346 public static String getMusicRestIp() {
355 public static void setMusicRestIp(String musicRestIp) {
356 MusicUtil.musicRestIp = musicRestIp;
360 * Get MusicPropertiesFilePath - Default = /opt/music/music.properties
361 * property file value - music.properties
365 public static String getMusicPropertiesFilePath() {
366 return musicPropertiesFilePath;
370 * Set MusicPropertiesFilePath
372 * @param musicPropertiesFilePath
374 public static void setMusicPropertiesFilePath(String musicPropertiesFilePath) {
375 MusicUtil.musicPropertiesFilePath = musicPropertiesFilePath;
379 * Get DefaultLockLeasePeriod - Default = 6000 property file value -
384 public static long getDefaultLockLeasePeriod() {
385 return defaultLockLeasePeriod;
389 * Set DefaultLockLeasePeriod
391 * @param defaultLockLeasePeriod
393 public static void setDefaultLockLeasePeriod(long defaultLockLeasePeriod) {
394 MusicUtil.defaultLockLeasePeriod = defaultLockLeasePeriod;
402 public static void setDebug(boolean debug) {
403 MusicUtil.debug = debug;
407 * Is Debug - Default = true property file value - debug
411 public static boolean isDebug() {
420 public static void setVersion(String version) {
421 MusicUtil.version = version;
425 * Return the version property file value - version
429 public static String getVersion() {
434 * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
435 * value - zookeeper.host
439 public static String getMyZkHost() {
444 * Set MyZkHost - Zookeeper Hostname
448 public static void setMyZkHost(String myZkHost) {
449 MusicUtil.myZkHost = myZkHost;
453 * Get MyCassHost - Cassandra Hostname - Default = localhost property file
454 * value - cassandra.host
458 public static String getMyCassaHost() {
463 * Set MyCassHost - Cassandra Hostname
467 public static void setMyCassaHost(String myCassaHost) {
468 MusicUtil.myCassaHost = myCassaHost;
472 * Get DefaultMusicIp - Default = localhost property file value - music.ip
476 public static String getDefaultMusicIp() {
477 return defaultMusicIp;
483 * @param defaultMusicIp
485 public static void setDefaultMusicIp(String defaultMusicIp) {
486 MusicUtil.defaultMusicIp = defaultMusicIp;
493 public static String getTestType() {
494 String testType = "";
496 Scanner fileScanner = new Scanner(new File(""));
497 testType = fileScanner.next();// ignore the my id line
498 @SuppressWarnings("unused")
499 String batchSize = fileScanner.next();// ignore the my public ip
502 } catch (FileNotFoundException e) {
503 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
513 public static void sleep(long time) {
516 } catch (InterruptedException e) {
517 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
518 Thread.currentThread().interrupt();
523 * Utility function to check if the query object is valid.
529 public static boolean isValidQueryObject(boolean withparams, PreparedQueryObject queryObject) {
531 int noOfValues = queryObject.getValues().size();
533 char[] temp = queryObject.getQuery().toCharArray();
534 for (int i = 0; i < temp.length; i++) {
538 return (noOfValues == noOfParams);
540 return !queryObject.getQuery().isEmpty();
545 public static void setCassName(String cassName) {
546 MusicUtil.cassName = cassName;
549 public static void setCassPwd(String cassPwd) {
550 MusicUtil.cassPwd = cassPwd;
553 @SuppressWarnings("unchecked")
554 public static String convertToCQLDataType(DataType type, Object valueObj) throws Exception {
557 switch (type.getName()) {
559 value = valueObj + "";
563 String valueString = valueObj + "";
564 valueString = valueString.replace("'", "''");
565 value = "'" + valueString + "'";
568 Map<String, Object> otMap = (Map<String, Object>) valueObj;
569 value = "{" + jsonMaptoSqlString(otMap, ",") + "}";
573 value = valueObj + "";
584 * @throws MusicTypeConversionException
587 @SuppressWarnings("unchecked")
588 public static Object convertToActualDataType(DataType colType, Object valueObj) throws Exception {
589 String valueObjString = valueObj + "";
590 switch (colType.getName()) {
592 return UUID.fromString(valueObjString);
594 return BigInteger.valueOf(Long.parseLong(valueObjString));
596 return Long.parseLong(valueObjString);
598 return Integer.parseInt(valueObjString);
600 return Float.parseFloat(valueObjString);
602 return Double.parseDouble(valueObjString);
604 return Boolean.parseBoolean(valueObjString);
606 return (Map<String, Object>) valueObj;
608 return (List<Object>)valueObj;
612 return valueObjString;
616 public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
617 ByteBuffer buffer = ByteBuffer.wrap(valueObj);
623 * Utility function to parse json map into sql like string
626 * @param lineDelimiter
630 public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
631 StringBuilder sqlString = new StringBuilder();
633 for (Map.Entry<String, Object> entry : jMap.entrySet()) {
634 Object ot = entry.getValue();
635 String value = ot + "";
636 if (ot instanceof String) {
637 value = "'" + value.replace("'", "''") + "'";
639 sqlString.append("'" + entry.getKey() + "':" + value);
640 if (counter != jMap.size() - 1)
641 sqlString.append(lineDelimiter);
642 counter = counter + 1;
644 return sqlString.toString();
647 @SuppressWarnings("unused")
648 public static String buildVersion(String major, String minor, String patch) {
650 major += "." + minor;
652 major += "." + patch;
659 * Currently this will build a header with X-latestVersion, X-minorVersion and X-pathcVersion
660 * X-latestVerstion will be equal to the latest full version.
661 * X-minorVersion - will be equal to the latest minor version.
662 * X-pathVersion - will be equal to the latest patch version.
663 * Future plans will change this.
670 public static ResponseBuilder buildVersionResponse(String major, String minor, String patch) {
671 ResponseBuilder response = Response.noContent();
672 String versionIn = buildVersion(major,minor,patch);
673 String version = MusicUtil.getVersion();
674 String[] verArray = version.split("\\.",3);
675 if ( minor != null ) {
676 response.header(XMINORVERSION,minor);
678 response.header(XMINORVERSION,verArray[1]);
680 if ( patch != null ) {
681 response.header(XPATCHVERSION,patch);
683 response.header(XPATCHVERSION,verArray[2]);
685 response.header(XLATESTVERSION,version);
686 logger.info(EELFLoggerDelegate.applicationLogger,"Version In:" + versionIn);
691 public static Map<String,String> extractBasicAuthentication(String authorization){
692 Map<String,String> authValues = new HashMap<>();
693 if(authorization == null) {
694 authValues.put("ERROR", "Authorization cannot be null");
697 authorization = authorization.replaceFirst("Basic", "");
698 String decoded = Base64.base64Decode(authorization);
699 StringTokenizer token = new StringTokenizer(decoded, ":");
700 authValues.put(MusicUtil.USERID, token.nextToken());
701 authValues.put(MusicUtil.PASSWORD,token.nextToken());
706 public static boolean isValidConsistency(String consistency) {
707 for (String string : cosistencyLevel) {
708 if (string.equalsIgnoreCase(consistency))
715 public static ConsistencyLevel getConsistencyLevel(String consistency) {
716 return consistencyName.get(consistency.toUpperCase());
719 public static void loadProperties() throws Exception {
720 Properties prop = new Properties();
721 InputStream input = null;
723 // load the properties file
724 input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
726 } catch (Exception ex) {
727 logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
728 throw new Exception();
733 } catch (IOException e) {
738 // get the property value and return it
739 MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
740 String zkHosts = prop.getProperty("zookeeper.host");
741 MusicUtil.setMyZkHost(zkHosts);
742 MusicUtil.setCassName(prop.getProperty("cassandra.user"));
743 MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
744 MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
745 MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
746 MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
747 MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty("cacheobject.maxlife")));
750 public static void setNotifyInterval(int notifyinterval) {
751 MusicUtil.notifyinterval = notifyinterval;
753 public static void setNotifyTimeOut(int notifytimeout) {
754 MusicUtil.notifytimeout = notifytimeout;
757 public static int getNotifyInterval() {
758 return MusicUtil.notifyinterval;
761 public static int getNotifyTimeout() {
762 return MusicUtil.notifytimeout;
765 public static int getCacheObjectMaxLife() {
766 return MusicUtil.cacheObjectMaxLife;
769 public static void setCacheObjectMaxLife(int cacheObjectMaxLife) {
770 MusicUtil.cacheObjectMaxLife = cacheObjectMaxLife;
774 * Given the time of write for an update in a critical section, this method provides a transformed timestamp
775 * that ensures that a previous lock holder who is still alive can never corrupt a later critical section.
776 * The main idea is to us the lock reference to clearly demarcate the timestamps across critical sections.
777 * @param the UUID lock reference associated with the write.
778 * @param the long timeOfWrite which is the actual time at which the write took place
779 * @throws MusicServiceException
780 * @throws MusicQueryException
782 public static long v2sTimeStampInMicroseconds(long ordinal, long timeOfWrite) throws MusicServiceException, MusicQueryException {
783 // TODO: use acquire time instead of music eternity epoch
784 long ts = ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
789 public static MusicCoreService getMusicCoreService() {
790 if(getLockUsing().equals(MusicUtil.CASSANDRA))
791 return MusicCassaCore.getInstance();
792 else if (getLockUsing().equals(MusicUtil.ZOOKEEPER))
793 return MusicZKCore.getInstance();
795 return MusicCassaCore.getInstance();
802 public static Map<String, Object> validateLock(String lockName) {
803 Map<String, Object> resultMap = new HashMap<>();
804 String[] locks = lockName.split("\\.");
805 if(locks.length < 3) {
806 resultMap.put("Error", "Invalid lock. Please make sure lock is of the type keyspaceName.tableName.primaryKey");
809 String keyspace= locks[0];
810 if(keyspace.startsWith("$"))
811 keyspace = keyspace.substring(1);
812 resultMap.put("keyspace",keyspace);
817 public static void setIsCadi(boolean isCadi) {
818 // TODO Auto-generated method stub
819 MusicUtil.isCadi = isCadi;
822 public static void writeBackToQuorum(PreparedQueryObject selectQuery, String primaryKeyName,
823 PreparedQueryObject updateQuery, String keyspace, String table,
824 Object cqlFormattedPrimaryKeyValue)
827 ResultSet results = MusicDataStoreHandle.getDSHandle().executeQuorumConsistencyGet(selectQuery);
828 // write it back to a quorum
829 Row row = results.one();
830 ColumnDefinitions colInfo = row.getColumnDefinitions();
831 int totalColumns = colInfo.size();
833 StringBuilder fieldValueString = new StringBuilder("");
834 for (Definition definition : colInfo) {
835 String colName = definition.getName();
836 if (colName.equals(primaryKeyName))
838 DataType colType = definition.getType();
839 Object valueObj = MusicDataStoreHandle.getDSHandle().getColValue(row, colName, colType);
840 Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
841 fieldValueString.append(colName + " = ?");
842 updateQuery.addValue(valueString);
843 if (counter != (totalColumns - 1))
844 fieldValueString.append(",");
845 counter = counter + 1;
847 updateQuery.appendQueryString("UPDATE " + keyspace + "." + table + " SET "
848 + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
849 updateQuery.addValue(cqlFormattedPrimaryKeyValue);
851 MusicDataStoreHandle.getDSHandle().executePut(updateQuery, "critical");
852 } catch (MusicServiceException | MusicQueryException e) {
853 logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,
854 ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
858 public static boolean getIsCadi() {
859 return MusicUtil.isCadi;