c5e8c37cbd2c095feda40033da44bb6bb2032617
[music.git] / src / main / java / org / onap / music / main / PropertiesListener.java
1 /*
2  * ============LICENSE_START==========================================
3  * org.onap.music
4  * ===================================================================
5  *  Copyright (c) 2017 AT&T Intellectual Property
6  *  Modifications Copyright (C) 2018 IBM.
7  * ===================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  * 
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  * 
20  * ============LICENSE_END=============================================
21  * ====================================================================
22  */
23
24 package org.onap.music.main;
25
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.URL;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Iterator;
33 import java.util.Properties;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37
38 import javax.servlet.ServletContextEvent;
39 import javax.servlet.ServletContextListener;
40
41 import org.onap.music.datastore.PreparedQueryObject;
42 import org.onap.music.eelf.logging.EELFLoggerDelegate;
43 import org.onap.music.eelf.logging.format.AppMessages;
44 import org.onap.music.eelf.logging.format.ErrorSeverity;
45 import org.onap.music.eelf.logging.format.ErrorTypes;
46
47 import org.onap.music.exceptions.MusicLockingException;
48 import org.onap.music.exceptions.MusicServiceException;
49
50 import com.datastax.driver.core.ResultSet;
51 import com.datastax.driver.core.Row;
52
53 public class PropertiesListener { // implements ServletContextListener {
54     private Properties prop;
55     private static final String MUSIC_PROPERTIES="music.properties";
56 /*    private Properties prop;
57
58 >>>>>>> c8db07f77a945bc22046ef50d773c3c3608b014a
59     private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesListener.class);
60
61     @Override
62     public void contextInitialized(ServletContextEvent servletContextEvent) {
63         prop = new Properties();
64         Properties projectProp = new Properties();
65         URL resource = getClass().getResource("/");
66         String musicPropertiesFilePath = resource.getPath().replace("WEB-INF/classes/","WEB-INF/classes/project.properties");
67
68         // Open the file
69         try {
70             InputStream musicProps = null;
71             projectProp.load(new FileInputStream(musicPropertiesFilePath));
72             if (projectProp.containsKey(MUSIC_PROPERTIES)) {
73                 musicProps = new FileInputStream(projectProp.getProperty(MUSIC_PROPERTIES));
74             } else {
75                 musicProps = new FileInputStream(MusicUtil.getMusicPropertiesFilePath());
76             }
77             prop.load(musicProps);
78             musicProps.close();
79             prop.putAll(projectProp);
80             String[] propKeys = MusicUtil.getPropkeys();
81             for (int k = 0; k < propKeys.length; k++) {
82                 String key = propKeys[k];
83                 if (prop.containsKey(key) && prop.get(key) != null) {
84                     logger.info(key + " : " + prop.getProperty(key));
85                     switch (key) {
86                         case "zookeeper.host":
87                             MusicUtil.setMyZkHost(prop.getProperty(key));
88                             break;
89                         case "cassandra.host":
90                             MusicUtil.setMyCassaHost(prop.getProperty(key));
91                             break;
92                         case "music.ip":
93                             MusicUtil.setDefaultMusicIp(prop.getProperty(key));
94                             break;
95                         case "debug":
96                             MusicUtil.setDebug(Boolean
97                                             .getBoolean(prop.getProperty(key).toLowerCase()));
98                             break;
99                         case "version":
100                             MusicUtil.setVersion(prop.getProperty(key));
101                             break;
102                         case "music.rest.ip":
103                             MusicUtil.setMusicRestIp(prop.getProperty(key));
104                             break;
105                         case MUSIC_PROPERTIES:
106                             MusicUtil.setMusicPropertiesFilePath(prop.getProperty(key));
107                             break;
108                         case "lock.lease.period":
109                             MusicUtil.setDefaultLockLeasePeriod(
110                                             Long.parseLong(prop.getProperty(key)));
111                             break;
112                         case "my.id":
113                             MusicUtil.setMyId(Integer.parseInt(prop.getProperty(key)));
114                             break;
115                         case "all.ids":
116                             String[] ids = prop.getProperty(key).split(":");
117                             MusicUtil.setAllIds(new ArrayList<String>(Arrays.asList(ids)));
118                             break;
119                         case "public.ip":
120                             MusicUtil.setPublicIp(prop.getProperty(key));
121                             break;
122                         case "all.public.ips":
123                             String[] ips = prop.getProperty(key).split(":");
124                             if (ips.length == 1) {
125                                 // Future use
126                             } else if (ips.length > 1) {
127                                 MusicUtil.setAllPublicIps(
128                                                 new ArrayList<String>(Arrays.asList(ips)));
129                             }
130                             break;
131                         case "cassandra.user":
132                             MusicUtil.setCassName(prop.getProperty(key));
133                             break;
134                         case "cassandra.password":
135                             MusicUtil.setCassPwd(prop.getProperty(key));
136                             break;
137                         case "aaf.endpoint.url":
138                             MusicUtil.setAafEndpointUrl(prop.getProperty(key));
139                             break;
140                         case "admin.username":
141                             MusicUtil.setAdminId(prop.getProperty(key));
142                             break;
143                         case "admin.password":
144                             MusicUtil.setAdminPass(prop.getProperty(key));
145                             break;
146                         case "cassandra.port":
147                             MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty(key)));
148                             break;
149                         case "aaf.admin.url":
150                             MusicUtil.setAafAdminUrl(prop.getProperty(key));
151                             break;
152                         case "music.namespace":
153                             MusicUtil.setMusicNamespace(prop.getProperty(key));
154                             break;
155                         case "admin.aaf.role":
156                             MusicUtil.setAdminAafRole(prop.getProperty(key));
157                             break; 
158                         case "notify.interval":
159                             MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty(key)));
160                             break;
161                         case "notify.timeout":
162                             MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty(key)));
163                             break;
164                         case "lock.using":
165                             MusicUtil.setLockUsing(prop.getProperty(key));
166                             break; 
167                         case "cacheobject.maxlife":
168                             MusicUtil.setCacheObjectMaxLife(Integer.parseInt(prop.getProperty(key)));
169                             CachingUtil.setCacheEternalProps();
170                             break;
171                         default:
172                             logger.error(EELFLoggerDelegate.errorLogger,
173                                             "No case found for " + key);
174                     }
175                 }
176             }
177         } catch (IOException e) {
178             logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR  ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR);
179             logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
180         }
181
182         logger.info(EELFLoggerDelegate.applicationLogger,
183                         "Starting MUSIC " + MusicUtil.getVersion() + " on node with id "
184                                         + MusicUtil.getMyId() + " and public ip "
185                                         + MusicUtil.getPublicIp() + "...");
186         logger.info(EELFLoggerDelegate.applicationLogger,
187                         "List of all MUSIC ids:" + MusicUtil.getAllIds().toString());
188         logger.info(EELFLoggerDelegate.applicationLogger,
189                         "List of all MUSIC public ips:" + MusicUtil.getAllPublicIps().toString());
190         
191         scheduleCronJobForZKCleanup();
192     }
193
194     @Override
195     public void contextDestroyed(ServletContextEvent servletContextEvent) {
196         prop = null;
197     }
198     
199     
200     private ScheduledExecutorService scheduler;
201     public void scheduleCronJobForZKCleanup() {
202         scheduler = Executors.newSingleThreadScheduledExecutor();
203         scheduler.scheduleAtFixedRate(new CachingUtil(), 0, 24, TimeUnit.HOURS);
204         PreparedQueryObject pQuery = new PreparedQueryObject();
205         String consistency = MusicUtil.EVENTUAL;
206         pQuery.appendQueryString("CREATE TABLE IF NOT EXISTS admin.locks ( lock_id text PRIMARY KEY, ctime text)");
207         try {
208             ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
209         } catch (MusicServiceException e1) {
210             logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),ErrorSeverity.ERROR);
211         }
212
213       //Zookeeper cleanup
214         scheduler.scheduleAtFixedRate(new Runnable() {
215             @Override
216             public void run() {
217                 deleteLocksFromDB();
218             }
219         } , 0, 24, TimeUnit.HOURS);
220     }
221
222
223     public void deleteLocksFromDB() {
224         PreparedQueryObject pQuery = new PreparedQueryObject();
225         pQuery.appendQueryString(
226                         "select * from admin.locks");
227             try {
228                 ResultSet rs = MusicCore.get(pQuery);
229                 Iterator<Row> it = rs.iterator();
230                 StringBuilder deleteKeys = new StringBuilder();
231                 Boolean expiredKeys = false;
232                 while (it.hasNext()) {
233                     Row row = (Row) it.next();
234                     String id = row.getString("lock_id");
235                     long ctime = Long.parseLong(row.getString("ctime"));
236                     if(System.currentTimeMillis() >= ctime + 24 * 60 * 60 * 1000) {
237                         expiredKeys = true;
238                         String new_id = id.substring(1);
239                         try {
240                             MusicCore.deleteLock(new_id);
241                         } catch (MusicLockingException e) {
242                             logger.info(EELFLoggerDelegate.applicationLogger,
243                                      e.getMessage());
244                         }
245                         deleteKeys.append("'").append(id).append("'").append(",");
246                     }
247                 }
248                 if(expiredKeys) {
249                     deleteKeys.deleteCharAt(deleteKeys.length()-1);
250                     CachingUtil.deleteKeysFromDB(deleteKeys.toString());
251                }
252             } catch (MusicServiceException e) {
253                 logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),ErrorSeverity.ERROR);
254             }
255     }
256 */
257 }