2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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 * ============LICENSE_END=========================================================
22 package org.openecomp.mso.bpmn.core;
24 import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.nio.file.ClosedWatchServiceException;
30 import java.nio.file.FileSystems;
31 import java.nio.file.Path;
32 import java.nio.file.WatchEvent;
33 import java.nio.file.WatchKey;
34 import java.nio.file.WatchService;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.List;
41 import java.util.Map.Entry;
42 import java.util.Properties;
43 import java.util.Timer;
44 import java.util.TimerTask;
45 import java.util.concurrent.ConcurrentHashMap;
49 import org.openecomp.mso.logger.MessageEnum;
50 import org.openecomp.mso.logger.MsoLogger;
53 * Loads the property configuration from file system and refreshes the
54 * properties when the property gets changed.
56 * WARNING: automatic refreshes might not work on network filesystems.
58 public class PropertyConfiguration {
61 * The base name of the MSO BPMN properties file (mso.bpmn.properties).
63 public static final String MSO_BPMN_PROPERTIES = "mso.bpmn.properties";
66 * The base name of the MSO BPMN URN-Mappings properties file (mso.bpmn.urn.properties).
68 public static final String MSO_BPMN_URN_PROPERTIES = "mso.bpmn.urn.properties";
71 * The base name of the MSO Topology properties file (topology.properties).
73 public static final String MSO_TOPOLOGY_PROPERTIES = "topology.properties";
75 * The name of the meta-property holding the time the properties were loaded
78 public static final String TIMESTAMP_PROPERTY = "mso.properties.timestamp";
80 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
82 private static final List<String> SUPPORTED_FILES =
83 Arrays.asList(MSO_BPMN_PROPERTIES, MSO_BPMN_URN_PROPERTIES, MSO_TOPOLOGY_PROPERTIES);
85 private volatile String msoConfigPath = null;
87 private final ConcurrentHashMap<String, Map<String, String>> propFileCache =
88 new ConcurrentHashMap<>();
90 private final Object CACHELOCK = new Object();
91 private FileWatcherThread fileWatcherThread = null;
93 // The key is the file name
94 private Map<String, TimerTask> timerTaskMap = new HashMap<>();
97 * Private Constructor.
99 private PropertyConfiguration() {
104 * Singleton holder pattern eliminates locking when accessing the instance
105 * and still provides for lazy initialization.
107 private static class PropertyConfigurationInstanceHolder {
108 private static PropertyConfiguration instance = new PropertyConfiguration();
112 * Gets the one and only instance of this class.
114 public static PropertyConfiguration getInstance() {
115 return PropertyConfigurationInstanceHolder.instance;
118 static void resetPropertyConfigurationSingletonInstance(){
119 PropertyConfigurationInstanceHolder.instance = new PropertyConfiguration();
123 * Returns the list of supported files.
125 public static List<String> supportedFiles() {
126 return new ArrayList<>(SUPPORTED_FILES);
130 * May be called to restart the PropertyConfiguration if it was previously shut down.
132 public synchronized void startUp() {
133 msoConfigPath = System.getProperty("mso.config.path");
135 if (msoConfigPath == null) {
136 LOGGER.debug("mso.config.path JVM system property is not set");
141 Path directory = FileSystems.getDefault().getPath(msoConfigPath);
142 WatchService watchService = FileSystems.getDefault().newWatchService();
143 directory.register(watchService, ENTRY_MODIFY);
145 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN", "Starting FileWatcherThread");
146 LOGGER.debug("Starting FileWatcherThread");
147 fileWatcherThread = new FileWatcherThread(watchService);
148 fileWatcherThread.start();
149 } catch (Exception e) {
150 LOGGER.debug("Error occurred while starting FileWatcherThread:", e);
152 MessageEnum.BPMN_GENERAL_EXCEPTION,
154 "Property Configuration",
155 MsoLogger.ErrorCode.UnknownError,
156 "Error occurred while starting FileWatcherThread:" + e);
161 * May be called to shut down the PropertyConfiguration. A shutDown followed
162 * by a startUp will reset the PropertyConfiguration to its initial state.
164 public synchronized void shutDown() {
165 if (fileWatcherThread != null) {
166 LOGGER.debug("Shutting down FileWatcherThread " + System.identityHashCode(fileWatcherThread));
167 fileWatcherThread.shutdown();
169 long waitInSeconds = 10;
172 fileWatcherThread.join(waitInSeconds * 1000);
173 } catch (InterruptedException e) {
174 LOGGER.debug("FileWatcherThread " + System.identityHashCode(fileWatcherThread)
175 + " shutdown did not occur within " + waitInSeconds + " seconds",e);
178 LOGGER.debug("Finished shutting down FileWatcherThread " + System.identityHashCode(fileWatcherThread));
179 fileWatcherThread = null;
183 msoConfigPath = null;
186 public synchronized boolean isFileWatcherRunning() {
187 return fileWatcherThread != null;
190 public void clearCache() {
191 synchronized(CACHELOCK) {
192 propFileCache.clear();
196 public int cacheSize() {
197 return propFileCache.size();
200 // TODO: throw IOException?
201 public Map<String, String> getProperties(String fileName) {
202 Map<String, String> properties = propFileCache.get(fileName);
204 if (properties == null) {
205 if (!SUPPORTED_FILES.contains(fileName)) {
206 throw new IllegalArgumentException("Not a supported property file: " + fileName);
209 if (msoConfigPath == null) {
210 LOGGER.debug("mso.config.path JVM system property must be set to load " + fileName);
213 MessageEnum.BPMN_GENERAL_EXCEPTION,
216 MsoLogger.ErrorCode.UnknownError,
217 "mso.config.path JVM system property must be set to load " + fileName);
223 properties = readProperties(new File(msoConfigPath, fileName));
224 } catch (Exception e) {
225 LOGGER.debug("Error loading " + fileName);
228 MessageEnum.BPMN_GENERAL_EXCEPTION,
231 MsoLogger.ErrorCode.UnknownError,
232 "Error loading " + fileName, e);
238 return Collections.unmodifiableMap(properties);
242 * Reads properties from the specified file, updates the property file cache, and
243 * returns the properties in a map.
244 * @param file the file to read
245 * @return a map of properties
247 private Map<String, String> readProperties(File file) throws IOException {
248 String fileName = file.getName();
249 LOGGER.debug("Reading " + fileName);
251 Map<String, String> properties = new HashMap<>();
252 Properties newProperties = new Properties();
254 try (FileReader reader = new FileReader(file)) {
255 newProperties.load(reader);
257 catch (Exception e) {
258 LOGGER.debug("Exception :",e);
261 for (Entry<Object, Object> entry : newProperties.entrySet()) {
262 properties.put(entry.getKey().toString(), entry.getValue().toString());
265 properties.put(TIMESTAMP_PROPERTY, String.valueOf(System.currentTimeMillis()));
267 synchronized(CACHELOCK) {
268 propFileCache.put(fileName, properties);
275 * File watcher thread which monitors a directory for file modification.
277 private class FileWatcherThread extends Thread {
278 private final WatchService watchService;
279 private final Timer timer = new Timer("FileWatcherTimer");
281 public FileWatcherThread(WatchService service) {
282 this.watchService = service;
285 public void shutdown() {
291 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN",
292 "FileWatcherThread started");
294 LOGGER.debug("Started FileWatcherThread " + System.identityHashCode(fileWatcherThread));
297 WatchKey watchKey = null;
299 while (!isInterrupted()) {
301 if (watchKey != null) {
305 watchKey = watchService.take();
307 for (WatchEvent<?> event : watchKey.pollEvents()) {
308 @SuppressWarnings("unchecked")
309 WatchEvent<Path> pathEvent = (WatchEvent<Path>) event;
311 if ("EVENT_OVERFLOW".equals(pathEvent.kind())) {
312 LOGGER.debug("Ignored overflow event for " + msoConfigPath);
316 String fileName = pathEvent.context().getFileName().toString();
318 if (!SUPPORTED_FILES.contains(fileName)) {
319 LOGGER.debug("Ignored modify event for " + fileName);
323 LOGGER.debug("Configuration file has changed: " + fileName);
325 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN",
326 "Configuation file has changed: " + fileName);
328 // There's a potential problem here. The MODIFY event is
329 // triggered as soon as somebody starts writing the file but
330 // there's no obvious way to know when the write is done. If we
331 // read the file while the write is still in progress, then the
332 // cache can really be messed up. As a workaround, we use a timer
333 // to sleep for at least one second, and then we sleep for as long
334 // as it takes for the file's lastModified time to stop changing.
335 // The timer has another benefit: it consolidates multiple events
336 // that we seem to receive when a file is modified.
338 synchronized(timerTaskMap) {
339 TimerTask task = timerTaskMap.get(fileName);
345 File file = new File(msoConfigPath, fileName);
346 task = new DelayTimerTask(timer, file, 1000);
347 timerTaskMap.put(fileName, task);
350 } catch (InterruptedException e) {
351 LOGGER.debug("InterruptedException :",e);
353 } catch (ClosedWatchServiceException e) {
355 MessageEnum.BPMN_GENERAL_INFO,
357 "FileWatcherThread shut down because the watch service was closed");
358 LOGGER.debug("ClosedWatchServiceException :",e);
360 } catch (Exception e) {
362 MessageEnum.BPMN_GENERAL_EXCEPTION,
364 "Property Configuration",
365 MsoLogger.ErrorCode.UnknownError,
366 "FileWatcherThread caught unexpected " + e.getClass().getSimpleName(), e);
373 synchronized(timerTaskMap) {
374 timerTaskMap.clear();
378 watchService.close();
379 } catch (IOException e) {
380 LOGGER.debug("FileWatcherThread caught " + e.getClass().getSimpleName()
381 + " while closing the watch service",e);
384 LOGGER.info(MessageEnum.BPMN_GENERAL_INFO, "BPMN",
385 "FileWatcherThread stopped");
390 private class DelayTimerTask extends TimerTask {
391 private final File file;
392 private final long lastModifiedTime;
393 private final Timer timer;
395 public DelayTimerTask(Timer timer, File file, long delay) {
398 this.lastModifiedTime = file.lastModified();
399 timer.schedule(this, delay);
405 long newLastModifiedTime = file.lastModified();
407 if (newLastModifiedTime == lastModifiedTime) {
409 readProperties(file);
410 } catch (Exception e) {
412 MessageEnum.BPMN_GENERAL_EXCEPTION,
414 "Property Configuration",
415 MsoLogger.ErrorCode.UnknownError,
416 "Unable to reload " + file, e);
419 LOGGER.debug("Delaying reload of " + file + " by 1 second");
421 synchronized(timerTaskMap) {
422 TimerTask task = timerTaskMap.get(file.getName());
424 if (task != null && task != this) {
428 task = new DelayTimerTask(timer, file, 1000);
429 timerTaskMap.put(file.getName(), task);
433 synchronized(timerTaskMap) {
434 TimerTask task = timerTaskMap.get(file.getName());
437 timerTaskMap.remove(file.getName());