aboutsummaryrefslogtreecommitdiffstats
path: root/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
diff options
context:
space:
mode:
Diffstat (limited to 'integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java')
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java634
1 files changed, 312 insertions, 322 deletions
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
index 717ae7a3..7031c50a 100644
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
+++ b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* Integrity Monitor
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +21,14 @@
package org.onap.policy.common.im;
+import com.google.re2j.Pattern;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.EntityTransaction;
+import jakarta.persistence.FlushModeType;
+import jakarta.persistence.LockModeType;
+import jakarta.persistence.Persistence;
+import jakarta.persistence.TypedQuery;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
@@ -31,16 +40,13 @@ import java.util.Map.Entry;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
+import java.util.function.IntConsumer;
+import java.util.function.LongConsumer;
import java.util.function.Supplier;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityTransaction;
-import javax.persistence.FlushModeType;
-import javax.persistence.LockModeType;
-import javax.persistence.Persistence;
-import javax.persistence.Query;
+import lombok.Getter;
+import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.common.im.jmx.ComponentAdmin;
import org.onap.policy.common.im.jmx.ComponentAdminMBean;
@@ -59,6 +65,9 @@ public class IntegrityMonitor {
private static final Logger logger = LoggerFactory.getLogger(IntegrityMonitor.class.getName());
+ private static final Pattern COMMA_PAT = Pattern.compile(",");
+ private static final Pattern SEMICOLON_PAT = Pattern.compile(";");
+
// only allow one instance of IntegrityMonitor
private static IntegrityMonitor instance = null;
@@ -69,8 +78,8 @@ public class IntegrityMonitor {
private static final String IGNORE_INVALID_PROPERTY_STRING = "Ignored invalid property: {}";
private static final String PROPERTY_EXCEPTION_STRING = "IntegrityMonitor Property Exception: ";
private static final String EXCEPTION_STRING = "IntegrityMonitor threw exception.";
- private static final String STATE_CHECK_STRING = "IntegrityMonitor.stateCheck(): "
- + "Failed to disableFail dependent resource = ";
+ private static final String STATE_CHECK_STRING =
+ "IntegrityMonitor.stateCheck(): " + "Failed to disableFail dependent resource = ";
private static final String RESOURCE_STRING = "Resource ";
private static final String LC_RESOURCE_STRING = "resource";
@@ -83,26 +92,27 @@ public class IntegrityMonitor {
boolean alarmExists = false;
/*
- * Error message that is written by the dependencyCheck() method. It is made available
- * externally through the evaluateSanity() method.
+ * Error message that is written by the dependencyCheck() method. It is made available externally through the
+ * evaluateSanity() method.
*/
private String dependencyCheckErrorMsg = "";
// The entity manager factory for JPA access
- private EntityManagerFactory emf;
- private EntityManager em;
+ private final EntityManagerFactory emf;
+ private final EntityManager em;
// Persistence Unit for JPA
public static final String PERSISTENCE_UNIT = "operationalPU";
public static final long CYCLE_INTERVAL_MILLIS = 1000L;
+ @Getter
private StateManagement stateManager = null;
/**
* Set to {@code null} if to stop running.
*/
- private volatile Thread fpManager = null;
+ private AtomicReference<Thread> fpManager = new AtomicReference<>();
// The forward progress counter is incremented as the
// process being monitored makes forward progress
@@ -148,14 +158,16 @@ public class IntegrityMonitor {
private static long writeFpcIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_WRITE_FPC_INTERVAL);
// check the health of dependencies
private static long checkDependencyIntervalMs =
- toMillis(IntegrityMonitorProperties.DEFAULT_CHECK_DEPENDENCY_INTERVAL);
+ toMillis(IntegrityMonitorProperties.DEFAULT_CHECK_DEPENDENCY_INTERVAL);
// A lead subsystem will have dependency groups with resource names in the
// properties file.
// For non-lead subsystems, the dependency_group property will be absent.
private static String[] depGroups = null;
- private static boolean isUnitTesting = false;
+ @Getter
+ @Setter
+ private static boolean unitTesting = false;
// can turn on health checking of dependents via jmx test() call by setting
// this property to true
@@ -191,30 +203,31 @@ public class IntegrityMonitor {
private final Object refreshStateAuditLock = new Object();
private final Object imFlushLock = new Object();
+ @Getter
private Map<String, String> allSeemsWellMap;
+ @Getter
private Map<String, String> allNotWellMap;
/**
* IntegrityMonitor constructor. It is invoked from the getInstance() method in this class or from the constructor
- * of a child or sub-class. A class can extend the IntegrityMonitor class if there is a need to override any of the
+ * of a child or subclass. A class can extend the IntegrityMonitor class if there is a need to override any of the
* base methods (ex. subsystemTest()). Only one instance is allowed to be created per resource name.
*
* @param resourceName The resource name of the resource
- * @param properties a set of properties passed in from the resource
+ * @param properties a set of properties passed in from the resource
* @throws IntegrityMonitorException if any errors are encountered in the constructor
*/
protected IntegrityMonitor(String resourceName, Properties properties) throws IntegrityMonitorException {
// singleton check since this constructor can be called from a child or
- // sub-class
+ // subclass
if (instance != null) {
- String msg = "IM object exists and only one instance allowed";
+ var msg = "IM object exists and only one instance allowed";
logger.error("{}", msg);
throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg);
}
- instance = this;
- IntegrityMonitor.resourceName = resourceName;
+ setInstance(this, resourceName);
/*
* Validate that the properties file contains all the needed properties. Throws an
@@ -229,14 +242,6 @@ public class IntegrityMonitor {
// Create the entity manager factory
//
emf = Persistence.createEntityManagerFactory(getPersistenceUnit(), properties);
- //
- // Did it get created?
- //
- if (emf == null) {
- logger.error("Error creating IM entity manager factory with persistence unit: {}",
- getPersistenceUnit());
- throw new IntegrityMonitorException("Unable to create IM Entity Manager Factory");
- }
// add entry to forward progress and resource registration tables in DB
@@ -249,71 +254,14 @@ public class IntegrityMonitor {
try {
// if ForwardProgress entry exists for resourceName, update it. If
// not found, create a new entry
- Query fquery = em.createQuery(QUERY_STRING);
- fquery.setParameter("rn", resourceName);
-
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ForwardProgressEntity fpx = null;
- if (!fpList.isEmpty()) {
- // ignores multiple results
- fpx = (ForwardProgressEntity) fpList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(fpx);
- if (logger.isDebugEnabled()) {
- logger.debug("Resource {} exists and will be updated - old fpc= {}, lastUpdated= {}", resourceName,
- fpx.getFpcCount(), fpx.getLastUpdated());
- }
- fpx.setFpcCount(fpCounter);
- } else {
- // Create a forward progress object
- logger.debug("Adding resource {} to ForwardProgress table", resourceName);
- fpx = new ForwardProgressEntity();
- }
- // update/set columns in entry
- fpx.setResourceName(resourceName);
- em.persist(fpx);
- // flush to the DB
- synchronized (imFlushLock) {
- em.flush();
- }
+ createOrUpdateForwardProgress(resourceName);
// if ResourceRegistration entry exists for resourceName, update it.
// If not found, create a new entry
- Query rquery = em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn");
- rquery.setParameter("rn", resourceName);
-
- @SuppressWarnings("rawtypes")
- List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- ResourceRegistrationEntity rrx = null;
- if (!rrList.isEmpty()) {
- // ignores multiple results
- rrx = (ResourceRegistrationEntity) rrList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(rrx);
- if (logger.isDebugEnabled()) {
- logger.debug("Resource {} exists and will be updated - old url= {}, createdDate={}", resourceName,
- rrx.getResourceUrl(), rrx.getCreatedDate());
- }
- rrx.setLastUpdated(MonitorTime.getInstance().getDate());
- } else {
- // register resource by adding entry to table in DB
- logger.debug("Adding resource {} to ResourceRegistration table", resourceName);
- rrx = new ResourceRegistrationEntity();
- }
- // update/set columns in entry
- rrx.setResourceName(resourceName);
- rrx.setResourceUrl(jmxUrl);
- rrx.setNodeType(nodeType);
- rrx.setSite(siteName);
- em.persist(rrx);
- // flush to the DB
- synchronized (imFlushLock) {
- et.commit();
- }
+ createOrUpdateResourceReg(resourceName, jmxUrl, et);
} catch (Exception e) {
- logger.error("IntegrityMonitor constructor DB table update failed with exception: ", e);
+ logger.error("IntegrityMonitor constructor DB table update threw an exception");
try {
if (et.isActive()) {
synchronized (imFlushLock) {
@@ -326,36 +274,115 @@ public class IntegrityMonitor {
throw e;
}
+ makeStateManager(resourceName);
+
+ // create management bean
+ makeManagementBean(resourceName);
+
+ // set now as the last time the refreshStateAudit ran
+ IntegrityMonitor.this.refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate();
+
+ fpManager.set(new Thread(this::runFpManager));
+ fpManager.get().start();
+
+ }
+
+ protected void createOrUpdateForwardProgress(String resourceName) {
+ TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
+ fquery.setParameter("rn", resourceName);
+
+ List<ForwardProgressEntity> fpList =
+ fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ ForwardProgressEntity fpx;
+ if (!fpList.isEmpty()) {
+ // ignores multiple results
+ fpx = fpList.get(0);
+ // refresh the object from DB in case cached data was returned
+ em.refresh(fpx);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Resource {} exists and will be updated - old fpc= {}, lastUpdated= {}", resourceName,
+ fpx.getFpcCount(), fpx.getLastUpdated());
+ }
+ fpx.setFpcCount(fpCounter);
+ } else {
+ // Create a forward progress object
+ logger.debug("Adding resource {} to ForwardProgress table", resourceName);
+ fpx = new ForwardProgressEntity();
+ }
+ // update/set columns in entry
+ fpx.setResourceName(resourceName);
+ em.persist(fpx);
+ // flush to the DB
+ synchronized (imFlushLock) {
+ em.flush();
+ }
+ }
+
+ protected void createOrUpdateResourceReg(String resourceName, String jmxUrl, EntityTransaction et) {
+ TypedQuery<ResourceRegistrationEntity> rquery =
+ em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn",
+ ResourceRegistrationEntity.class);
+ rquery.setParameter("rn", resourceName);
+
+ List<ResourceRegistrationEntity> rrList =
+ rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ ResourceRegistrationEntity rrx;
+ if (!rrList.isEmpty()) {
+ // ignores multiple results
+ rrx = rrList.get(0);
+ // refresh the object from DB in case cached data was returned
+ em.refresh(rrx);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Resource {} exists and will be updated - old url= {}, createdDate={}", resourceName,
+ rrx.getResourceUrl(), rrx.getCreatedDate());
+ }
+ rrx.setLastUpdated(MonitorTime.getInstance().getDate());
+ } else {
+ // register resource by adding entry to table in DB
+ logger.debug("Adding resource {} to ResourceRegistration table", resourceName);
+ rrx = new ResourceRegistrationEntity();
+ }
+ // update/set columns in entry
+ rrx.setResourceName(resourceName);
+ rrx.setResourceUrl(jmxUrl);
+ rrx.setNodeType(nodeType);
+ rrx.setSite(siteName);
+ em.persist(rrx);
+ // flush to the DB
+ synchronized (imFlushLock) {
+ et.commit();
+ }
+ }
+
+ protected void makeStateManager(String resourceName) throws IntegrityMonitorException {
try {
// create instance of StateManagement class and pass emf to it
stateManager = new StateManagement(emf, resourceName);
- /**
- * Initialize the state and status attributes. This will maintain any Administrative
- * state value but will set the operational state = enabled, availability status = null,
- * standby status = null. The integrity monitor will set the operational state via the
- * FPManager and the owning application must set the standby status by calling
- * promote/demote on the StateManager.
+ /*
+ * Initialize the state and status attributes. This will maintain any Administrative state value but will
+ * set the operational state = enabled, availability status = null, standby status = null. The integrity
+ * monitor will set the operational state via the FPManager and the owning application must set the standby
+ * status by calling promote/demote on the StateManager.
*/
stateManager.initializeState();
} catch (StateManagementException e) {
throw new IntegrityMonitorException(e);
}
+ }
- // create management bean
+ protected void makeManagementBean(String resourceName) {
try {
new ComponentAdmin(resourceName, this, stateManager);
} catch (Exception e) {
- logger.error("ComponentAdmin constructor exception: {}", e.toString(), e);
+ logger.error("ComponentAdmin constructor exception: {}", e, e);
}
+ }
- // set now as the last time the refreshStateAudit ran
- IntegrityMonitor.this.refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate();
-
- fpManager = new Thread(this::runFpManager);
- fpManager.start();
-
+ private static void setInstance(IntegrityMonitor newInstance, String newResourceName) {
+ instance = newInstance;
+ resourceName = newResourceName;
}
/**
@@ -363,12 +390,12 @@ public class IntegrityMonitor {
* instance is allowed to be created per resource name.
*
* @param resourceName The resource name of the resource
- * @param properties a set of properties passed in from the resource
+ * @param properties a set of properties passed in from the resource
* @return The new instance of IntegrityMonitor
* @throws IntegrityMonitorException if unable to create jmx url or the constructor returns an exception
*/
public static IntegrityMonitor getInstance(String resourceName, Properties properties)
- throws IntegrityMonitorException {
+ throws IntegrityMonitorException {
synchronized (getInstanceLock) {
logger.debug("getInstance() called - resourceName= {}", resourceName);
@@ -379,7 +406,8 @@ public class IntegrityMonitor {
if (instance == null) {
logger.debug("Creating new instance of IntegrityMonitor");
- instance = new IntegrityMonitor(resourceName, properties);
+ // note: new() will populate "instance"
+ new IntegrityMonitor(resourceName, properties);
}
return instance;
}
@@ -395,7 +423,7 @@ public class IntegrityMonitor {
logger.debug("getInstance() called");
if (instance == null) {
String msg = "No IntegrityMonitor instance exists."
- + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)";
+ + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)";
throw new IntegrityMonitorPropertiesException(msg);
} else {
return instance;
@@ -411,7 +439,7 @@ public class IntegrityMonitor {
synchronized (getInstanceLock) {
if (isUnitTesting() && instance != null && instance.fpManager != null) {
// Stop the FPManager thread
- Thread fpm = instance.fpManager;
+ Thread fpm = instance.fpManager.get();
instance.fpManager = null;
fpm.interrupt();
@@ -426,7 +454,7 @@ public class IntegrityMonitor {
if (fpm.isAlive()) {
logger.error("IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
throw new IntegrityMonitorException(
- "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
+ "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
}
instance = null;
@@ -438,7 +466,7 @@ public class IntegrityMonitor {
private static String getJmxUrlFromProps() throws IntegrityMonitorException {
// get the jmx remote port and construct the JMX URL
- Properties systemProps = System.getProperties();
+ var systemProps = System.getProperties();
String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port");
String jmxErrMsg;
if (jmxPort == null) {
@@ -447,7 +475,7 @@ public class IntegrityMonitor {
throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
}
- int port = 0;
+ var port = 0;
try {
port = Integer.parseInt(jmxPort);
} catch (NumberFormatException e) {
@@ -462,12 +490,12 @@ public class IntegrityMonitor {
jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName();
}
} catch (Exception e) {
- String msg = "getJmxUrl could not get hostname";
+ var msg = "getJmxUrl could not get hostname";
logger.error("{}", msg, e);
throw new IntegrityMonitorException("getJmxUrl Exception: " + msg);
}
if (jmxFqdn == null) {
- String msg = "getJmxUrl encountered null hostname";
+ var msg = "getJmxUrl encountered null hostname";
logger.error("{}", msg);
throw new IntegrityMonitorException("getJmxUrl error: " + msg);
}
@@ -506,7 +534,7 @@ public class IntegrityMonitor {
}
// check standby state and throw exception if cold standby
if ((stateManager.getStandbyStatus() != null)
- && stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
+ && stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
String msg = RESOURCE_STRING + resourceName + " is cold standby";
logger.debug("{}", msg);
throw new StandbyStatusException("IntegrityMonitor Standby Status Exception: " + msg);
@@ -531,21 +559,22 @@ public class IntegrityMonitor {
String errorMsg =
withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> {
- Query query = em.createQuery(
- "Select p from ForwardProgressEntity p where p.resourceName=:resource");
+ TypedQuery<ForwardProgressEntity> query = em.createQuery(
+ "Select p from ForwardProgressEntity p where p.resourceName=:resource",
+ ForwardProgressEntity.class);
query.setParameter(LC_RESOURCE_STRING, dep);
- @SuppressWarnings("rawtypes")
- List fpList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT)
- .getResultList();
+ List<ForwardProgressEntity> fpList = query.setLockMode(LockModeType.NONE)
+ .setFlushMode(FlushModeType.COMMIT).getResultList();
if (!fpList.isEmpty()) {
// exists
- forwardProgressEntity.set((ForwardProgressEntity) fpList.get(0));
+ forwardProgressEntity.set(fpList.get(0));
// refresh the object from DB in case cached data was
// returned
em.refresh(forwardProgressEntity.get());
- logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}", dep);
+ logger.debug("Found entry in ForwardProgressEntity table for dependent Resource={}",
+ dep);
return null;
} else {
@@ -553,18 +582,20 @@ public class IntegrityMonitor {
}
});
- if (errorMsg == null) {
+ if (StringUtils.isEmpty(errorMsg)) {
errorMsg = withinTransaction(dep + ": StateManagementEntity DB read failed with exception: ", () -> {
// query if StateManagement entry exists for dependent resource
- Query query = em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource");
+ TypedQuery<StateManagementEntity> query =
+ em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
+ StateManagementEntity.class);
query.setParameter(LC_RESOURCE_STRING, dep);
- @SuppressWarnings("rawtypes")
- List smList = query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<StateManagementEntity> smList =
+ query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!smList.isEmpty()) {
// exist
- stateManagementEntity.set((StateManagementEntity) smList.get(0));
+ stateManagementEntity.set(smList.get(0));
// refresh the object from DB in case cached data was
// returned
em.refresh(stateManagementEntity.get());
@@ -577,12 +608,12 @@ public class IntegrityMonitor {
}
// verify that the ForwardProgress is current (check last_updated)
- if (errorMsg == null) {
+ if (StringUtils.isEmpty(errorMsg)) {
checkForwardProgress(dep, forwardProgressEntity.get(), stateManagementEntity.get());
}
// check operation, admin and standby states of dependent resource
- if (errorMsg == null) {
+ if (StringUtils.isEmpty(errorMsg)) {
errorMsg = checkDependentStates(dep, stateManagementEntity.get());
}
@@ -594,45 +625,38 @@ public class IntegrityMonitor {
/**
* Runs an action within a transaction.
*
- * @param exMsg message to log and return if an exception occurs
+ * @param exMsg message to log and return if an exception occurs
* @param action action to apply; returns non-null if an error occurs
* @return {@code null} if success, or an error message otherwise
*/
private String withinTransaction(String exMsg, Supplier<String> action) {
- String errorMsg = null;
-
// Start a transaction
EntityTransaction et = em.getTransaction();
et.begin();
try {
- errorMsg = action.get();
- if (errorMsg != null) {
- logger.error("{}", errorMsg);
- }
-
+ var errorMsg = action.get();
+ logger.error("{}", errorMsg);
synchronized (imFlushLock) {
et.commit();
}
-
+ return errorMsg;
} catch (RuntimeException ex) {
// log an error
- errorMsg = exMsg;
- logger.error("{}", errorMsg, ex);
+ logger.error("{}", exMsg, ex);
synchronized (imFlushLock) {
if (et.isActive()) {
et.rollback();
}
}
+ return exMsg;
}
-
- return errorMsg;
}
private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
- StateManagementEntity stateManagementEntity) {
+ StateManagementEntity stateManagementEntity) {
if (forwardProgressEntity != null && stateManagementEntity != null) {
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime();
logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs);
@@ -646,15 +670,13 @@ public class IntegrityMonitor {
}
} else {
+ String msg;
if (forwardProgressEntity == null) {
- String msg = STATE_CHECK_STRING + dep
- + "; " + " forwardProgressEntity == null.";
- logger.error("{}", msg);
+ msg = STATE_CHECK_STRING + dep + "; " + " forwardProgressEntity == null.";
} else {
- String msg = STATE_CHECK_STRING + dep
- + "; " + " stateManagementEntity == null.";
- logger.error("{}", msg);
+ msg = STATE_CHECK_STRING + dep + "; " + " stateManagementEntity == null.";
}
+ logger.error("{}", msg);
}
}
@@ -663,15 +685,15 @@ public class IntegrityMonitor {
if (stateManagementEntity != null) {
if ((stateManager.getAdminState() != null)
- && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) {
+ && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) {
errorMsg = dep + ": resource is administratively locked";
logger.error("{}", errorMsg);
} else if ((stateManager.getOpState() != null)
- && stateManagementEntity.getOpState().equals(StateManagement.DISABLED)) {
+ && stateManagementEntity.getOpState().equals(StateManagement.DISABLED)) {
errorMsg = dep + ": resource is operationally disabled";
logger.error("{}", errorMsg);
} else if ((stateManager.getStandbyStatus() != null)
- && stateManagementEntity.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
+ && stateManagementEntity.getStandbyStatus().equals(StateManagement.COLD_STANDBY)) {
errorMsg = dep + ": resource is cold standby";
logger.error("{}", errorMsg);
}
@@ -690,20 +712,20 @@ public class IntegrityMonitor {
}
private String fpCheck2(String dep) {
- Query fquery = em.createQuery(QUERY_STRING);
+ TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
fquery.setParameter("rn", dep);
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<ForwardProgressEntity> fpList =
+ fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
ForwardProgressEntity fpx;
if (!fpList.isEmpty()) {
// ignores multiple results
- fpx = (ForwardProgressEntity) fpList.get(0);
+ fpx = fpList.get(0);
// refresh the object from DB in case cached data was returned
em.refresh(fpx);
if (logger.isDebugEnabled()) {
logger.debug("Dependent resource {} - fpc= {}, lastUpdated={}", dep, fpx.getFpcCount(),
- fpx.getLastUpdated());
+ fpx.getLastUpdated());
}
long currTime = MonitorTime.getInstance().getMillis();
// if dependent resource FPC has not been updated, consider it
@@ -733,9 +755,9 @@ public class IntegrityMonitor {
ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
- Query fquery = em.createQuery("Select e from ForwardProgressEntity e");
+ var fquery = em.createQuery("Select e from ForwardProgressEntity e");
fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
- .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
+ .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
return null;
});
@@ -744,10 +766,10 @@ public class IntegrityMonitor {
}
logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
- int index = 0;
+ var index = 0;
for (ForwardProgressEntity fpe : fpList) {
logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
- fpe.getResourceName());
+ fpe.getResourceName());
}
return fpList;
@@ -759,9 +781,8 @@ public class IntegrityMonitor {
// get the JMX URL from the database
AtomicReference<String> jmxUrl = new AtomicReference<>();
- String errorMsg =
- withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ",
- () -> getJmxUrlFromDb(dep, jmxUrl));
+ String errorMsg = withinTransaction(dep + ": ResourceRegistrationEntity DB read failed with exception: ",
+ () -> getJmxUrlFromDb(dep, jmxUrl));
if (jmxUrl.get() != null) {
errorMsg = jmxCheck2(dep, jmxUrl.get(), errorMsg);
@@ -772,25 +793,24 @@ public class IntegrityMonitor {
private String getJmxUrlFromDb(String dep, AtomicReference<String> jmxUrl) {
// query if ResourceRegistration entry exists for resourceName
- Query rquery = em.createQuery(
- "Select r from ResourceRegistrationEntity r where r.resourceName=:rn");
+ TypedQuery<ResourceRegistrationEntity> rquery =
+ em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn",
+ ResourceRegistrationEntity.class);
rquery.setParameter("rn", dep);
- @SuppressWarnings("rawtypes")
- List rrList = rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT)
- .getResultList();
- ResourceRegistrationEntity rrx = null;
+ List<ResourceRegistrationEntity> rrList =
+ rquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ ResourceRegistrationEntity rrx;
if (!rrList.isEmpty()) {
// ignores multiple results
- rrx = (ResourceRegistrationEntity) rrList.get(0);
+ rrx = rrList.get(0);
// refresh the object from DB in case cached data was
// returned
em.refresh(rrx);
jmxUrl.set(rrx.getResourceUrl());
if (logger.isDebugEnabled()) {
- logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(),
- rrx.getCreatedDate());
+ logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(), rrx.getCreatedDate());
}
return null;
@@ -806,7 +826,7 @@ public class IntegrityMonitor {
jmxAgentConnection = new JmxAgentConnection(jmxUrl);
MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection();
ComponentAdminMBean admin =
- JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
+ JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
// invoke the test method via the jmx proxy
admin.test();
@@ -834,7 +854,7 @@ public class IntegrityMonitor {
synchronized (dependencyCheckLock) {
// Start with the error message empty
- StringBuilder errorMsg = new StringBuilder();
+ var errorMsg = new StringBuilder();
/*
* Before we check dependency groups we need to check subsystemTest.
@@ -846,18 +866,17 @@ public class IntegrityMonitor {
dependencyOk = checkDependencies(errorMsg) && dependencyOk;
/*
- * We have checked all the dependency groups. If all are ok and subsystemTest
- * passed, dependencyFailure == false
+ * We have checked all the dependency groups. If all are ok and subsystemTest passed, dependencyFailure
+ * == false
*/
if (dependencyOk) {
dependenciesGood(errorMsg);
}
} else if (dependencyOk) {
/*
- * This is put here to clean up when no dependency group should exist, but one was
- * erroneously added which caused the state to be disabled/dependency/coldstandby
- * and later removed. We saw this happen in the lab, but is not very likely in a
- * production environment...but you never know.
+ * This is put here to clean up when no dependency group should exist, but one was erroneously added
+ * which caused the state to be disabled/dependency/coldstandby and later removed. We saw this happen in
+ * the lab, but is not very likely in a production environment...but you never know.
*/
noDependencyGroups(errorMsg);
}
@@ -893,10 +912,8 @@ public class IntegrityMonitor {
// This indicates a subsystemTest failure
try {
if (logger.isDebugEnabled()) {
- logger.debug(
- "{}: There has been a subsystemTest failure with error:{} Updating this resource's "
- + "state to disableDependency",
- resourceName, e.getMessage());
+ logger.debug("{}: There has been a subsystemTest failure with error:{} Updating this resource's "
+ + "state to disableDependency", resourceName, e.getMessage());
}
// Capture the subsystemTest failure info
appendSeparator(errorMsg);
@@ -924,7 +941,7 @@ public class IntegrityMonitor {
* @return {@code true} if the dependencies are OK, {@code false} otherwise
*/
private boolean checkDependencies(StringBuilder errorMsg) {
- boolean dependencyOk = true;
+ var dependencyOk = true;
// check state of resources in dependency groups
for (String group : depGroups) {
@@ -936,7 +953,7 @@ public class IntegrityMonitor {
}
// check the next group
- } // end for (String group : depGroups)
+ }
return dependencyOk;
}
@@ -944,7 +961,7 @@ public class IntegrityMonitor {
/**
* Checks if a dependency group has an error.
*
- * @param group group to be checked
+ * @param group group to be checked
* @param errorMsg error messages are appended here
* @return {@code true} if the group has an error, {@code false} otherwise
*/
@@ -954,12 +971,12 @@ public class IntegrityMonitor {
// ignore empty group
return false;
}
- String[] dependencies = group.split(",");
+ String[] dependencies = COMMA_PAT.split(group);
if (logger.isDebugEnabled()) {
logger.debug("group dependencies = {}", Arrays.toString(dependencies));
}
- int realDepCount = 0;
- int failDepCount = 0;
+ var realDepCount = 0;
+ var failDepCount = 0;
for (String dep : dependencies) {
dep = dep.trim();
if (dep.isEmpty()) {
@@ -974,7 +991,7 @@ public class IntegrityMonitor {
appendSeparator(errorMsg);
errorMsg.append(failMsg);
}
- } // end for (String dep : dependencies)
+ }
// if all dependencies in a group are failed, set this
// resource's state to disable dependency
@@ -1005,16 +1022,16 @@ public class IntegrityMonitor {
* Disables the dependency group.
*
* @param errorMsg error messages are appended to this
- * @param group group of interest
+ * @param group group of interest
* @return {@code true} if it was successfully disabled, {@code false} otherwise
*/
private boolean disableDependency(StringBuilder errorMsg, String group) {
try {
logger.debug("All dependents in group {} have failed their health check. Updating this "
- + "resource's state to disableDependency", group);
- if (stateManager.getAvailStatus() == null || !((stateManager.getAvailStatus())
- .equals(StateManagement.DEPENDENCY)
- || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
+ + "resource's state to disableDependency", group);
+ if (stateManager.getAvailStatus() == null
+ || !((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
+ || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
// Note: redundant calls are made by
// refreshStateAudit
this.stateManager.disableDependency();
@@ -1033,12 +1050,11 @@ public class IntegrityMonitor {
private void dependenciesGood(StringBuilder errorMsg) {
try {
- logger.debug(
- "All dependency groups have at least one viable member. Updating this resource's state"
- + " to enableNoDependency");
+ logger.debug("All dependency groups have at least one viable member. Updating this resource's state"
+ + " to enableNoDependency");
if (stateManager.getAvailStatus() != null
- && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
- || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
+ && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
+ || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
// Note: redundant calls are made by
// refreshStateAudit
this.stateManager.enableNoDependency();
@@ -1057,8 +1073,8 @@ public class IntegrityMonitor {
try {
logger.debug("There are no dependents. Updating this resource's state to enableNoDependency");
if (stateManager.getAvailStatus() != null
- && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
- || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
+ && ((stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY)
+ || (stateManager.getAvailStatus()).equals(StateManagement.DEPENDENCY_FAILED))) {
// Note: redundant calls are made by refreshStateAudit
this.stateManager.enableNoDependency();
}
@@ -1073,7 +1089,7 @@ public class IntegrityMonitor {
}
private void appendSeparator(StringBuilder errorMsg) {
- if (errorMsg.length() != 0) {
+ if (!errorMsg.isEmpty()) {
errorMsg.append(',');
}
}
@@ -1099,9 +1115,8 @@ public class IntegrityMonitor {
* Additional testing for subsystems that do not have a /test interface (for ex. 3rd party processes like elk). This
* method would be overridden by the subsystem.
*
- * @throws IntegrityMonitorException if an error occurs
*/
- public void subsystemTest() throws IntegrityMonitorException {
+ public void subsystemTest() {
// Testing provided by subsystem
logger.debug("IntegrityMonitor subsystemTest() OK");
}
@@ -1123,8 +1138,8 @@ public class IntegrityMonitor {
// check standby state and throw exception if locked
if ((stateManager.getStandbyStatus() != null)
- && (stateManager.getStandbyStatus().equals(StateManagement.HOT_STANDBY)
- || stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY))) {
+ && (stateManager.getStandbyStatus().equals(StateManagement.HOT_STANDBY)
+ || stateManager.getStandbyStatus().equals(StateManagement.COLD_STANDBY))) {
String msg = RESOURCE_STRING + resourceName + " is standby";
throw new StandbyStatusException("IntegrityMonitor Standby Status Exception: " + msg);
@@ -1144,26 +1159,28 @@ public class IntegrityMonitor {
if (getAllNotWellMap() != null) {
if (!(getAllNotWellMap().isEmpty())) {
/*
- * An entity has reported that it is not well. We must not allow the the forward
- * progress counter to advance.
+ * An entity has reported that it is not well. We must not allow the forward progress counter to
+ * advance.
*/
- String msg = "allNotWellMap:";
- for (Entry<String, String> entry : allNotWellMap.entrySet()) {
- msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
- }
- logger.error("endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward"
- + "progress counter. \n{}\n", msg);
+ var msg = new StringBuilder("allNotWellMap:");
+ buildMapString(msg, allNotWellMap);
+ logger.error(
+ """
+ endTransaction: allNotWellMap is NOT EMPTY. Not advancing forward progress counter.
+ {}
+ """, msg);
return;
}
if (logger.isDebugEnabled() && getAllSeemsWellMap() != null && !(getAllSeemsWellMap().isEmpty())) {
- String msg = "allSeemsWellMap:";
- for (Entry<String, String> entry : allSeemsWellMap.entrySet()) {
- msg = msg.concat("\nkey = " + entry.getKey() + " msg = " + entry.getValue());
- }
+ var msg = new StringBuilder("allSeemsWellMap:");
+ buildMapString(msg, allSeemsWellMap);
logger.debug(
- "endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY. "
- + "Advancing forward progress counter. \n{}\n", msg);
+ """
+ endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY.
+ Advancing forward progress counter.
+ {}
+ """, msg);
}
}
// increment local FPC
@@ -1171,6 +1188,15 @@ public class IntegrityMonitor {
}
}
+ private void buildMapString(StringBuilder msg, Map<String, String> map) {
+ for (Entry<String, String> entry : map.entrySet()) {
+ msg.append("\nkey = ");
+ msg.append(entry.getKey());
+ msg.append(" msg = ");
+ msg.append(entry.getValue());
+ }
+ }
+
// update FP count in DB with local FP count
private void writeFpc() throws IntegrityMonitorException {
@@ -1183,20 +1209,20 @@ public class IntegrityMonitor {
try {
// query if ForwardProgress entry exists for resourceName
- Query fquery = em.createQuery(QUERY_STRING);
+ TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
fquery.setParameter("rn", resourceName);
- @SuppressWarnings("rawtypes")
- List fpList = fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<ForwardProgressEntity> fpList =
+ fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
ForwardProgressEntity fpx;
if (!fpList.isEmpty()) {
// ignores multiple results
- fpx = (ForwardProgressEntity) fpList.get(0);
+ fpx = fpList.get(0);
// refresh the object from DB in case cached data was returned
em.refresh(fpx);
if (logger.isDebugEnabled()) {
logger.debug("Updating FP entry: Resource={}, fpcCount={}, lastUpdated={}, new fpcCount={}",
- resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter);
+ resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter);
}
fpx.setFpcCount(fpCounter);
em.persist(fpx);
@@ -1219,16 +1245,11 @@ public class IntegrityMonitor {
} catch (Exception e1) {
logger.error(EXCEPTION_STRING, e1);
}
- logger.error("writeFpc DB table commit failed with exception: {}", e);
+ logger.error("writeFpc DB table commit failed with exception");
throw e;
}
}
- // retrieve state manager reference
- public final StateManagement getStateManager() {
- return this.stateManager;
- }
-
/**
* Read and validate properties.
*
@@ -1241,28 +1262,24 @@ public class IntegrityMonitor {
checkNonNull(prop, IntegrityMonitorProperties.DB_USER);
checkNonNull(prop, IntegrityMonitorProperties.DB_PWD);
- setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL,
- value -> monitorIntervalMs = toMillis(value));
+ setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL, value -> monitorIntervalMs = toMillis(value));
- setInt(prop, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD,
- value -> failedCounterThreshold = value);
+ setInt(prop, value -> failedCounterThreshold = value);
- setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL,
- value -> testTransIntervalMs = toMillis(value));
+ setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL, value -> testTransIntervalMs = toMillis(value));
- setLong(prop, IntegrityMonitorProperties.WRITE_FPC_INTERVAL,
- value -> writeFpcIntervalMs = toMillis(value));
+ setLong(prop, IntegrityMonitorProperties.WRITE_FPC_INTERVAL, value -> writeFpcIntervalMs = toMillis(value));
setLong(prop, IntegrityMonitorProperties.CHECK_DEPENDENCY_INTERVAL,
value -> checkDependencyIntervalMs = toMillis(value));
- // dependency_groups are a semi-colon separated list of groups
+ // dependency_groups are a semicolon separated list of groups
// each group is a comma separated list of resource names
// For ex. dependency_groups = site_1.pap_1,site_1.pap_2 ; site_1.pdp_1,
// site_1.pdp_2
String depGroupsValue = prop.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS);
if (!StringUtils.isBlank(depGroupsValue)) {
- depGroups = depGroupsValue.split(";");
+ depGroups = SEMICOLON_PAT.split(depGroupsValue);
if (logger.isDebugEnabled()) {
logger.debug("dependency groups property = {}", Arrays.toString(depGroups));
}
@@ -1285,14 +1302,13 @@ public class IntegrityMonitor {
setLong(prop, IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL,
value -> maxFpcUpdateIntervalMs = toMillis(value));
- setLong(prop, IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS,
- value -> stateAuditIntervalMs = value);
+ setLong(prop, IntegrityMonitorProperties.STATE_AUDIT_INTERVAL_MS, value -> stateAuditIntervalMs = value);
setLong(prop, IntegrityMonitorProperties.REFRESH_STATE_AUDIT_INTERVAL_MS,
value -> refreshStateAuditIntervalMs = value);
logger.debug("IntegrityMonitor.validateProperties(): Property values \nmaxFpcUpdateIntervalMs = {}\n",
- maxFpcUpdateIntervalMs);
+ maxFpcUpdateIntervalMs);
}
private static void setBoolean(Properties props, String propName, Consumer<Boolean> setter) {
@@ -1302,8 +1318,7 @@ public class IntegrityMonitor {
}
}
- private static String checkNonNull(Properties props, String propName)
- throws IntegrityMonitorPropertiesException {
+ private static String checkNonNull(Properties props, String propName) throws IntegrityMonitorPropertiesException {
String propValue = props.getProperty(propName);
if (propValue == null) {
@@ -1315,8 +1330,8 @@ public class IntegrityMonitor {
return propValue.trim();
}
- private static void setInt(Properties props, String propName, Consumer<Integer> setter) {
- String propValue = props.getProperty(propName);
+ private static void setInt(Properties props, IntConsumer setter) {
+ String propValue = props.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD);
if (StringUtils.isBlank(propValue)) {
return;
}
@@ -1324,11 +1339,11 @@ public class IntegrityMonitor {
try {
setter.accept(Integer.parseInt(propValue.trim()));
} catch (NumberFormatException e) {
- logger.warn(IGNORE_INVALID_PROPERTY_STRING, propName, e);
+ logger.warn(IGNORE_INVALID_PROPERTY_STRING, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, e);
}
}
- private static void setLong(Properties props, String propName, Consumer<Long> setter) {
+ private static void setLong(Properties props, String propName, LongConsumer setter) {
String propValue = props.getProperty(propName);
if (StringUtils.isBlank(propValue)) {
return;
@@ -1409,7 +1424,7 @@ public class IntegrityMonitor {
missedCycles += 1;
if (missedCycles >= failedCounterThreshold && !alarmExists) {
logger.debug("Forward progress not detected for resource {}. Setting state to disable failed.",
- resourceName);
+ resourceName);
if (!(stateManager.getOpState()).equals(StateManagement.DISABLED)) {
// Note: The refreshStateAudit will make redundant
// calls
@@ -1425,8 +1440,7 @@ public class IntegrityMonitor {
lastFpCounter = fpCounter;
missedCycles = 0;
// set op state to enabled
- logger.debug("Forward progress detected for resource {}. Setting state to enable not failed.",
- resourceName);
+ logger.debug("Forward progress detected for resource {}. Setting state to enable not failed.", resourceName);
if (!(stateManager.getOpState()).equals(StateManagement.ENABLED)) {
// Note: The refreshStateAudit will make redundant calls
stateManager.enableNotFailed();
@@ -1457,13 +1471,13 @@ public class IntegrityMonitor {
return;
}
if (!stateManager.getStandbyStatus().equals(StateManagement.NULL_VALUE)
- && stateManager.getStandbyStatus() != null
- && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) {
+ && stateManager.getStandbyStatus() != null
+ && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) {
logger.debug("IntegrityMonitor.stateAudit(): NOT PROVIDING_SERVICE. returning");
return;
}
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime();
if (timeSinceLastStateAudit < stateAuditIntervalMs) {
logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning");
@@ -1482,14 +1496,14 @@ public class IntegrityMonitor {
*/
public void executeStateAudit() {
logger.debug("IntegrityMonitor.executeStateAudit(): entry");
- Date date = MonitorTime.getInstance().getDate();
+ var date = MonitorTime.getInstance().getDate();
// Get all entries in the forwardprogressentity table
List<ForwardProgressEntity> fpList = getAllForwardProgressEntity();
// Check if each forwardprogressentity entry is current
for (ForwardProgressEntity fpe : fpList) {
- // If the this is my ForwardProgressEntity, continue
+ // If this is my ForwardProgressEntity, continue
if (fpe.getResourceName().equals(IntegrityMonitor.resourceName)) {
continue;
}
@@ -1498,21 +1512,21 @@ public class IntegrityMonitor {
long diffMs = date.getTime() - fpe.getLastUpdated().getTime();
if (logger.isDebugEnabled()) {
logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, diffMs = {}", fpe.getResourceName(),
- diffMs);
+ diffMs);
}
// Threshold for a stale entry
long staleMs = maxFpcUpdateIntervalMs;
if (logger.isDebugEnabled()) {
logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, staleMs = {}", fpe.getResourceName(),
- staleMs);
+ staleMs);
}
if (diffMs > staleMs) {
// ForwardProgress is stale. Disable it
// Start a transaction
logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, FPC is stale. Disabling it",
- fpe.getResourceName());
+ fpe.getResourceName());
EntityTransaction et = em.getTransaction();
et.begin();
StateManagementEntity sme = disableEntity(et, fpe);
@@ -1520,15 +1534,16 @@ public class IntegrityMonitor {
if (sme != null && !sme.getOpState().equals(StateManagement.DISABLED)) {
disableFailed(sme);
}
- } // end if(diffMs > staleMs)
- } // end for(ForwardProgressEntity fpe : fpList)
+ }
+ }
logger.debug("IntegrityMonitor.executeStateAudit(): exit");
}
/**
* Disables the entity.
+ *
* @param entrans entity transaction
- * @param fpe entity of interest
+ * @param fpe entity of interest
* @return the corresponding state management entity
*/
private StateManagementEntity disableEntity(EntityTransaction entrans, ForwardProgressEntity fpe) {
@@ -1536,28 +1551,26 @@ public class IntegrityMonitor {
try {
// query if StateManagement entry exists for fpe resource
- Query query =
- em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource");
+ TypedQuery<StateManagementEntity> query =
+ em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
+ StateManagementEntity.class);
query.setParameter(LC_RESOURCE_STRING, fpe.getResourceName());
- @SuppressWarnings("rawtypes")
- List smList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
+ List<StateManagementEntity> smList =
+ query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
if (!smList.isEmpty()) {
// exists
- sme = (StateManagementEntity) smList.get(0);
+ sme = smList.get(0);
// refresh the object from DB in case cached data was
// returned
em.refresh(sme);
if (logger.isDebugEnabled()) {
- logger.debug(
- "IntegrityMonitor.executeStateAudit(): Found entry in StateManagementEntity table "
- + "for Resource={}",
- sme.getResourceName());
+ logger.debug("IntegrityMonitor.executeStateAudit(): Found entry in StateManagementEntity table "
+ + "for Resource={}", sme.getResourceName());
}
} else {
String msg = "IntegrityMonitor.executeStateAudit(): " + fpe.getResourceName()
- + ": resource not found in state management entity database table";
+ + ": resource not found in state management entity database table";
logger.error("{}", msg);
}
synchronized (imFlushLock) {
@@ -1566,7 +1579,7 @@ public class IntegrityMonitor {
} catch (Exception e) {
// log an error
logger.error("IntegrityMonitor.executeStateAudit(): {}: StateManagementEntity DB read failed with "
- + "exception: ", fpe.getResourceName(), e);
+ + "exception: ", fpe.getResourceName(), e);
synchronized (imFlushLock) {
if (entrans.isActive()) {
entrans.rollback();
@@ -1584,19 +1597,18 @@ public class IntegrityMonitor {
stateManager.disableFailed(dep);
}
} catch (Exception e) {
- String msg = STATE_CHECK_STRING + dep
- + "; " + e.getMessage();
+ String msg = STATE_CHECK_STRING + dep + "; " + e.getMessage();
logger.error("{}", msg, e);
}
}
private void disableEntity(String dep) {
try {
- // create instance of StateMangement class for dependent
- StateManagement depStateManager = new StateManagement(emf, dep);
+ // create instance of StateManagement class for dependent
+ var depStateManager = new StateManagement(emf, dep);
if (!depStateManager.getOpState().equals(StateManagement.DISABLED)) {
logger.debug("Forward progress not detected for dependent resource {}. Setting dependent's "
- + "state to disable failed.", dep);
+ + "state to disable failed.", dep);
depStateManager.disableFailed();
}
} catch (Exception e) {
@@ -1607,12 +1619,13 @@ public class IntegrityMonitor {
/**
* Indicates a failure to disable an entity.
+ *
* @param sme entity of interest
*/
private void disableFailed(StateManagementEntity sme) {
if (logger.isDebugEnabled()) {
logger.debug("IntegrityMonitor.executeStateAudit(): Changing OpStat = disabled for {}",
- sme.getResourceName());
+ sme.getResourceName());
}
try {
stateManager.disableFailed(sme.getResourceName());
@@ -1692,7 +1705,7 @@ public class IntegrityMonitor {
long currTime = MonitorTime.getInstance().getMillis();
logger.debug("checkDependentHealth currTime - lastDependencyCheckTime = {}",
- currTime - lastDependencyCheckTime);
+ currTime - lastDependencyCheckTime);
if ((currTime - lastDependencyCheckTime) > checkDependencyIntervalMs) {
// execute dependency check and update this resource's state
@@ -1702,13 +1715,13 @@ public class IntegrityMonitor {
}
/*
- * This is a simple refresh audit which is periodically run to assure that the states and status
- * attributes are aligned and notifications are sent to any listeners. It is possible for
- * state/status to get out of sync and notified systems to be out of synch due to database
- * corruption (manual or otherwise) or because a node became isolated.
+ * This is a simple refresh audit which is periodically run to assure that the states and status attributes are
+ * aligned and notifications are sent to any listeners. It is possible for state/status to get out of sync and
+ * notified systems to be out of sync due to database corruption (manual or otherwise) or because a node became
+ * isolated.
*
- * When the operation (lock/unlock) is called, it will cause a re-evaluation of the state and
- * send a notification to all registered observers.
+ * When the operation (lock/unlock) is called, it will cause a re-evaluation of the state and send a notification to
+ * all registered observers.
*/
private void refreshStateAudit() {
logger.debug("refreshStateAudit(): entry");
@@ -1728,7 +1741,7 @@ public class IntegrityMonitor {
logger.debug("executeRefreshStateAudit(): entry");
synchronized (refreshStateAuditLock) {
logger.debug("refreshStateAudit: entry");
- Date now = MonitorTime.getInstance().getDate();
+ var now = MonitorTime.getInstance().getDate();
long nowMs = now.getTime();
long lastTimeMs = refreshStateAuditLastRunDate.getTime();
logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs);
@@ -1814,10 +1827,8 @@ public class IntegrityMonitor {
* @param key the key
* @param asw <code>true</code> if all seems well for the key, <code>false</code> if all seems not well for the key
* @param msg message to add for the key
- * @throws AllSeemsWellException if an error occurs
*/
- public void allSeemsWell(String key, Boolean asw, String msg)
- throws AllSeemsWellException {
+ public void allSeemsWell(String key, Boolean asw, String msg) {
logger.debug("allSeemsWell entry: key = {}, asw = {}, msg = {}", key, asw, msg);
if (StringUtils.isEmpty(key)) {
@@ -1841,7 +1852,7 @@ public class IntegrityMonitor {
allNotWellMap = new HashMap<>();
}
- if (asw) {
+ if (Boolean.TRUE.equals(asw)) {
logger.info("allSeemsWell: ALL SEEMS WELL: key = {}, msg = {}", key, msg);
allSeemsWellMap.put(key, msg);
allNotWellMap.remove(key);
@@ -1864,7 +1875,7 @@ public class IntegrityMonitor {
}
/**
- * Converts the given value to milliseconds using the current {@link #propertyUnits}.
+ * Converts the given value to milliseconds using the current propertyUnits.
*
* @param value value to be converted, or -1
* @return the value, in milliseconds, or -1
@@ -1873,19 +1884,10 @@ public class IntegrityMonitor {
return (value < 0 ? -1 : value * 1000L);
}
- public Map<String, String> getAllSeemsWellMap() {
- return allSeemsWellMap;
- }
-
- public Map<String, String> getAllNotWellMap() {
- return allNotWellMap;
- }
-
// these methods may be overridden by junit tests
/**
- * Indicates that the {@link FpManager#run()} method has started. This method
- * simply returns.
+ * Indicates that the {FpManager#run()} method has started. This method simply returns.
*
* @throws InterruptedException can be interrupted
*/
@@ -1910,16 +1912,4 @@ public class IntegrityMonitor {
protected String getPersistenceUnit() {
return PERSISTENCE_UNIT;
}
-
- /*
- * The remaining methods are used by JUnit tests.
- */
-
- public static boolean isUnitTesting() {
- return isUnitTesting;
- }
-
- public static void setUnitTesting(boolean isUnitTesting) {
- IntegrityMonitor.isUnitTesting = isUnitTesting;
- }
}