aboutsummaryrefslogtreecommitdiffstats
path: root/integrity-audit/src/main/java/org/onap/policy/common/ia/IntegrityAudit.java
blob: d50c705915a86c6b5a8698456b21b49cdb5e1388 (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
/*-
 * ============LICENSE_START=======================================================
 * Integrity Audit
 * ================================================================================
 * Copyright (C) 2017-2018 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.onap.policy.common.ia;

import java.util.Properties;
import org.onap.policy.common.ia.IntegrityAuditProperties.NodeTypeEnum;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;

/**
 * class IntegrityAudit Audits all persisted entities for all resource clusters for all sites and
 * logs any anomalies.
 */
public class IntegrityAudit {

    private static final Logger logger = FlexLogger.getLogger(IntegrityAudit.class);

    private static boolean isUnitTesting;
    private boolean isThreadInitialized = false;

    AuditThread auditThread = null;

    private String persistenceUnit;
    private Properties properties;
    private String resourceName;


    /*
     * This is the audit period in milliseconds. For example, if it had a value of 3600000, the
     * audit can only run once per hour. If it has a value of 6000, it can run once per minute.
     * 
     * Values: integrityAuditPeriodSeconds < 0 (negative number) indicates the audit is off
     * integrityAuditPeriodSeconds == 0 indicates the audit is to run continuously
     * integrityAuditPeriodSeconds > 0 indicates the audit is to run at most once during the
     * indicated period
     * 
     */
    private int integrityAuditPeriodSeconds;

    /**
     * IntegrityAudit constructor.
     * 
     * @param resourceName the resource name
     * @param persistenceUnit the persistence unit
     * @param properties the properties
     * @throws IntegrityAuditException if an error occurs
     */
    public IntegrityAudit(String resourceName, String persistenceUnit, Properties properties)
            throws IntegrityAuditException {

        logger.info("Constructor: Entering and checking for nulls");
        StringBuilder parmList = new StringBuilder();
        if (parmsAreBad(resourceName, persistenceUnit, properties, parmList)) {
            logger.error("Constructor: Parms contain nulls; cannot run audit for resourceName=" + resourceName
                    + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList);
            throw new IntegrityAuditException("Constructor: Parms contain nulls; cannot run audit for resourceName="
                    + resourceName + ", persistenceUnit=" + persistenceUnit + ", bad parameters: " + parmList);
        }

        this.persistenceUnit = persistenceUnit;
        this.properties = properties;
        this.resourceName = resourceName;

        // IntegrityAuditProperties.AUDIT_PERIOD_SECONDS and
        // IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS are allowed to be null
        if (properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null) {
            this.integrityAuditPeriodSeconds =
                    Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim());
        } else {
            // If it is null, set it to the default value
            this.integrityAuditPeriodSeconds = IntegrityAuditProperties.DEFAULT_AUDIT_PERIOD_SECONDS;
        }
        logger.info("Constructor: Exiting");

    }

    /**
     * Used during JUnit testing by AuditPeriodTest.java
     */
    public int getIntegrityAuditPeriodSeconds() {
        return integrityAuditPeriodSeconds;
    }

    /**
     * Determine if the nodeType conforms to the required node types.
     */
    public static boolean isNodeTypeEnum(String nt) {
        for (NodeTypeEnum n : NodeTypeEnum.values()) {
            if (n.toString().equals(nt)) {
                return true;
            }
        }
        return false;
    }


    /**
     * Makes sure we don't try to run the audit with bad parameters.
     */
    public static boolean parmsAreBad(String resourceName, String persistenceUnit, Properties properties,
            StringBuilder badparams) {

        boolean parmsAreBad = false;

        if (resourceName == null || resourceName.isEmpty()) {
            badparams.append("resourceName ");
            parmsAreBad = true;
        }

        if (persistenceUnit == null || persistenceUnit.isEmpty()) {
            badparams.append("persistenceUnit ");
            parmsAreBad = true;
        }

        if (properties == null || properties.isEmpty()) {
            badparams.append("properties ");
            parmsAreBad = true;
        } else {
            String dbDriver = properties.getProperty(IntegrityAuditProperties.DB_DRIVER);
            if (dbDriver == null || dbDriver.isEmpty()) {
                badparams.append("dbDriver ");
                parmsAreBad = true;
            }

            String dbUrl = properties.getProperty(IntegrityAuditProperties.DB_URL);
            if (dbUrl == null || dbUrl.isEmpty()) {
                badparams.append("dbUrl ");
                parmsAreBad = true;
            }

            String dbUser = properties.getProperty(IntegrityAuditProperties.DB_USER);
            if (dbUser == null || dbUser.isEmpty()) {
                badparams.append("dbUser ");
                parmsAreBad = true;
            }

            String dbPwd = properties.getProperty(IntegrityAuditProperties.DB_PWD);
            if (dbPwd == null) { // may be empty
                badparams.append("dbPwd ");
                parmsAreBad = true;
            }

            String siteName = properties.getProperty(IntegrityAuditProperties.SITE_NAME);
            if (siteName == null || siteName.isEmpty()) {
                badparams.append("siteName ");
                parmsAreBad = true;
            }

            String nodeType = properties.getProperty(IntegrityAuditProperties.NODE_TYPE);
            if (nodeType == null || nodeType.isEmpty()) {
                badparams.append("nodeType ");
                parmsAreBad = true;
            } else {
                nodeType = nodeType.trim();
                if (!isNodeTypeEnum(nodeType)) {
                    String nodetypes = "nodeType must be one of[";
                    for (NodeTypeEnum n : NodeTypeEnum.values()) {
                        nodetypes = nodetypes.concat(n.toString() + " ");
                    }
                    badparams.append(nodetypes + "] ");
                    parmsAreBad = true;
                }
            }
            // IntegrityAuditProperties.AUDIT_PERIOD_SECONDS and
            // IntegrityAuditProperties.AUDIT_PERIOD_MILLISECONDS are allowed to be null
            if (properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS) != null) {
                try {
                    Integer.parseInt(properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim());
                } catch (NumberFormatException nfe) {
                    badparams.append(", auditPeriodSeconds="
                            + properties.getProperty(IntegrityAuditProperties.AUDIT_PERIOD_SECONDS).trim());
                    parmsAreBad = true;
                }
            }
        } // End else
        logger.debug("parmsAreBad: exit:" + "\nresourceName: " + resourceName + "\npersistenceUnit: " + persistenceUnit
                + "\nproperties: " + properties);

        return parmsAreBad;
    }

    /**
     * Starts the audit thread.
     * 
     * @throws IntegrityAuditException if an error occurs
     */
    public void startAuditThread() throws IntegrityAuditException {
        logger.info("startAuditThread: Entering");

        if (integrityAuditPeriodSeconds >= 0) {
            this.auditThread = makeAuditThread(this.resourceName, this.persistenceUnit, 
                            this.properties, integrityAuditPeriodSeconds);
            logger.info("startAuditThread: Audit started and will run every " + integrityAuditPeriodSeconds 
                            + " seconds");
            this.auditThread.start();
            
        } else {
            logger.info("startAuditThread: Suppressing integrity audit, integrityAuditPeriodSeconds="
                    + integrityAuditPeriodSeconds);
        }

        logger.info("startAuditThread: Exiting");
    }

    /**
     * Stops the audit thread.
     */
    public void stopAuditThread() {

        logger.info("stopAuditThread: Entering");

        if (this.auditThread != null) {
            this.auditThread.interrupt();
        } else {
            logger.info("stopAuditThread: auditThread never instantiated; no need to interrupt");
        }

        logger.info("stopAuditThread: Exiting");
    }

    public boolean isThreadInitialized() {
        return isThreadInitialized;
    }

    public void setThreadInitialized(boolean isThreadInitialized) {
        logger.info("setThreadInitialized: Setting isThreadInitialized=" + isThreadInitialized);
        this.isThreadInitialized = isThreadInitialized;
    }

    public static boolean isUnitTesting() {
        return isUnitTesting;
    }

    public static void setUnitTesting(boolean isUnitTesting) {
        IntegrityAudit.isUnitTesting = isUnitTesting;
    }

    /**
     * Waits a bit for the AuditThread to complete. Used by JUnit tests.
     * 
     * @param twaitms wait time, in milliseconds
     * @return {@code true} if the thread stopped within the given time, {@code false} otherwise
     * @throws InterruptedException if the thread is interrupted
     */
    protected boolean joinAuditThread(long twaitms) throws InterruptedException {
        if (this.auditThread == null) {
            return true;

        } else {
            this.auditThread.join(twaitms);
            return !this.auditThread.isAlive();
        }
    }

    /**
     * Return if audit thread.
     * 
     * @return {@code true} if an audit thread exists, {@code false} otherwise
     */
    protected boolean haveAuditThread() {
        return (this.auditThread != null);
    }

    /**
     * Creates an audit thread. May be overridden by junit tests.
     * 
     * @param resourceName2 the resource name
     * @param persistenceUnit2 the persistence unit
     * @param properties2 properties
     * @param integrityAuditPeriodSeconds2
     * 
     * @return a new audit thread
     * @throws IntegrityAuditException audit exception
     */
    protected AuditThread makeAuditThread(String resourceName2, String persistenceUnit2, Properties properties2,
                    int integrityAuditPeriodSeconds2) throws IntegrityAuditException {

        return new AuditThread(resourceName2, persistenceUnit2, properties2, integrityAuditPeriodSeconds2, this);
    }
}