Neon SR1 upgrade
[appc.git] / appc-core / appc-common-bundle / java / org / onap / appc / configuration / ConfigurationFactory.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.configuration;
25
26 import java.io.BufferedInputStream;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.text.DateFormat;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.Optional;
35 import java.util.Properties;
36 import java.util.concurrent.locks.ReentrantReadWriteLock;
37 import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
39 import org.onap.appc.i18n.Msg;
40 import com.att.eelf.configuration.EELFLogger;
41 import com.att.eelf.configuration.EELFManager;
42 import com.att.eelf.i18n.EELFResourceManager;
43
44 /**
45  * The configuration factory is used to obtain access to an already created and initialized
46  * singleton configuration object as well as to create and initialize the singleton if not already
47  * set up.
48  * <p>
49  * This class is responsible for the creation of the configuration object used to manage the
50  * configuration of the application. The configuration object implementation must implement the
51  * <code>Configuration</code> interface. This allows for the factory to create different
52  * specializations in the future if needed and not break any application code.
53  * </p>
54  * <p>
55  * The configuration object is basically a wrapper around a properties object. The configuration is
56  * therefore specified as a set of properties that are loaded and processed from different sources
57  * with different precedences. It is important that the configuration object always be able to
58  * supply default values for any configuration properties that must be supplied, and not rely on the
59  * user always supplying these values. This also relieves the application itself from having to
60  * interpret missing or invalid properties and applying defaults. By having all of the defaults in
61  * one place, the application code can be simpler (not having to worry about defaults or invalid
62  * properties), and the defaults can be changed much easier (they are all in one place and not
63  * distributed throughout the codebase).
64  * </p>
65  * <p>
66  * Since the configuration is managed as a property object, we can use a characteristic of the
67  * <code>Properties</code> class to our advantage. Namely, if we put a property into a
68  * <code>Properties</code> object that already exists, the <code>Properties</code> object replaces
69  * it with the new value. This does not affect any other properties that may already be defined in
70  * the properties object. This gives us the ability to initialize the properties with default values
71  * for all of the application settings, then override just those that we need to override, possibly
72  * from multiple sources and in increasing order of precedence.
73  * </p>
74  * <p>
75  * This means that properties are in effect "merged" together from multiple sources in a prescribed
76  * precedence order. In fact, the precedence order that this factory implements is defined as:
77  * </p>
78  * <ol>
79  * <li>Default values from a system resource file.</li>
80  * <li>User-supplied properties file, if any.</li>
81  * <li>Application-supplied properties, if any.</li>
82  * <li>Command-line properties (if any)</li>
83  * </ol>
84  * <p>
85  * The name and location of the properties file that is loaded can also be set, either in the
86  * defaults, overridden by the system command line via -D, or as a system environment variable.
87  * There are two properties that can be specified to define the name and path. These are:
88  * </p>
89  * <dl>
90  * <dt>org.onap.appc.bootstrap.file</dt>
91  * <dd>This property defines the name of the file that will be loaded. If not specified, the default
92  * value is "appc.properties". This can be specified in either (or both) the default properties or
93  * the command line. The command line specification will always override.</dd>
94  * <dt>org.onap.appc.bootstrap.path</dt>
95  * <dd>This is a comma-delimited (,) path of directories to be searched to locate the specified
96  * file. The first occurrence of the file is the one loaded, and no additional searching is
97  * performed. The path can be specified in either, or both, the default values and the command line
98  * specification. If specified on the command line, the value overrides the default values. If
99  * omitted, the default path is <code>$/opt/onap/appc/data/properties,${user.home},.</code></dd>
100  * </dl>
101  *
102  * @since Mar 18, 2014
103  * @version $Id$
104  */
105 public final class ConfigurationFactory {
106
107     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ConfigurationFactory.class);
108
109     /**
110      * This is a string constant for the comma character. It's intended to be used a common string
111      * delimiter.
112      */
113     private static final String COMMA = ",";
114
115     /**
116      * The default Configuration object that implements the <code>Configuration</code> interface and
117      * represents our system configuration settings.
118      */
119     private static DefaultConfiguration config = null;
120
121     /**
122      * The default properties resource to be loaded
123      */
124     private static final String DEFAULT_PROPERTIES = "org/onap/appc/default.properties";
125
126     /**
127      * This collection allows for special configurations to be created and maintained, organized by
128      * some identification (such as an object reference to the StackBuilder to which they apply),
129      * and then obtained from the configuration factory when needed.
130      */
131     private static HashMap<Object, Configuration> localConfigs = new HashMap<>();
132
133     /**
134      * The reentrant shared lock used to serialize access to the properties.
135      */
136     private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
137
138     /**
139      * This is a constant array of special property names that will be copied from the configuration
140      * back to the System properties object if they are defined in the configuration AND they do not
141      * already exist in the System properties object. These are intended as a convenience for
142      * setting the AFT properties for the Discovery client where it may be difficult or impossible
143      * to set VM arguments for the container.
144      */
145     private static final String[] specialProperties =
146             {"AFT_LATITUDE", "AFT_LONGITUDE", "AFT_ENVIRONMENT", "SCLD_PLATFORM"};
147
148     private ConfigurationFactory() {}
149
150     /**
151      * This method is used to obtain the common configuration object (as well as set it up if not
152      * already).
153      *
154      * @return The configuration object implementation
155      */
156     public static Configuration getConfiguration() {
157
158         /*
159          * First, attempt to access the properties as a read lock holder
160          */
161         ReadLock readLock = lock.readLock();
162         readLock.lock();
163         try {
164
165             /*
166              * If the properties don't exist, release the read lock and acquire the write lock. Once
167              * we get the write lock, we need to re-check to see that the configuration needs to be
168              * set up (because another thread may have beat us to it). After we get a configuration
169              * set up, release the write lock and re-obtain the read lock to access the properties.
170              */
171             if (config == null) {
172                 readLock.unlock();
173                 WriteLock writeLock = lock.writeLock();
174                 writeLock.lock();
175                 try {
176                     if (config == null) {
177                         config = new DefaultConfiguration();
178                         initialize(null);
179                     }
180                 } catch (Exception e){
181                     logger.error("getConfiguration", e);
182                 } finally {
183                     writeLock.unlock();
184                 }
185                 readLock.lock();
186             }
187         } finally {
188             readLock.unlock();
189         }
190         return config;
191     }
192
193     /**
194      * This method will obtain the local configuration for the specified object if it exists, or
195      * will create it from the current global configuration. This allows the configuration to be
196      * tailored for a specific process or operation, and uniquely identified by some value (such as
197      * the object that represents the special use of the configuration).
198      *
199      * @param owner The owner or identification of the owner of the special configuration
200      * @return The special configuration object, or a clone of the global configuration so that it
201      *         can be altered if needed.
202      */
203     public static Configuration getConfiguration(final Object owner) {
204         DefaultConfiguration local;
205         ReadLock readLock = lock.readLock();
206         readLock.lock();
207         try {
208             local = (DefaultConfiguration) localConfigs.get(owner);
209             if (local == null) {
210                 readLock.unlock();
211                 WriteLock writeLock = lock.writeLock();
212                 writeLock.lock();
213                 local = (DefaultConfiguration) localConfigs.get(owner);
214                 if (local == null) {
215                     local = getClonedDefaultConfiguration(owner, local);
216                 }
217                 writeLock.unlock();
218             }
219             readLock.lock();
220         } finally {
221             readLock.unlock();
222         }
223         return local;
224     }
225
226     /**
227      * This method allows the caller to alter the configuration, supplying the specified
228      * configuration properties which override the application default values.
229      * <p>
230      * The configuration is re-constructed (if already constructed) or created new (if not already
231      * created) and the default properties are loaded into the configuration.
232      * </p>
233      * <p>
234      * The primary purpose of this method is to allow the application configuration properties to be
235      * reset or refreshed after the application has already been initialized. This method will lock
236      * the configuration for the duration while it is being re-built, and should not be called on a
237      * regular basis.
238      * </p>
239      *
240      * @param props The properties used to configure the application.
241      * @return Access to the configuration implementation
242      */
243     public static Configuration getConfiguration(final Properties props) {
244         WriteLock writeLock = lock.writeLock();
245         writeLock.lock();
246         try {
247             config = new DefaultConfiguration();
248             initialize(props);
249             return config;
250         } finally {
251             writeLock.unlock();
252         }
253     }
254
255     private static DefaultConfiguration getClonedDefaultConfiguration(Object owner, DefaultConfiguration local) {
256         Optional<DefaultConfiguration> global =
257                 Optional.ofNullable((DefaultConfiguration) getConfiguration());
258         try {
259             if (global.isPresent()) {
260                 local = (DefaultConfiguration) global.get().clone();
261             }
262         } catch (CloneNotSupportedException e) {
263             logger.error("getClonedDefaultConfiguration", e);
264         }
265         localConfigs.put(owner, local);
266         return local;
267     }
268
269     /**
270      * This method will clear the current configuration and then re-initialize it with the default
271      * values, application-specific configuration file, user-supplied properties (if any), and then
272      * command-line settings.
273      * <p>
274      * This method <strong><em>MUST</em></strong> be called holding the configuration lock!
275      * </p>
276      * <p>
277      * This method is a little special in that logging messages generated during the method must be
278      * cached and delayed until after the logging framework has been initialized. After that, the
279      * delayed logging buffer can be dumped to the log file and cleared.
280      * </p>
281      *
282      * @param props Application-supplied configuration values, if any
283      */
284     private static void initialize(final Properties props) {
285         DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
286         Date now = new Date();
287         logger.info(
288                 "------------------------------------------------------------------------------");
289
290         logger.info(Msg.CONFIGURATION_STARTED, format.format(now));
291
292         /*
293          * Clear any existing properties
294          */
295         config.clear();
296         logger.info(Msg.CONFIGURATION_CLEARED);
297
298         /*
299          * Load the defaults (if any are present)
300          */
301         InputStream in = Thread.currentThread().getContextClassLoader()
302                 .getResourceAsStream(DEFAULT_PROPERTIES);
303         if (in != null) {
304             logger.info(Msg.LOADING_DEFAULTS, DEFAULT_PROPERTIES);
305             try {
306                 config.setProperties(in);
307             } finally {
308                 try {
309                     in.close();
310                 } catch (IOException e) {
311                     logger.error("Cannot close inputStream", e);
312                 }
313             }
314             for (String key : config.getProperties().stringPropertyNames()) {
315                 logger.info(Msg.PROPERTY_VALUE, key, config.getProperty(key));
316             }
317         } else {
318             logger.info(Msg.NO_DEFAULTS_FOUND, DEFAULT_PROPERTIES);
319         }
320
321         /*
322          * Look for application configuration property file. By default, we will look for the file
323          * "cdp.properties" on the user home path, then on "./etc" (relative to current path), then
324          * on "../etc" (relative to current path). If we do not find any property file, then we
325          * continue. Otherwise, we load the first property file we find and then continue. In order
326          * to allow default values for the filename and paths to be searched, we first attempt to
327          * obtain these from our configuration object (which should be primed with default values
328          * and/or overridden with application-specified values). We then use the values obtained
329          * from that to get any user supplied values on the command line.
330          */
331         String filename = config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME,
332                 Configuration.DEFAULT_BOOTSTRAP_FILE_NAME);
333         filename = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME, filename);
334         String env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_NAME);
335         if (env != null && env.trim().length() > 0) {
336             filename = env;
337         }
338
339         String path = config.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH,
340                 Configuration.DEFAULT_BOOTSTRAP_FILE_PATH);
341         path = System.getProperty(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH, path);
342         env = System.getenv(Configuration.PROPERTY_BOOTSTRAP_FILE_PATH);
343         if (env != null && env.trim().length() > 0) {
344             path = env;
345         }
346
347         logger.info(Msg.SEARCHING_CONFIGURATION_OVERRIDES, path, filename);
348
349         String[] pathElements = path.split(COMMA);
350         boolean found = false;
351         for (String pathElement : pathElements) {
352             File file = new File(pathElement, filename);
353             if (file.exists() && file.canRead() && !file.isDirectory()) {
354
355                 logger.info(Msg.LOADING_CONFIGURATION_OVERRIDES, file.getAbsolutePath());
356                 Properties fileProperties = new Properties();
357                 BufferedInputStream stream = null;
358                 try {
359                     stream = new BufferedInputStream(new FileInputStream(file));
360                     fileProperties.load(stream);
361                     for (String key : fileProperties.stringPropertyNames()) {
362                         logger.debug(Msg.PROPERTY_VALUE, key, fileProperties.getProperty(key));
363                         config.setProperty(key, fileProperties.getProperty(key));
364                     }
365                     found = true;
366                     break;
367                 } catch (IOException e) {
368                     logger.error(EELFResourceManager.format(e));
369                 } finally {
370                     try {
371                         if (stream != null) {
372                             stream.close();
373                         }
374                     } catch (IOException e) {
375                         logger.error("Unable to close stream", e);
376                     }
377                 }
378             }
379         }
380
381         if (!found) {
382             logger.warn(Msg.NO_OVERRIDE_PROPERTY_FILE_LOADED, filename, path);
383         }
384
385         /*
386          * Apply any application-specified properties
387          */
388         if (props != null) {
389             logger.info(Msg.LOADING_APPLICATION_OVERRIDES);
390             for (String key : props.stringPropertyNames()) {
391                 logger.debug(Msg.PROPERTY_VALUE, key, props.getProperty(key));
392                 config.setProperty(key, props.getProperty(key));
393             }
394         } else {
395             logger.info(Msg.NO_APPLICATION_OVERRIDES);
396         }
397
398         /*
399          * Merge in the System.properties to pick-up any command line arguments (-Dkeyword=value)
400          */
401         logger.info(Msg.MERGING_SYSTEM_PROPERTIES);
402         config.setProperties(System.getProperties());
403
404         /*
405          * As a convenience, copy the "specialProperties" that are not defined in System.properties
406          * from the configuration back to the system properties object.
407          */
408         for (String key : config.getProperties().stringPropertyNames()) {
409             for (String specialProperty : specialProperties) {
410                 if (key.equals(specialProperty) && !System.getProperties().containsKey(key)) {
411                     System.setProperty(key, config.getProperty(key));
412                     logger.info(Msg.SETTING_SPECIAL_PROPERTY, key, config.getProperty(key));
413                 }
414             }
415         }
416
417         /*
418          * Initialize the resource manager by loading the requested bundles, if any are defined.
419          * Resource bundles may be specified as a comma-delimited list of names. These resource
420          * names are base names of resource bundles, do not include the language or country code, or
421          * the ".properties" extension. The actual loading of the resource bundles is done lazily
422          * when requested the first time. If the bundle does not exist, or cannot be loaded, it is
423          * ignored.
424          */
425         String resourcesList = config.getProperty(Configuration.PROPERTY_RESOURCE_BUNDLES,
426                 Configuration.DEFAULT_RESOURCE_BUNDLES);
427         String[] resources = resourcesList.split(",");
428         for (String resource : resources) {
429             logger.info(Msg.LOADING_RESOURCE_BUNDLE, resource.trim());
430             EELFResourceManager.loadMessageBundle(resource.trim());
431         }
432     }
433 }