aboutsummaryrefslogtreecommitdiffstats
path: root/policy-persistence/src/main/java/org/openecomp/policy/drools/core/DroolsPDPIntegrityMonitor.java
blob: 2b6058fdf4b2bac67951a246614c3615316d60cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*-
 * ============LICENSE_START=======================================================
 * policy-persistence
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.policy.drools.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.LinkedList;
import java.util.Properties;
import java.util.concurrent.Callable;

import org.openecomp.policy.common.im.IntegrityMonitor;
import org.openecomp.policy.common.logging.flexlogger.PropertyUtil;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
import org.openecomp.policy.common.logging.flexlogger.Logger;
import org.openecomp.policy.common.logging.eelf.MessageCodes;
import org.openecomp.policy.drools.persistence.DroolsPdpsElectionHandler;
import org.openecomp.policy.drools.persistence.XacmlPersistenceProperties;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/**
 * This class extends 'IntegrityMonitor' for use in the 'Drools PDP'
 * virtual machine. The included audits are 'Database' and 'Repository'.
 */
public class DroolsPDPIntegrityMonitor extends IntegrityMonitor
{
	
	// get an instance of logger 
  private static Logger  logger = FlexLogger.getLogger(DroolsPDPIntegrityMonitor.class);	

  // static global instance
  static private DroolsPDPIntegrityMonitor im = null;

  // list of audits to run
  static private AuditBase[] audits =
	new AuditBase[]{DbAudit.getInstance(), RepositoryAudit.getInstance()};

  // save initialization properties
  private Properties droolsPersistenceProperties = null;
  
  /**
   * Static initialization -- create Drools Integrity Monitor, and
   * an HTTP server to handle REST 'test' requests
   */
  static public DroolsPDPIntegrityMonitor init(String configDir) throws Exception
  {
	  	  
	logger.info("init: Entering and invoking PropertyUtil.getProperties() on '"
				+ configDir + "'");
		
	// read in properties
	Properties integrityMonitorProperties =
	  PropertyUtil.getProperties(configDir + "/IntegrityMonitor.properties");
	Properties droolsPersistenceProperties =
	  PropertyUtil.getProperties(configDir + "/droolsPersistence.properties");
	Properties xacmlPersistenceProperties =
	  PropertyUtil.getProperties(configDir + "/xacmlPersistence.properties");

	// fetch and verify definitions of some properties
	// (the 'IntegrityMonitor' constructor does some additional verification)
	String resourceName = integrityMonitorProperties.getProperty("resource.name");
	String hostPort = integrityMonitorProperties.getProperty("hostPort");
	String fpMonitorInterval = integrityMonitorProperties.getProperty("fp_monitor_interval");
	String failedCounterThreshold = integrityMonitorProperties.getProperty("failed_counter_threshold");
	String testTransInterval = integrityMonitorProperties.getProperty("test_trans_interval");
	String writeFpcInterval = integrityMonitorProperties.getProperty("write_fpc_interval");
	String siteName = integrityMonitorProperties.getProperty("site_name");
	String nodeType = integrityMonitorProperties.getProperty("node_type");
	String dependencyGroups = integrityMonitorProperties.getProperty("dependency_groups");
	String droolsJavaxPersistenceJdbcDriver = droolsPersistenceProperties.getProperty("javax.persistence.jdbc.driver");
	String droolsJavaxPersistenceJdbcUrl = droolsPersistenceProperties.getProperty("javax.persistence.jdbc.url");
	String droolsJavaxPersistenceJdbcUser = droolsPersistenceProperties.getProperty("javax.persistence.jdbc.user");
	String droolsJavaxPersistenceJdbcPassword = droolsPersistenceProperties.getProperty("javax.persistence.jdbc.password");	
	String xacmlJavaxPersistenceJdbcDriver = xacmlPersistenceProperties.getProperty("javax.persistence.jdbc.driver");
	String xacmlJavaxPersistenceJdbcUrl = xacmlPersistenceProperties.getProperty("javax.persistence.jdbc.url");
	String xacmlJavaxPersistenceJdbcUser = xacmlPersistenceProperties.getProperty("javax.persistence.jdbc.user");
	String xacmlJavaxPersistenceJdbcPassword = xacmlPersistenceProperties.getProperty("javax.persistence.jdbc.password");
	
	if (resourceName == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'resource.name'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'resource.name'"));
	  }
	if (hostPort == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'hostPort'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'hostPort'"));
	  }
	if (fpMonitorInterval == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'fp_monitor_interval'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'fp_monitor_interval'"));
	  }	
	if (failedCounterThreshold == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'failed_counter_threshold'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'failed_counter_threshold'"));
	  }	
	if (testTransInterval == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'test_trans_interval'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'test_trans_interval'"));
	  }	
	if (writeFpcInterval == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'write_fpc_interval'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'write_fpc_interval'"));
	  }	
	if (siteName == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'site_name'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'site_name'"));
	  }	
	if (nodeType == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'node_type'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'node_type'"));
	  }	
	if (dependencyGroups == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'dependency_groups'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'dependency_groups'"));
	  }	
	if (droolsJavaxPersistenceJdbcDriver == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for drools DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for drools DB'"));
	  }		
	if (droolsJavaxPersistenceJdbcUrl == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.url  for drools DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.url for drools DB'"));
	  }			
	if (droolsJavaxPersistenceJdbcUser == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for drools DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for drools DB'"));
	  }			
	if (droolsJavaxPersistenceJdbcPassword == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.password for drools DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.password for drools DB'"));
	  }	
	if (xacmlJavaxPersistenceJdbcDriver == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for xacml DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for xacml DB'"));
	  }		
	if (xacmlJavaxPersistenceJdbcUrl == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.url  for xacml DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.url  for xacml DB'"));
	  }			
	if (xacmlJavaxPersistenceJdbcUser == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for xacml DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for xacml DB'"));
	  }			
	if (xacmlJavaxPersistenceJdbcPassword == null)
	  {
		logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.password for xacml DB'");
		throw(new Exception
			  ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.password'  for xacml DB'"));
	  }		

	logger.info("init: loading consolidatedProperties");
	Properties consolidatedProperties = new Properties();
	consolidatedProperties.load(new FileInputStream(new File(configDir + "/IntegrityMonitor.properties")));
	consolidatedProperties.load(new FileInputStream(new File(configDir + "/xacmlPersistence.properties")));
	// verify that consolidatedProperties has properties from both properties files.
	logger.info("init: PDP_INSTANCE_ID=" + consolidatedProperties.getProperty(IntegrityMonitorProperties.PDP_INSTANCE_ID));
	logger.info("init: DB_URL=" + consolidatedProperties.getProperty(XacmlPersistenceProperties.DB_URL));

	// Now that we've validated the properties, create Drools Integrity Monitor
	// with these properties.
	im = new DroolsPDPIntegrityMonitor(resourceName,
				consolidatedProperties, droolsPersistenceProperties);
	logger.info("init: New DroolsPDPIntegrityMonitor instantiated, hostPort=" + hostPort);

	// determine host and port for HTTP server
	int index = hostPort.lastIndexOf(':');
	InetSocketAddress addr;

	if (index < 0)
	  {
		addr = new InetSocketAddress(Integer.valueOf(hostPort));
	  }
	else
	  {
		addr = new InetSocketAddress
		  (hostPort.substring(0, index),
		   Integer.valueOf(hostPort.substring(index + 1)));
	  }

	// create http server
	try {
		logger.info("init: Starting HTTP server, addr=" + addr);
		HttpServer server = HttpServer.create(addr, 0);
		server.createContext("/test", new TestHandler());
		server.setExecutor(null);
		server.start();
			System.out.println("init: Started server on hostPort=" + hostPort);
	} catch (Exception e) {
			if (PolicyContainer.isUnitTesting) {
				System.out
						.println("init: Caught Exception attempting to start server on hostPort="
								+ hostPort + ", message=" + e.getMessage());
		} else {
			throw e;
		}
	}
	
	logger.info("init: Exiting and returning DroolsPDPIntegrityMonitor");
	return im;
  }

  /**
   * Constructor - pass arguments to superclass, but remember properties
   * @param resourceName unique name of this Integrity Monitor
   * @param url the JMX URL of the MBean server
   * @param properties properties used locally, as well as by
   *	'IntegrityMonitor'
   * @throws Exception (passed from superclass)
   */
	private DroolsPDPIntegrityMonitor(String resourceName,
			Properties consolidatedProperties,
			Properties droolsPersistenceProperties) throws Exception {
	super(resourceName, consolidatedProperties);
	this.droolsPersistenceProperties = droolsPersistenceProperties;
  }

  /**
   * Run tests (audits) unique to Drools PDP VM (Database + Repository)
   */
  @Override
	public void subsystemTest() throws Exception
  {
	logger.info("DroolsPDPIntegrityMonitor.subsystemTest called");

	// clear all responses (non-null values indicate an error)
	for (AuditBase audit : audits)
	  {
		audit.setResponse(null);
	  }

	// invoke all of the audits
	for (AuditBase audit : audits)
	  {
		try
		  {
			// invoke the audit (responses are stored within the audit object)
			audit.invoke(droolsPersistenceProperties);
		  }
		catch (Exception e)
		  {
			logger.error(MessageCodes.EXCEPTION_ERROR, e,
							   audit.getName() + " audit error");
			if (audit.getResponse() == null)
			  {
				// if there is no current response, use the exception message
				audit.setResponse(e.getMessage());
			  }
		  }
	  }
	
	  // will contain list of subsystems where the audit failed
	  String responseMsg = "";

	  // Loop through all of the audits, and see which ones have failed.
	  // NOTE: response information is stored within the audit objects
	  // themselves -- only one can run at a time.
	  for (AuditBase audit : audits)
		{
		  String response = audit.getResponse();
		  if (response != null)
			{
			  // the audit has failed -- add subsystem and 
			  // and 'responseValue' with the new information
			  responseMsg = responseMsg.concat("\n" + audit.getName() + ": " + response);
			}
		}
	  
	  if(!responseMsg.isEmpty()){
		  throw new Exception(responseMsg);
	  }
  }

  /* ============================================================ */

  /**
   * This is the base class for audits invoked in 'subsystemTest'
   */
  static public abstract class AuditBase
  {
	// name of the audit
	protected String name;

	// non-null indicates the error response
	protected String response;

	/**
	 * Constructor - initialize the name, and clear the initial response
	 * @param name name of the audit
	 */
	public AuditBase(String name)
	{
	  this.name = name;
	  this.response = null;
	}

	/**
	 * @return the name of this audit
	 */
	public String getName()
	{
	  return(name);
	}

	/**
	 * @return the response String (non-null indicates the error message)
	 */
	public String getResponse()
	{
	  return(response);
	}

	/**
	 * Set the response string to the specified value
	 * @param value the new value of the response string (null = no errors)
	 */
	public void setResponse(String value)
	{
	  response = value;
	}

	/**
	 * Abstract method to invoke the audit
	 * @param droolsPersistenceProperties Used for DB access
	 * @throws Exception passed in by the audit
	 */
	abstract void invoke(Properties droolsPersistenceProperties) throws Exception;
  }

  /* ============================================================ */

  /**
   * This class is the HTTP handler for the REST 'test' invocation
   */
  static class TestHandler implements HttpHandler
  {
	/**
	 * Handle an incoming REST 'test' invocation
	 * @param ex used to pass incoming and outgoing HTTP information
	 */
	@Override
	  public void handle(HttpExchange ex) throws IOException
	{
		
		  System.out.println("TestHandler.handle: Entering");

	  // The responses are stored within the audit objects, so we need to
	  // invoke the audits and get responses before we handle another
	  // request.
	  synchronized(TestHandler.class)
		{
		  // will include messages associated with subsystem failures
		  StringBuilder body = new StringBuilder();

		  // 200=SUCCESS, 500=failure
		  int responseValue = 200;

		  if (im != null)
			{
			  try
				{
				  // call 'IntegrityMonitor.evaluateSanity()'
				  im.evaluateSanity();
				}
			  catch (Exception e)
				{
				  // this exception isn't coming from one of the audits,
				  // because those are caught in 'subsystemTest()'
				  logger.error
					(MessageCodes.EXCEPTION_ERROR, e,
					 "DroolsPDPIntegrityMonitor.evaluateSanity()");

				  // include exception in HTTP response
				  body.append("\nException: " + e + "\n");
				  responseValue = 500;
				}
			}
/*
 * Audit failures are being logged. A string will be generated which captures the 
 * the audit failures. This string will be included in an exception coming from im.evaluateSanity().
 * 
		  // will contain list of subsystems where the audit failed
		  LinkedList<String> subsystems = new LinkedList<String>();

		  // Loop through all of the audits, and see which ones have failed.
		  // NOTE: response information is stored within the audit objects
		  // themselves -- only one can run at a time.
		  for (AuditBase audit : audits)
			{
			  String response = audit.getResponse();
			  if (response != null)
				{
				  // the audit has failed -- update 'subsystems', 'body',
				  // and 'responseValue' with the new information
				  subsystems.add(audit.getName());
				  body
					.append('\n')
					.append(audit.getName())
					.append(":\n")
					.append(response)
					.append('\n');
				  responseValue = 500;
				}
			}

		  if (subsystems.size() != 0)
			{
			  // there is at least one failure -- add HTTP headers
			  ex.getResponseHeaders().put("X-ECOMP-SubsystemFailure",
										  subsystems);
			}
*/
		  // send response, including the contents of 'body'
		  // (which is empty if everything is successful)
		  ex.sendResponseHeaders(responseValue, body.length());
		  OutputStream os = ex.getResponseBody();
		  os.write(body.toString().getBytes());
		  os.close();
		  System.out.println("TestHandler.handle: Exiting");
		}
	}
  }
	public static DroolsPDPIntegrityMonitor getInstance() throws Exception{
		logger.info("getInstance() called");
		if (im == null) {
			String msg = "No DroolsPDPIntegrityMonitor instance exists."
					+ " Please use the method DroolsPDPIntegrityMonitor init(String configDir)";
			throw new Exception(msg);
		}else{
			return im;
		}
	}
}