aboutsummaryrefslogtreecommitdiffstats
path: root/policy-persistence/src/main/java/org/openecomp/policy/drools/core/DbAudit.java
blob: 51e92aa990d937fcbd6482cc325fc0844a8cb59d (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
/*-
 * ============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.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.UUID;

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.DroolsPersistenceProperties;

/**
 * This class audits the database
 */
public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase
{
	// get an instance of logger 
  private static Logger  logger = FlexLogger.getLogger(DbAudit.class);	
  // single global instance of this audit object
  static private DbAudit instance = new DbAudit();

  // This indicates if 'CREATE TABLE IF NOT EXISTS Audit ...' should be
  // invoked -- doing this avoids the need to create the table in advance.
  static private boolean createTableNeeded = true;

  /**
   * @return the single 'DbAudit' instance
   */
  static DroolsPDPIntegrityMonitor.AuditBase getInstance()
  {
	return(instance);
  }

  /**
   * Constructor - set the name to 'Database'
   */
  private DbAudit()
  {
	super("Database");
  }

  /**
   * Invoke the audit
   *
   * @param properties properties to be passed to the audit
   */
  @Override
	public void invoke(Properties droolsPersistenceProperties)
  {
	logger.info("Running 'DbAudit.invoke'");
	boolean isActive = true;
	String dbAuditIsActive = IntegrityMonitorProperties.getProperty("db.audit.is.active");
	logger.debug("DbAudit.invoke: dbAuditIsActive = " + dbAuditIsActive);
	
	if (dbAuditIsActive != null) {
		try {
			isActive = Boolean.parseBoolean(dbAuditIsActive.trim());
		} catch (NumberFormatException e) {
			logger.warn("DbAudit.invoke: Ignoring invalid property: db.audit.is.active = " + dbAuditIsActive);
		}
	}
	
	if(!isActive){
		logger.info("DbAudit.invoke: exiting because isActive = " + isActive);
		return;
	}
	
	// fetch DB properties from properties file -- they are already known
	// to exist, because they were verified by the 'IntegrityMonitor'
	// constructor
	String url = droolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_URL);
	String user = droolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_USER);
	String password =
			droolsPersistenceProperties.getProperty(DroolsPersistenceProperties.DB_PWD);

	// connection to DB
	Connection connection = null;

	// supports SQL operations
	PreparedStatement statement = null;
	ResultSet rs = null;

	// operation phase currently running -- used to construct an error
	// message, if needed
	String phase = null;

	try
	  {
		// create connection to DB
		phase = "creating connection";
		logger.info("DbAudit: Creating connection to " + url);

		connection = DriverManager.getConnection(url, user, password);

		// create audit table, if needed
		if (createTableNeeded)
		  {
			phase = "create table";
			logger.info("DbAudit: Creating 'Audit' table, if needed");
			statement = connection.prepareStatement
			  ("CREATE TABLE IF NOT EXISTS Audit (\n"
			   + " name varchar(64) DEFAULT NULL,\n"
			   + " UNIQUE KEY name (name)\n"
			   + ") DEFAULT CHARSET=latin1;");
			statement.execute();
			createTableNeeded = false;
		  }

		// insert an entry into the table
		phase = "insert entry";
		String key = UUID.randomUUID().toString();
		statement = connection.prepareStatement
		  ("INSERT INTO Audit (name) VALUES (?)");
		statement.setString(1, key);
		statement.executeUpdate();

		// fetch the entry from the table
		phase = "fetch entry";
		statement = connection.prepareStatement
		  ("SELECT name FROM Audit WHERE name = ?");
		statement.setString(1, key);
		rs = statement.executeQuery();
		if (rs.first())
		  {
			// found entry
			logger.info("DbAudit: Found key " + rs.getString(1));
		  }
		else
		  {
			logger.error
			  ("DbAudit: can't find newly-created entry with key " + key);
			setResponse("Can't find newly-created entry");
		  }

		// delete entries from table
		phase = "delete entry";
		statement = connection.prepareStatement
		  ("DELETE FROM Audit WHERE name = ?");
		statement.setString(1, key);
		statement.executeUpdate();
	  }
	catch (Exception e)
	  {
		String message = "DbAudit: Exception during audit, phase = " + phase;
		logger.error(MessageCodes.EXCEPTION_ERROR, e, message);
		setResponse(message);
	  }
	finally
	  {
		if (rs != null)
		  {
			try
			  {
				rs.close();
			  }
			catch (Exception e)
			  {
			  }
		  }
		if (statement != null)
		  {
			try
			  {
				statement.close();
			  }
			catch (Exception e)
			  {
			  }
		  }
		if (connection != null)
		  {
			try
			  {
				connection.close();
			  }
			catch (Exception e)
			  {
			  }
		  }
	  }
  }
}