2252a0f4c6a3b13cbcd13c7eda11c5419d941faa
[policy/drools-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * feature-state-management
4  * ================================================================================
5  * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.drools.statemanagement;
22
23 import java.io.IOException;
24 import java.util.List;
25 import java.util.Properties;
26 import org.onap.policy.common.capabilities.Startable;
27 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
28 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
29 import org.onap.policy.common.im.IntegrityMonitor;
30 import org.onap.policy.common.im.IntegrityMonitorException;
31 import org.onap.policy.drools.utils.PropertyUtil;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * This class extends 'IntegrityMonitor' for use in the 'Drools PDP' virtual machine. The included
37  * audits are 'Database' and 'Repository'.
38  */
39 public class DroolsPdpIntegrityMonitor extends IntegrityMonitor {
40
41     private static final String INVALID_PROPERTY_VALUE = "init: property {} does not have the expected value of {}";
42
43     // get an instance of logger
44     private static final Logger logger = LoggerFactory.getLogger(DroolsPdpIntegrityMonitor.class);
45
46     // static global instance
47     private static DroolsPdpIntegrityMonitor im = null;
48
49     // list of audits to run
50     private static AuditBase[] audits = new AuditBase[] {DbAudit.getInstance(), RepositoryAudit.getInstance()};
51
52     private static Properties subsystemTestProperties = null;
53
54     private static final String PROPERTIES_NAME = "feature-state-management.properties";
55
56     /**
57      * Constructor - pass arguments to superclass, but remember properties.
58      *
59      * @param resourceName unique name of this Integrity Monitor
60      * @param url the JMX URL of the MBean server
61      * @param properties properties used locally, as well as by 'IntegrityMonitor'
62      * @throws IntegrityMonitorException (passed from superclass)
63      */
64     private DroolsPdpIntegrityMonitor(String resourceName, Properties consolidatedProperties)
65             throws IntegrityMonitorException {
66         super(resourceName, consolidatedProperties);
67     }
68
69     private static void missingProperty(String prop) throws IntegrityMonitorException {
70         String msg = "init: missing IntegrityMonitor property: ".concat(prop);
71         logger.error(msg);
72         throw new IntegrityMonitorException(msg);
73     }
74
75     private static void logPropertyValue(String prop, String val) {
76         logger.info("\n\n    init: property: {} = {}\n", prop, val);
77     }
78
79     /**
80      * Static initialization -- create Drools Integrity Monitor, and an HTTP server to handle REST
81      * 'test' requests.
82      *
83      * @throws IntegrityMonitorException exception
84      */
85     public static DroolsPdpIntegrityMonitor init(String configDir) throws IntegrityMonitorException {
86
87         logger.info("init: Entering and invoking PropertyUtil.getProperties() on '{}'", configDir);
88
89         // read in properties
90         Properties stateManagementProperties = getProperties(configDir);
91
92         // fetch and verify definitions of some properties, adding defaults where
93         // appropriate
94         // (the 'IntegrityMonitor' constructor does some additional verification)
95
96         checkPropError(stateManagementProperties, StateManagementProperties.TEST_HOST);
97         checkPropError(stateManagementProperties, StateManagementProperties.TEST_PORT);
98
99         addDefaultPropError(stateManagementProperties, StateManagementProperties.TEST_SERVICES,
100                 StateManagementProperties.TEST_SERVICES_DEFAULT);
101
102         addDefaultPropError(stateManagementProperties, StateManagementProperties.TEST_REST_CLASSES,
103                 StateManagementProperties.TEST_REST_CLASSES_DEFAULT);
104
105         addDefaultPropWarn(stateManagementProperties, StateManagementProperties.TEST_MANAGED,
106                 StateManagementProperties.TEST_MANAGED_DEFAULT);
107
108         addDefaultPropWarn(stateManagementProperties, StateManagementProperties.TEST_SWAGGER,
109                 StateManagementProperties.TEST_SWAGGER_DEFAULT);
110
111         checkPropError(stateManagementProperties, StateManagementProperties.RESOURCE_NAME);
112         checkPropError(stateManagementProperties, StateManagementProperties.FP_MONITOR_INTERVAL);
113         checkPropError(stateManagementProperties, StateManagementProperties.FAILED_COUNTER_THRESHOLD);
114         checkPropError(stateManagementProperties, StateManagementProperties.TEST_TRANS_INTERVAL);
115         checkPropError(stateManagementProperties, StateManagementProperties.WRITE_FPC_INTERVAL);
116         checkPropError(stateManagementProperties, StateManagementProperties.SITE_NAME);
117         checkPropError(stateManagementProperties, StateManagementProperties.NODE_TYPE);
118         checkPropError(stateManagementProperties, StateManagementProperties.DEPENDENCY_GROUPS);
119         checkPropError(stateManagementProperties, StateManagementProperties.DB_DRIVER);
120         checkPropError(stateManagementProperties, StateManagementProperties.DB_URL);
121         checkPropError(stateManagementProperties, StateManagementProperties.DB_USER);
122         checkPropError(stateManagementProperties, StateManagementProperties.DB_PWD);
123
124         final String testHost = stateManagementProperties.getProperty(StateManagementProperties.TEST_HOST);
125         final String testPort = stateManagementProperties.getProperty(StateManagementProperties.TEST_PORT);
126         final String resourceName = stateManagementProperties.getProperty(StateManagementProperties.RESOURCE_NAME);
127
128         subsystemTestProperties = stateManagementProperties;
129
130         // Now that we've validated the properties, create Drools Integrity Monitor
131         // with these properties.
132         im = makeMonitor(resourceName, stateManagementProperties);
133         logger.info("init: New DroolsPDPIntegrityMonitor instantiated, resourceName = {}", resourceName);
134
135         // create http server
136         makeRestServer(testHost, testPort, stateManagementProperties);
137         logger.info("init: Exiting and returning DroolsPDPIntegrityMonitor");
138
139         return im;
140     }
141
142     /**
143      * Makes an Integrity Monitor.
144      *
145      * @param resourceName unique name of this Integrity Monitor
146      * @param properties properties used to configure the Integrity Monitor
147      * @return monitor object
148      * @throws IntegrityMonitorException exception
149      */
150     private static DroolsPdpIntegrityMonitor makeMonitor(String resourceName, Properties properties)
151             throws IntegrityMonitorException {
152
153         try {
154             return new DroolsPdpIntegrityMonitor(resourceName, properties);
155
156         } catch (Exception e) {
157             throw new IntegrityMonitorException(e);
158         }
159     }
160
161     /**
162      * Makes a rest server for the Integrity Monitor.
163      *
164      * @param testHost host name
165      * @param testPort port
166      * @param properties properties used to configure the rest server
167      * @throws IntegrityMonitorException exception
168      */
169     private static void makeRestServer(String testHost, String testPort, Properties properties)
170             throws IntegrityMonitorException {
171
172         try {
173             logger.info("init: Starting HTTP server, addr= {}:{}", testHost, testPort);
174
175             new IntegrityMonitorRestServer(properties);
176
177         } catch (Exception e) {
178             logger.error("init: Caught Exception attempting to start server on testPort={}", testPort);
179             throw new IntegrityMonitorException(e);
180         }
181     }
182
183     /**
184      * Gets the properties from the property file.
185      *
186      * @param configDir directory containing the property file
187      * @return the properties
188      * @throws IntegrityMonitorException exception
189      */
190     private static Properties getProperties(String configDir) throws IntegrityMonitorException {
191         try {
192             return PropertyUtil.getProperties(configDir + "/" + PROPERTIES_NAME);
193
194         } catch (IOException e) {
195             throw new IntegrityMonitorException(e);
196         }
197     }
198
199     /**
200      * Checks that a property is defined.
201      *
202      * @param props set of properties
203      * @param name name of the property to check
204      * @throws IntegrityMonitorException exception
205      */
206     private static void checkPropError(Properties props, String name) throws IntegrityMonitorException {
207         String val = props.getProperty(name);
208         if (val == null) {
209             missingProperty(name);
210         }
211
212         logPropertyValue(name, val);
213     }
214
215     /**
216      * Checks a property's value to verify that it matches the expected value. If the property is
217      * not defined, then it is added to the property set, with the expected value. Logs an error if
218      * the property is defined, but does not have the expected value.
219      *
220      * @param props set of properties
221      * @param name name of the property to check
222      * @param expected expected/default value
223      */
224     private static void addDefaultPropError(Properties props, String name, String expected) {
225         String val = props.getProperty(name);
226         if (val == null) {
227             props.setProperty(name, expected);
228
229         } else if (!val.equals(expected)) {
230             logger.error(INVALID_PROPERTY_VALUE, name, expected);
231         }
232
233         logPropertyValue(name, val);
234     }
235
236     /**
237      * Checks a property's value to verify that it matches the expected value. If the property is
238      * not defined, then it is added to the property set, with the expected value. Logs a warning if
239      * the property is defined, but does not have the expected value.
240      *
241      * @param props set of properties
242      * @param name name of the property to check
243      * @param expected expected/default value
244      */
245     private static void addDefaultPropWarn(Properties props, String name, String dflt) {
246         String val = props.getProperty(name);
247         if (val == null) {
248             props.setProperty(name, dflt);
249
250         } else if (!val.equals(dflt)) {
251             logger.warn(INVALID_PROPERTY_VALUE, name, dflt);
252         }
253
254         logPropertyValue(name, val);
255     }
256
257     /**
258      * Run tests (audits) unique to Drools PDP VM (Database + Repository).
259      */
260     @Override
261     public void subsystemTest() throws IntegrityMonitorException {
262         logger.info("DroolsPDPIntegrityMonitor.subsystemTest called");
263
264         // clear all responses (non-null values indicate an error)
265         for (AuditBase audit : audits) {
266             audit.setResponse(null);
267         }
268
269         // invoke all of the audits
270         for (AuditBase audit : audits) {
271             try {
272                 // invoke the audit (responses are stored within the audit object)
273                 audit.invoke(subsystemTestProperties);
274             } catch (Exception e) {
275                 logger.error("{} audit error", audit.getName(), e);
276                 if (audit.getResponse() == null) {
277                     // if there is no current response, use the exception message
278                     audit.setResponse(e.getMessage());
279                 }
280             }
281         }
282
283         // will contain list of subsystems where the audit failed
284         String responseMsg = "";
285
286         // Loop through all of the audits, and see which ones have failed.
287         // NOTE: response information is stored within the audit objects
288         // themselves -- only one can run at a time.
289         for (AuditBase audit : audits) {
290             String response = audit.getResponse();
291             if (response != null) {
292                 // the audit has failed -- add subsystem and
293                 // and 'responseValue' with the new information
294                 responseMsg = responseMsg.concat("\n" + audit.getName() + ": " + response);
295             }
296         }
297
298         if (!responseMsg.isEmpty()) {
299             throw new IntegrityMonitorException(responseMsg);
300         }
301     }
302
303     /* ============================================================ */
304
305     /**
306      * This is the base class for audits invoked in 'subsystemTest'.
307      */
308     public abstract static class AuditBase {
309         // name of the audit
310         protected String name;
311
312         // non-null indicates the error response
313         protected String response;
314
315         /**
316          * Constructor - initialize the name, and clear the initial response.
317          *
318          * @param name name of the audit
319          */
320         public AuditBase(String name) {
321             this.name = name;
322             this.response = null;
323         }
324
325         /**
326          * Get the name.
327          *
328          * @return the name of this audit
329          */
330         public String getName() {
331             return name;
332         }
333
334         /**
335          * Get the response.
336          *
337          * @return the response String (non-null indicates the error message)
338          */
339         public String getResponse() {
340             return response;
341         }
342
343         /**
344          * Set the response string to the specified value.
345          *
346          * @param value the new value of the response string (null = no errors)
347          */
348         public void setResponse(String value) {
349             response = value;
350         }
351
352         /**
353          * Abstract method to invoke the audit.
354          *
355          * @param persistenceProperties Used for DB access
356          * @throws Exception passed in by the audit
357          */
358         abstract void invoke(Properties persistenceProperties) throws Exception;
359     }
360
361     public static class IntegrityMonitorRestServer implements Startable {
362         protected HttpServletServer server = null;
363         protected final Properties integrityMonitorRestServerProperties;
364
365         public IntegrityMonitorRestServer(Properties props) {
366             this.integrityMonitorRestServerProperties = props;
367             this.start();
368         }
369
370         @Override
371         public boolean start() {
372             try {
373                 List<HttpServletServer> servers = HttpServletServerFactoryInstance.getServerFactory()
374                                 .build(integrityMonitorRestServerProperties);
375
376                 if (!servers.isEmpty()) {
377                     server = servers.get(0);
378
379                     waitServerStart();
380                 }
381             } catch (Exception e) {
382                 logger.error("Exception building servers", e);
383                 return false;
384             }
385
386             return true;
387         }
388
389         private void waitServerStart() {
390             try {
391                 server.waitedStart(5);
392             } catch (Exception e) {
393                 logger.error("Exception waiting for servers to start: ", e);
394             }
395         }
396
397         @Override
398         public boolean stop() {
399             try {
400                 server.stop();
401             } catch (Exception e) {
402                 logger.error("Exception during stop", e);
403             }
404
405             return true;
406         }
407
408         @Override
409         public void shutdown() {
410             this.stop();
411         }
412
413         @Override
414         public synchronized boolean isAlive() {
415             return this.integrityMonitorRestServerProperties != null;
416         }
417     }
418
419     /**
420      * Returns the instance.
421      *
422      * @return DroolsPDPIntegrityMonitor object
423      * @throws IntegrityMonitorException exception
424      */
425     public static DroolsPdpIntegrityMonitor getInstance() throws IntegrityMonitorException {
426         logger.debug("getInstance() called");
427         if (im == null) {
428             String msg = "No DroolsPDPIntegrityMonitor instance exists."
429                     + " Please use the method DroolsPDPIntegrityMonitor init(String configDir)";
430             throw new IntegrityMonitorException(msg);
431         } else {
432             return im;
433         }
434     }
435 }