aboutsummaryrefslogtreecommitdiffstats
path: root/integrity-monitor/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'integrity-monitor/src/main')
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java41
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java42
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java41
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java1915
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java47
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java62
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java41
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java39
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java47
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java76
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java60
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java551
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java42
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java401
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java42
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java31
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java226
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java44
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java49
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java120
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java71
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java70
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java89
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java69
-rw-r--r--integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java113
-rw-r--r--integrity-monitor/src/main/resources/META-INF/persistence.xml51
-rw-r--r--integrity-monitor/src/main/resources/log4j.properties48
27 files changed, 0 insertions, 4428 deletions
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java
deleted file mode 100644
index 14e0f0a8..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/AdministrativeStateException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class AdministrativeStateException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public AdministrativeStateException() {
- super();
- }
-
- public AdministrativeStateException(String message) {
- super(message);
- }
-
- public AdministrativeStateException(Throwable cause) {
- super(cause);
- }
-
- public AdministrativeStateException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java
deleted file mode 100644
index 1583a9d5..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/AllSeemsWellException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class AllSeemsWellException extends IntegrityMonitorException {
-
- private static final long serialVersionUID = 1L;
-
- public AllSeemsWellException() {
- super();
- }
-
- public AllSeemsWellException(String msg) {
- super(msg);
- }
-
- public AllSeemsWellException(String msg, Exception cause) {
- super(msg, cause);
- }
-
- public AllSeemsWellException(Exception cause) {
- super(cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java
deleted file mode 100644
index a72fe9e2..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/ForwardProgressException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class ForwardProgressException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public ForwardProgressException() {
- super();
- }
-
- public ForwardProgressException(String message) {
- super(message);
- }
-
- public ForwardProgressException(Throwable cause) {
- super(cause);
- }
-
- public ForwardProgressException(String message, Throwable cause) {
- super(message, cause);
- }
-}
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
deleted file mode 100644
index 7031c50a..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitor.java
+++ /dev/null
@@ -1,1915 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.
- * 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.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;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-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 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;
-import org.onap.policy.common.im.jmx.JmxAgentConnection;
-import org.onap.policy.common.im.jpa.ForwardProgressEntity;
-import org.onap.policy.common.im.jpa.ResourceRegistrationEntity;
-import org.onap.policy.common.im.jpa.StateManagementEntity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * IntegrityMonitor Main class for monitoring the integrity of a resource and managing its state. State management
- * follows the X.731 ITU standard.
- */
-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;
-
- /*
- * Common strings
- */
- private static final String NULL_PROPERTY_STRING = " property is null";
- 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 RESOURCE_STRING = "Resource ";
- private static final String LC_RESOURCE_STRING = "resource";
-
- /*
- * Query String
- */
- private static final String QUERY_STRING = "Select f from ForwardProgressEntity f where f.resourceName=:rn";
-
- private static String resourceName = null;
- boolean alarmExists = false;
-
- /*
- * 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 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 AtomicReference<Thread> fpManager = new AtomicReference<>();
-
- // The forward progress counter is incremented as the
- // process being monitored makes forward progress
- private int fpCounter = 0;
- private int lastFpCounter = 0;
-
- // elapsed time since last FP counter check
- private long elapsedTime = 0;
-
- // elapsed time since last test transaction check
- private long elapsedTestTransTime = 0;
-
- // elapsed time since last write Fpc check
- private long elapsedWriteFpcTime = 0;
-
- // last dependency health check time. Initialize so that the periodic check
- // starts after 60 seconds.
- // This allows time for dependents to come up.
- private long lastDependencyCheckTime = MonitorTime.getInstance().getMillis();
-
- // Time of the last state audit. It is initialized at the time of the IM
- // construction
- private Date lastStateAuditTime = MonitorTime.getInstance().getDate();
-
- // Interval between state audits in ms. We leave it turned off by default so
- // that it will only
- // be run on the nodes which we want doing the audit. In particular, we only
- // want it to run
- // on the droolspdps
- private static long stateAuditIntervalMs = 0L;
-
- // the number of cycles since 'fpCounter' was last changed
- private int missedCycles = 0;
-
- // forward progress monitoring interval
- private static long monitorIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_MONITOR_INTERVAL);
- // The number of periods the counter fails to increment before an alarm is
- // raised.
- private static int failedCounterThreshold = IntegrityMonitorProperties.DEFAULT_FAILED_COUNTER_THRESHOLD;
- // test transaction interval
- private static long testTransIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_TEST_INTERVAL);
- // write Fpc to DB interval
- 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);
-
- // 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;
-
- @Getter
- @Setter
- private static boolean unitTesting = false;
-
- // can turn on health checking of dependents via jmx test() call by setting
- // this property to true
- private static boolean testViaJmx = false;
-
- private static String jmxFqdn = null;
-
- // this is the max interval allowed without any forward progress
- // counter updates
- private static long maxFpcUpdateIntervalMs = toMillis(IntegrityMonitorProperties.DEFAULT_MAX_FPC_UPDATE_INTERVAL);
-
- // Node types
- private enum NodeType {
- PDP_XACML, PDP_DROOLS, PAP, PAP_ADMIN, LOGPARSER, BRMS_GATEWAY, ASTRA_GATEWAY, ELK_SERVER, PYPDP
-
- }
-
- private static String siteName;
- private static String nodeType;
- private Date refreshStateAuditLastRunDate;
- private static long refreshStateAuditIntervalMs = 600000; // run it once per 10 minutes
-
- // lock objects
- private final Object evaluateSanityLock = new Object();
- private final Object fpMonitorCycleLock = new Object();
- private final Object dependencyCheckLock = new Object();
- private final Object testTransactionLock = new Object();
- private final Object startTransactionLock = new Object();
- private final Object endTransactionLock = new Object();
- private final Object checkTestTransactionLock = new Object();
- private final Object checkWriteFpcLock = new Object();
- private static final Object getInstanceLock = new Object();
- 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 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
- * @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
- // subclass
- if (instance != null) {
- var msg = "IM object exists and only one instance allowed";
- logger.error("{}", msg);
- throw new IntegrityMonitorException("IntegrityMonitor constructor exception: " + msg);
- }
-
- setInstance(this, resourceName);
-
- /*
- * Validate that the properties file contains all the needed properties. Throws an
- * IntegrityMonitorPropertiesException
- */
- validateProperties(properties);
-
- // construct jmx url
- String jmxUrl = getJmxUrlFromProps();
-
- //
- // Create the entity manager factory
- //
- emf = Persistence.createEntityManagerFactory(getPersistenceUnit(), properties);
-
- // add entry to forward progress and resource registration tables in DB
-
- // Start a transaction
- em = emf.createEntityManager();
- EntityTransaction et = em.getTransaction();
-
- et.begin();
-
- try {
- // if ForwardProgress entry exists for resourceName, update it. If
- // not found, create a new entry
- createOrUpdateForwardProgress(resourceName);
-
- // if ResourceRegistration entry exists for resourceName, update it.
- // If not found, create a new entry
- createOrUpdateResourceReg(resourceName, jmxUrl, et);
-
- } catch (Exception e) {
- logger.error("IntegrityMonitor constructor DB table update threw an exception");
- try {
- if (et.isActive()) {
- synchronized (imFlushLock) {
- et.rollback();
- }
- }
- } catch (Exception e1) {
- logger.error("IntegrityMonitor constructor threw exception: ", e1);
- }
- 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.
- */
- stateManager.initializeState();
-
- } catch (StateManagementException e) {
- throw new IntegrityMonitorException(e);
- }
- }
-
- protected void makeManagementBean(String resourceName) {
- try {
- new ComponentAdmin(resourceName, this, stateManager);
- } catch (Exception e) {
- logger.error("ComponentAdmin constructor exception: {}", e, e);
- }
- }
-
- private static void setInstance(IntegrityMonitor newInstance, String newResourceName) {
- instance = newInstance;
- resourceName = newResourceName;
- }
-
- /**
- * Get an instance of IntegrityMonitor for a given resource name. It creates one if it does not exist. 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
- * @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 {
-
- synchronized (getInstanceLock) {
- logger.debug("getInstance() called - resourceName= {}", resourceName);
- if (resourceName == null || resourceName.isEmpty() || properties == null) {
- logger.error("Error: getIntegrityMonitorInstance() called with invalid input");
- return null;
- }
-
- if (instance == null) {
- logger.debug("Creating new instance of IntegrityMonitor");
- // note: new() will populate "instance"
- new IntegrityMonitor(resourceName, properties);
- }
- return instance;
- }
- }
-
- /**
- * Get the single instance.
- *
- * @return the instance
- * @throws IntegrityMonitorException if no instance exists
- */
- public static IntegrityMonitor getInstance() throws IntegrityMonitorException {
- logger.debug("getInstance() called");
- if (instance == null) {
- String msg = "No IntegrityMonitor instance exists."
- + " Please use the method IntegrityMonitor.getInstance(String resourceName, Properties properties)";
- throw new IntegrityMonitorPropertiesException(msg);
- } else {
- return instance;
- }
- }
-
- /**
- * This is a facility used by JUnit testing to destroy the IntegrityMonitor instance before creating a new one. It
- * waits a bit to allow the FPManager to fully exit.
- */
- public static void deleteInstance() throws IntegrityMonitorException {
- logger.debug("deleteInstance() called");
- synchronized (getInstanceLock) {
- if (isUnitTesting() && instance != null && instance.fpManager != null) {
- // Stop the FPManager thread
- Thread fpm = instance.fpManager.get();
- instance.fpManager = null;
- fpm.interrupt();
-
- try {
- // Make sure it has exited
- fpm.join(2000L);
- } catch (InterruptedException e) {
- logger.error("deleteInstance: Interrupted while waiting for FPManager to fully exit", e);
- Thread.currentThread().interrupt();
- }
-
- if (fpm.isAlive()) {
- logger.error("IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
- throw new IntegrityMonitorException(
- "IntegrityMonitor.deleteInstance() Failed to kill FPManager thread");
- }
-
- instance = null;
- }
- }
- logger.debug("deleteInstance() exit");
- }
-
- private static String getJmxUrlFromProps() throws IntegrityMonitorException {
-
- // get the jmx remote port and construct the JMX URL
- var systemProps = System.getProperties();
- String jmxPort = systemProps.getProperty("com.sun.management.jmxremote.port");
- String jmxErrMsg;
- if (jmxPort == null) {
- jmxErrMsg = "System property com.sun.management.jmxremote.port for JMX remote port is not set";
- logger.error("{}", jmxErrMsg);
- throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
- }
-
- var port = 0;
- try {
- port = Integer.parseInt(jmxPort);
- } catch (NumberFormatException e) {
- jmxErrMsg = "JMX remote port is not a valid integer value - " + jmxPort;
- logger.error("{}", jmxErrMsg);
- throw new IntegrityMonitorException("getJmxUrl exception: " + jmxErrMsg);
- }
-
- try {
- if (jmxFqdn == null) {
- // get FQDN of this host
- jmxFqdn = InetAddress.getLocalHost().getCanonicalHostName();
- }
- } catch (Exception e) {
- var msg = "getJmxUrl could not get hostname";
- logger.error("{}", msg, e);
- throw new IntegrityMonitorException("getJmxUrl Exception: " + msg);
- }
- if (jmxFqdn == null) {
- var msg = "getJmxUrl encountered null hostname";
- logger.error("{}", msg);
- throw new IntegrityMonitorException("getJmxUrl error: " + msg);
- }
-
- // assemble the jmx url
- String jmxUrl = "service:jmx:rmi:///jndi/rmi://" + jmxFqdn + ":" + port + "/jmxrmi";
-
- logger.debug("IntegrityMonitor - jmx url={}", jmxUrl);
-
- return jmxUrl;
- }
-
- /**
- * evaluateSanity() is designed to be called by an external entity to evaluate the sanity of the node. It checks the
- * operational and administrative states and the standby status. If the operational state is disabled, it will
- * include the dependencyCheckErrorMsg which includes information about any dependency (node) which has failed.
- */
- public void evaluateSanity() throws IntegrityMonitorException {
- logger.debug("evaluateSanity called ....");
- synchronized (evaluateSanityLock) {
-
- String errorMsg = dependencyCheckErrorMsg;
- logger.debug("evaluateSanity dependencyCheckErrorMsg = {}", errorMsg);
- // check op state and throw exception if disabled
- if ((stateManager.getOpState() != null) && stateManager.getOpState().equals(StateManagement.DISABLED)) {
- String msg = RESOURCE_STRING + resourceName + " operation state is disabled. " + errorMsg;
- logger.debug("{}", msg);
- throw new IntegrityMonitorException(msg);
- }
-
- // check admin state and throw exception if locked
- if ((stateManager.getAdminState() != null) && stateManager.getAdminState().equals(StateManagement.LOCKED)) {
- String msg = RESOURCE_STRING + resourceName + " is administratively locked";
- logger.debug("{}", msg);
- throw new AdministrativeStateException("IntegrityMonitor Admin State Exception: " + msg);
- }
- // check standby state and throw exception if cold standby
- if ((stateManager.getStandbyStatus() != null)
- && 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);
- }
-
- }
-
- }
-
- /**
- * This method checks the forward progress counter and the state of a dependency. If the dependency is unavailable
- * or failed, an error message is created which is checked when evaluateSanity interface is called. If the error
- * message is set then the evaluateSanity will return an error.
- *
- * @param dep the dependency
- * @return {@code null} if success, an error message otherwise
- */
- public String stateCheck(String dep) {
- logger.debug("checking state of dependent resource: {}", dep);
- AtomicReference<ForwardProgressEntity> forwardProgressEntity = new AtomicReference<>();
- AtomicReference<StateManagementEntity> stateManagementEntity = new AtomicReference<>();
-
- String errorMsg =
- withinTransaction(dep + ": ForwardProgressEntity DB operation failed with exception: ", () -> {
- TypedQuery<ForwardProgressEntity> query = em.createQuery(
- "Select p from ForwardProgressEntity p where p.resourceName=:resource",
- ForwardProgressEntity.class);
- query.setParameter(LC_RESOURCE_STRING, dep);
-
- List<ForwardProgressEntity> fpList = query.setLockMode(LockModeType.NONE)
- .setFlushMode(FlushModeType.COMMIT).getResultList();
-
- if (!fpList.isEmpty()) {
- // exists
- 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);
- return null;
-
- } else {
- return dep + ": resource not found in ForwardProgressEntity database table";
- }
- });
-
- if (StringUtils.isEmpty(errorMsg)) {
- errorMsg = withinTransaction(dep + ": StateManagementEntity DB read failed with exception: ", () -> {
-
- // query if StateManagement entry exists for dependent resource
- TypedQuery<StateManagementEntity> query =
- em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
- StateManagementEntity.class);
- query.setParameter(LC_RESOURCE_STRING, dep);
-
- List<StateManagementEntity> smList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!smList.isEmpty()) {
- // exist
- stateManagementEntity.set(smList.get(0));
- // refresh the object from DB in case cached data was
- // returned
- em.refresh(stateManagementEntity.get());
- logger.debug("Found entry in StateManagementEntity table for dependent Resource={}", dep);
- return null;
- } else {
- return dep + ": resource not found in state management entity database table";
- }
- });
- }
-
- // verify that the ForwardProgress is current (check last_updated)
- if (StringUtils.isEmpty(errorMsg)) {
- checkForwardProgress(dep, forwardProgressEntity.get(), stateManagementEntity.get());
- }
-
- // check operation, admin and standby states of dependent resource
- if (StringUtils.isEmpty(errorMsg)) {
- errorMsg = checkDependentStates(dep, stateManagementEntity.get());
- }
-
- String returnMsg = "IntegrityMonitor.stateCheck(): returned error_msg: " + errorMsg;
- logger.debug("{}", returnMsg);
- return errorMsg;
- }
-
- /**
- * Runs an action within a transaction.
- *
- * @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) {
- // Start a transaction
- EntityTransaction et = em.getTransaction();
- et.begin();
-
- try {
- var errorMsg = action.get();
- logger.error("{}", errorMsg);
- synchronized (imFlushLock) {
- et.commit();
- }
- return errorMsg;
- } catch (RuntimeException ex) {
- // log an error
- logger.error("{}", exMsg, ex);
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
- }
- return exMsg;
- }
- }
-
- private void checkForwardProgress(String dep, ForwardProgressEntity forwardProgressEntity,
- StateManagementEntity stateManagementEntity) {
- if (forwardProgressEntity != null && stateManagementEntity != null) {
- var date = MonitorTime.getInstance().getDate();
- long diffMs = date.getTime() - forwardProgressEntity.getLastUpdated().getTime();
- logger.debug("IntegrityMonitor.stateCheck(): diffMs = {}", diffMs);
-
- // Threshold for a stale entry
- long staleMs = maxFpcUpdateIntervalMs;
- logger.debug("IntegrityMonitor.stateCheck(): staleMs = {}", staleMs);
-
- if (diffMs > staleMs) {
- // ForwardProgress is stale. Disable it
- disableEntity(dep, stateManagementEntity);
- }
- } else {
-
- String msg;
- if (forwardProgressEntity == null) {
- msg = STATE_CHECK_STRING + dep + "; " + " forwardProgressEntity == null.";
- } else {
- msg = STATE_CHECK_STRING + dep + "; " + " stateManagementEntity == null.";
- }
- logger.error("{}", msg);
- }
- }
-
- private String checkDependentStates(String dep, StateManagementEntity stateManagementEntity) {
- String errorMsg = null;
-
- if (stateManagementEntity != null) {
- if ((stateManager.getAdminState() != null)
- && stateManagementEntity.getAdminState().equals(StateManagement.LOCKED)) {
- errorMsg = dep + ": resource is administratively locked";
- logger.error("{}", errorMsg);
- } else if ((stateManager.getOpState() != null)
- && 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)) {
- errorMsg = dep + ": resource is cold standby";
- logger.error("{}", errorMsg);
- }
- } else {
- errorMsg = dep + ": could not check standy state of resource. stateManagementEntity == null.";
- logger.error("{}", errorMsg);
- }
-
- return errorMsg;
- }
-
- private String fpCheck(String dep) {
- logger.debug("checking forward progress count of dependent resource: {}", dep);
-
- return withinTransaction(dep + ": ForwardProgressEntity DB read failed with exception: ", () -> fpCheck2(dep));
- }
-
- private String fpCheck2(String dep) {
- TypedQuery<ForwardProgressEntity> fquery = em.createQuery(QUERY_STRING, ForwardProgressEntity.class);
- fquery.setParameter("rn", dep);
-
- 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("Dependent resource {} - fpc= {}, lastUpdated={}", dep, fpx.getFpcCount(),
- fpx.getLastUpdated());
- }
- long currTime = MonitorTime.getInstance().getMillis();
- // if dependent resource FPC has not been updated, consider it
- // an error
- if ((currTime - fpx.getLastUpdated().getTime()) > maxFpcUpdateIntervalMs) {
- disableEntity(dep);
- return dep + ": FP count has not been updated in the last " + maxFpcUpdateIntervalMs + "ms";
- }
-
- return null;
-
- } else {
- // resource entry not found in FPC table
- return dep + ": resource not found in ForwardProgressEntity table in the DB";
- }
- }
-
- /**
- * Get all forward progress entities.
- *
- * @return list of all forward progress entities
- */
- @SuppressWarnings("unchecked")
- public List<ForwardProgressEntity> getAllForwardProgressEntity() {
- logger.debug("getAllForwardProgressEntity: entry");
-
- ArrayList<ForwardProgressEntity> fpList = new ArrayList<>();
-
- withinTransaction("getAllForwardProgessEntity DB read failed with exception: ", () -> {
- var fquery = em.createQuery("Select e from ForwardProgressEntity e");
- fquery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList()
- .forEach(obj -> fpList.add((ForwardProgressEntity) obj));
- return null;
- });
-
- if (!logger.isDebugEnabled()) {
- return fpList;
- }
-
- logger.debug("getAllForwardProgressEntity: fpList.size(): {}", fpList.size());
- var index = 0;
- for (ForwardProgressEntity fpe : fpList) {
- logger.debug("getAllForwardProgressEntity: fpList.get({}).getResourceName(): {}", index++,
- fpe.getResourceName());
- }
-
- return fpList;
- }
-
- private String jmxCheck(String dep) {
- logger.debug("checking health of dependent by calling test() via JMX on resource: {}", dep);
-
- // 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));
-
- if (jmxUrl.get() != null) {
- errorMsg = jmxCheck2(dep, jmxUrl.get(), errorMsg);
- }
-
- return errorMsg;
- }
-
- private String getJmxUrlFromDb(String dep, AtomicReference<String> jmxUrl) {
- // query if ResourceRegistration entry exists for resourceName
- TypedQuery<ResourceRegistrationEntity> rquery =
- em.createQuery("Select r from ResourceRegistrationEntity r where r.resourceName=:rn",
- ResourceRegistrationEntity.class);
- rquery.setParameter("rn", dep);
-
- 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);
- jmxUrl.set(rrx.getResourceUrl());
- if (logger.isDebugEnabled()) {
- logger.debug("Dependent Resource={}, url={}, createdDate={}", dep, jmxUrl.get(), rrx.getCreatedDate());
- }
-
- return null;
-
- } else {
- return dep + ": resource not found in ResourceRegistrationEntity table in the DB";
- }
- }
-
- private String jmxCheck2(String dep, String jmxUrl, String errorMsg) {
- JmxAgentConnection jmxAgentConnection = null;
- try {
- jmxAgentConnection = new JmxAgentConnection(jmxUrl);
- MBeanServerConnection mbeanServer = jmxAgentConnection.getMBeanConnection();
- ComponentAdminMBean admin =
- JMX.newMXBeanProxy(mbeanServer, ComponentAdmin.getObjectName(dep), ComponentAdminMBean.class);
-
- // invoke the test method via the jmx proxy
- admin.test();
- logger.debug("Dependent resource {} sanity test passed", dep);
- } catch (Exception e) {
- String errorMsg2 = dep + ": resource sanity test failed with exception: ";
- logger.error("{}", errorMsg2, e);
- return errorMsg2;
- } finally {
- // close the JMX connector
- if (jmxAgentConnection != null) {
- jmxAgentConnection.disconnect();
- }
- }
- return errorMsg;
- }
-
- /**
- * Perform a dependency check.
- *
- * @return an error message detailing any issues found
- */
- public String dependencyCheck() {
- logger.debug("dependencyCheck: entry");
- synchronized (dependencyCheckLock) {
-
- // Start with the error message empty
- var errorMsg = new StringBuilder();
-
- /*
- * Before we check dependency groups we need to check subsystemTest.
- */
- boolean dependencyOk = checkSubsystems(errorMsg);
-
- // Check the sanity of dependents for lead subcomponents
- if (depGroups != null && depGroups.length > 0) {
- dependencyOk = checkDependencies(errorMsg) && dependencyOk;
-
- /*
- * 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.
- */
- noDependencyGroups(errorMsg);
- }
-
- dependencyCheckErrorMsg = errorMsg.toString();
- lastDependencyCheckTime = MonitorTime.getInstance().getMillis();
-
- if (!dependencyCheckErrorMsg.isEmpty()) {
- logger.error("Sanity failure detected in a dependent resource: {}", errorMsg);
-
- }
-
- logger.debug("dependencyCheck: exit");
- return dependencyCheckErrorMsg;
- }
- }
-
- /**
- * Checks the subsystems.
- *
- * @param errorMsg error messages are appended to this
- * @return {@code true} if the test succeeds, {@code false} otherwise
- */
- private boolean checkSubsystems(StringBuilder errorMsg) {
- try {
- // Test any subsystems that are not covered under the dependency
- // relationship
- subsystemTest();
- return true;
-
- } catch (Exception e) {
- logger.error("IntegrityMonitor threw exception", e);
- // 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());
- }
- // Capture the subsystemTest failure info
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": ");
- errorMsg.append(e.getMessage());
- this.stateManager.disableDependency();
- } catch (Exception ex) {
- logger.error(EXCEPTION_STRING, ex);
- appendSeparator(errorMsg);
- errorMsg.append('\n');
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to disable dependency after subsystemTest failure due to: ");
- errorMsg.append(ex.getMessage());
- }
-
- return false;
- }
- }
-
- /**
- * Checks the dependencies.
- *
- * @param errorMsg error messages are appended to this
- * @return {@code true} if the dependencies are OK, {@code false} otherwise
- */
- private boolean checkDependencies(StringBuilder errorMsg) {
- var dependencyOk = true;
-
- // check state of resources in dependency groups
- for (String group : depGroups) {
- if (checkDependencyGroupHasError(group, errorMsg)) {
- dependencyOk = false;
- if (!disableDependency(errorMsg, group)) {
- break; // break out on failure and skip checking other groups
- }
- }
- // check the next group
-
- }
-
- return dependencyOk;
- }
-
- /**
- * Checks if a dependency group has an error.
- *
- * @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
- */
- private boolean checkDependencyGroupHasError(String group, StringBuilder errorMsg) {
- group = group.trim();
- if (group.isEmpty()) {
- // ignore empty group
- return false;
- }
- String[] dependencies = COMMA_PAT.split(group);
- if (logger.isDebugEnabled()) {
- logger.debug("group dependencies = {}", Arrays.toString(dependencies));
- }
- var realDepCount = 0;
- var failDepCount = 0;
- for (String dep : dependencies) {
- dep = dep.trim();
- if (dep.isEmpty()) {
- // ignore empty dependency
- continue;
- }
- realDepCount++; // this is a valid dependency whose state is tracked
- // if a resource is down, its FP count will not be incremented
- String failMsg = doDependencyChecks(dep);
- if (failMsg != null) {
- failDepCount++;
- appendSeparator(errorMsg);
- errorMsg.append(failMsg);
- }
- }
-
- // if all dependencies in a group are failed, set this
- // resource's state to disable dependency
- return (realDepCount > 0) && (failDepCount == realDepCount);
- }
-
- /**
- * Checks a single dependency.
- *
- * @param dep dependency to be checked
- * @return the failure message, or {@code null} if all checks passed
- */
- private String doDependencyChecks(String dep) {
- String failMsg = fpCheck(dep);
-
- if (failMsg == null) {
- if (testViaJmx) {
- failMsg = jmxCheck(dep);
- } else {
- failMsg = stateCheck(dep);
- }
- }
-
- return failMsg;
- }
-
- /**
- * Disables the dependency group.
- *
- * @param errorMsg error messages are appended to this
- * @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))) {
- // Note: redundant calls are made by
- // refreshStateAudit
- this.stateManager.disableDependency();
- }
-
- return true;
-
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to disable dependency");
- return false;
- }
- }
-
- private void dependenciesGood(StringBuilder errorMsg) {
- try {
- 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))) {
- // Note: redundant calls are made by
- // refreshStateAudit
- this.stateManager.enableNoDependency();
- }
- // The refreshStateAudit will catch the case where it is disabled but
- // availStatus != failed
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to enable no dependency");
- }
- }
-
- private void noDependencyGroups(StringBuilder errorMsg) {
- 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))) {
- // Note: redundant calls are made by refreshStateAudit
- this.stateManager.enableNoDependency();
- }
- // The refreshStateAudit will catch the case where it is disabled but
- // availStatus != failed
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- appendSeparator(errorMsg);
- errorMsg.append(resourceName);
- errorMsg.append(": Failed to enable no dependency");
- }
- }
-
- private void appendSeparator(StringBuilder errorMsg) {
- if (!errorMsg.isEmpty()) {
- errorMsg.append(',');
- }
- }
-
- /**
- * Execute a test transaction. It is called when the test transaction timer fires. It could be overridden to provide
- * additional test functionality. If overridden, the overriding method must invoke startTransaction() and
- * endTransaction() and check if the allNotWellMap is empty.
- */
- public void testTransaction() {
- synchronized (testTransactionLock) {
- logger.debug("testTransaction: entry");
- //
- // startTransaction() not required for testTransaction
- //
-
- // end transaction - increments local FP counter
- endTransaction();
- }
- }
-
- /**
- * 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.
- *
- */
- public void subsystemTest() {
- // Testing provided by subsystem
- logger.debug("IntegrityMonitor subsystemTest() OK");
- }
-
- /**
- * Checks admin state and resets transaction timer. Called by application at the start of a transaction.
- *
- * @throws IntegrityMonitorException if resource is locked or in standby
- */
- public void startTransaction() throws IntegrityMonitorException {
-
- synchronized (startTransactionLock) {
- // check admin state and throw exception if locked
- if ((stateManager.getAdminState() != null) && stateManager.getAdminState().equals(StateManagement.LOCKED)) {
- String msg = RESOURCE_STRING + resourceName + " is administratively locked";
-
- throw new AdministrativeStateException("IntegrityMonitor Admin State Exception: " + msg);
- }
- // check standby state and throw exception if locked
-
- if ((stateManager.getStandbyStatus() != null)
- && (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);
- }
-
- // reset transactionTimer so it will not fire
- elapsedTestTransTime = 0;
- }
- }
-
- /**
- * Increment the local forward progress counter. Called by application at the end of each transaction (successful or
- * not).
- */
- public void endTransaction() {
- synchronized (endTransactionLock) {
- if (getAllNotWellMap() != null) {
- if (!(getAllNotWellMap().isEmpty())) {
- /*
- * An entity has reported that it is not well. We must not allow the forward progress counter to
- * advance.
- */
- 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())) {
- var msg = new StringBuilder("allSeemsWellMap:");
- buildMapString(msg, allSeemsWellMap);
- logger.debug(
- """
- endTransaction: allNotWellMap IS EMPTY and allSeemsWellMap is NOT EMPTY.
- Advancing forward progress counter.
- {}
- """, msg);
- }
- }
- // increment local FPC
- fpCounter++;
- }
- }
-
- 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 {
-
- // Start a transaction
- EntityTransaction et = em.getTransaction();
-
- if (!et.isActive()) {
- et.begin();
- }
-
- try {
- // query if ForwardProgress entry exists for 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("Updating FP entry: Resource={}, fpcCount={}, lastUpdated={}, new fpcCount={}",
- resourceName, fpx.getFpcCount(), fpx.getLastUpdated(), fpCounter);
- }
- fpx.setFpcCount(fpCounter);
- em.persist(fpx);
- // flush to the DB and commit
- synchronized (imFlushLock) {
- et.commit();
- }
- } else {
- // Error - FP entry does not exist
- String msg = "FP entry not found in database for resource " + resourceName;
- throw new IntegrityMonitorException(msg);
- }
- } catch (Exception e) {
- try {
- synchronized (imFlushLock) {
- if (et.isActive()) {
- et.rollback();
- }
- }
- } catch (Exception e1) {
- logger.error(EXCEPTION_STRING, e1);
- }
- logger.error("writeFpc DB table commit failed with exception");
- throw e;
- }
- }
-
- /**
- * Read and validate properties.
- *
- * @throws IntegrityMonitorPropertiesException if a property is invalid
- */
- private static void validateProperties(Properties prop) throws IntegrityMonitorPropertiesException {
-
- checkNonNull(prop, IntegrityMonitorProperties.DB_DRIVER);
- checkNonNull(prop, IntegrityMonitorProperties.DB_URL);
- checkNonNull(prop, IntegrityMonitorProperties.DB_USER);
- checkNonNull(prop, IntegrityMonitorProperties.DB_PWD);
-
- setLong(prop, IntegrityMonitorProperties.FP_MONITOR_INTERVAL, value -> monitorIntervalMs = toMillis(value));
-
- setInt(prop, value -> failedCounterThreshold = value);
-
- setLong(prop, IntegrityMonitorProperties.TEST_TRANS_INTERVAL, value -> testTransIntervalMs = 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 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 = SEMICOLON_PAT.split(depGroupsValue);
- if (logger.isDebugEnabled()) {
- logger.debug("dependency groups property = {}", Arrays.toString(depGroups));
- }
- }
-
- siteName = checkNonNull(prop, IntegrityMonitorProperties.SITE_NAME);
-
- nodeType = checkNonNull(prop, IntegrityMonitorProperties.NODE_TYPE);
- if (!isNodeTypeEnum(nodeType)) {
- String msg = IntegrityMonitorProperties.NODE_TYPE + " property " + nodeType + " is invalid";
- logger.error("{}", msg);
- throw new IntegrityMonitorPropertiesException(PROPERTY_EXCEPTION_STRING + msg);
- }
-
- setBoolean(prop, IntegrityMonitorProperties.TEST_VIA_JMX, value -> testViaJmx = value);
-
- String jmxFqdnValue = prop.getProperty(IntegrityMonitorProperties.JMX_FQDN);
- jmxFqdn = StringUtils.isBlank(jmxFqdnValue) ? null : jmxFqdnValue.trim();
-
- setLong(prop, IntegrityMonitorProperties.MAX_FPC_UPDATE_INTERVAL,
- value -> maxFpcUpdateIntervalMs = toMillis(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);
- }
-
- private static void setBoolean(Properties props, String propName, Consumer<Boolean> setter) {
- String propValue = props.getProperty(propName);
- if (propValue != null) {
- setter.accept(Boolean.parseBoolean(propValue.trim()));
- }
- }
-
- private static String checkNonNull(Properties props, String propName) throws IntegrityMonitorPropertiesException {
-
- String propValue = props.getProperty(propName);
- if (propValue == null) {
- String msg = propName + NULL_PROPERTY_STRING;
- logger.error("{}", msg);
- throw new IntegrityMonitorPropertiesException(PROPERTY_EXCEPTION_STRING + msg);
- }
-
- return propValue.trim();
- }
-
- private static void setInt(Properties props, IntConsumer setter) {
- String propValue = props.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD);
- if (StringUtils.isBlank(propValue)) {
- return;
- }
-
- try {
- setter.accept(Integer.parseInt(propValue.trim()));
- } catch (NumberFormatException e) {
- logger.warn(IGNORE_INVALID_PROPERTY_STRING, IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD, e);
- }
- }
-
- private static void setLong(Properties props, String propName, LongConsumer setter) {
- String propValue = props.getProperty(propName);
- if (StringUtils.isBlank(propValue)) {
- return;
- }
-
- try {
- setter.accept(Long.parseLong(propValue.trim()));
- } catch (NumberFormatException e) {
- logger.warn(IGNORE_INVALID_PROPERTY_STRING, propName, e);
- }
- }
-
- /**
- * Update properties.
- *
- * @param newprop the new properties
- */
- public static void updateProperties(Properties newprop) {
- if (isUnitTesting()) {
- try {
- validateProperties(newprop);
- } catch (IntegrityMonitorPropertiesException e) {
- logger.error(EXCEPTION_STRING, e);
- }
- } else {
- logger.debug("Update integrity monitor properties not allowed");
- }
- }
-
- private static boolean isNodeTypeEnum(String nodeType) {
- String upper = nodeType.toUpperCase();
- for (NodeType n : NodeType.values()) {
- if (n.toString().equals(upper)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Look for "Forward Progress" -- if the 'FPMonitor' is stalled for too long, the operational state is changed to
- * 'Disabled', and an alarm is set. The state is restored when forward progress continues.
- */
- private void fpMonitorCycle() {
- logger.debug("fpMonitorCycle(): entry");
- synchronized (fpMonitorCycleLock) {
- // monitoring interval checks
- if (monitorIntervalMs <= 0) {
- logger.debug("fpMonitorCycle(): disabled");
- elapsedTime = 0;
- return; // monitoring is disabled
- }
-
- elapsedTime = elapsedTime + CYCLE_INTERVAL_MILLIS;
- if (elapsedTime < monitorIntervalMs) {
- return; // monitoring interval not reached
- }
-
- elapsedTime = 0; // reset elapsed time
-
- try {
- if (fpCounter == lastFpCounter) {
- // no forward progress
- noForwardProgress();
- } else {
- // forward progress has occurred
- forwardProgress();
- }
- } catch (Exception e) {
- // log error
- logger.error("FP Monitor encountered error. ", e);
- }
- }
- logger.debug("fpMonitorCycle(): exit");
- }
-
- private void noForwardProgress() throws StateManagementException {
- missedCycles += 1;
- if (missedCycles >= failedCounterThreshold && !alarmExists) {
- logger.debug("Forward progress not detected for resource {}. Setting state to disable failed.",
- resourceName);
- if (!(stateManager.getOpState()).equals(StateManagement.DISABLED)) {
- // Note: The refreshStateAudit will make redundant
- // calls
- stateManager.disableFailed();
- }
- // The refreshStateAudit will catch the case where opStat = disabled and
- // availState ! failed/dependency.failed
- alarmExists = true;
- }
- }
-
- private void forwardProgress() throws StateManagementException {
- lastFpCounter = fpCounter;
- missedCycles = 0;
- // set op state to enabled
- 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();
- }
- // The refreshStateAudit will catch the case where opState=enabled and
- // availStatus != null
- alarmExists = false;
- }
-
- /**
- * Look for "Forward Progress" on other nodes. If they are not making forward progress, check their operational
- * state. If it is not disabled, then disable them.
- */
- private void stateAudit() {
- logger.debug("IntegrityMonitor.stateAudit(): entry");
- if (stateAuditIntervalMs <= 0) {
- logger.debug("IntegrityMonitor.stateAudit(): disabled");
- return; // stateAudit is disabled
- }
-
- // Only run from nodes that are operational
- if (stateManager.getOpState().equals(StateManagement.DISABLED)) {
- logger.debug("IntegrityMonitor.stateAudit(): DISABLED. returning");
- return;
- }
- if (stateManager.getAdminState().equals(StateManagement.LOCKED)) {
- logger.debug("IntegrityMonitor.stateAudit(): LOCKED. returning");
- return;
- }
- if (!stateManager.getStandbyStatus().equals(StateManagement.NULL_VALUE)
- && stateManager.getStandbyStatus() != null
- && !stateManager.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)) {
- logger.debug("IntegrityMonitor.stateAudit(): NOT PROVIDING_SERVICE. returning");
- return;
- }
-
- var date = MonitorTime.getInstance().getDate();
- long timeSinceLastStateAudit = date.getTime() - lastStateAuditTime.getTime();
- if (timeSinceLastStateAudit < stateAuditIntervalMs) {
- logger.debug("IntegrityMonitor.stateAudit(): Not time to run. returning");
- return;
- }
-
- executeStateAudit();
-
- lastStateAuditTime = date;
-
- logger.debug("IntegrityMonitor.stateAudit(): exit");
- }
-
- /**
- * Execute state audit.
- */
- public void executeStateAudit() {
- logger.debug("IntegrityMonitor.executeStateAudit(): entry");
- 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 this is my ForwardProgressEntity, continue
- if (fpe.getResourceName().equals(IntegrityMonitor.resourceName)) {
- continue;
- }
- // Make sure you are not getting a cached version
- em.refresh(fpe);
- long diffMs = date.getTime() - fpe.getLastUpdated().getTime();
- if (logger.isDebugEnabled()) {
- logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, diffMs = {}", fpe.getResourceName(),
- diffMs);
- }
-
- // Threshold for a stale entry
- long staleMs = maxFpcUpdateIntervalMs;
- if (logger.isDebugEnabled()) {
- logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, staleMs = {}", fpe.getResourceName(),
- staleMs);
- }
-
- if (diffMs > staleMs) {
- // ForwardProgress is stale. Disable it
- // Start a transaction
- logger.debug("IntegrityMonitor.executeStateAudit(): resource = {}, FPC is stale. Disabling it",
- fpe.getResourceName());
- EntityTransaction et = em.getTransaction();
- et.begin();
- StateManagementEntity sme = disableEntity(et, fpe);
-
- if (sme != null && !sme.getOpState().equals(StateManagement.DISABLED)) {
- disableFailed(sme);
- }
- }
- }
- logger.debug("IntegrityMonitor.executeStateAudit(): exit");
- }
-
- /**
- * Disables the entity.
- *
- * @param entrans entity transaction
- * @param fpe entity of interest
- * @return the corresponding state management entity
- */
- private StateManagementEntity disableEntity(EntityTransaction entrans, ForwardProgressEntity fpe) {
- StateManagementEntity sme = null;
-
- try {
- // query if StateManagement entry exists for fpe resource
- TypedQuery<StateManagementEntity> query =
- em.createQuery("Select p from StateManagementEntity p where p.resourceName=:resource",
- StateManagementEntity.class);
- query.setParameter(LC_RESOURCE_STRING, fpe.getResourceName());
-
- List<StateManagementEntity> smList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!smList.isEmpty()) {
- // exists
- 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());
- }
- } else {
- String msg = "IntegrityMonitor.executeStateAudit(): " + fpe.getResourceName()
- + ": resource not found in state management entity database table";
- logger.error("{}", msg);
- }
- synchronized (imFlushLock) {
- entrans.commit();
- }
- } catch (Exception e) {
- // log an error
- logger.error("IntegrityMonitor.executeStateAudit(): {}: StateManagementEntity DB read failed with "
- + "exception: ", fpe.getResourceName(), e);
- synchronized (imFlushLock) {
- if (entrans.isActive()) {
- entrans.rollback();
- }
- }
- }
-
- return sme;
- }
-
- private void disableEntity(String dep, StateManagementEntity sme) {
- try {
- if (!sme.getOpState().equals(StateManagement.DISABLED)) {
- logger.debug("IntegrityMonitor.stateCheck(): Changing OpStat = disabled for {}", dep);
- stateManager.disableFailed(dep);
- }
- } catch (Exception e) {
- String msg = STATE_CHECK_STRING + dep + "; " + e.getMessage();
- logger.error("{}", msg, e);
- }
- }
-
- private void disableEntity(String dep) {
- try {
- // 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);
- depStateManager.disableFailed();
- }
- } catch (Exception e) {
- // ignore errors
- logger.error("Update dependent state failed with exception: ", e);
- }
- }
-
- /**
- * 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());
- }
- try {
- stateManager.disableFailed(sme.getResourceName());
- } catch (Exception e) {
- String msg = "IntegrityMonitor.executeStateAudit(): Failed to disable " + sme.getResourceName();
- logger.error("{}", msg, e);
- }
- }
-
- /**
- * Execute a test transaction when test transaction interval has elapsed.
- */
- private void checkTestTransaction() {
- logger.debug("checkTestTransaction(): entry");
- synchronized (checkTestTransactionLock) {
-
- // test transaction timer checks
- if (testTransIntervalMs <= 0) {
- logger.debug("checkTestTransaction(): disabled");
- elapsedTestTransTime = 0;
- return; // test transaction is disabled
- }
-
- elapsedTestTransTime = elapsedTestTransTime + CYCLE_INTERVAL_MILLIS;
- if (elapsedTestTransTime < testTransIntervalMs) {
- return; // test transaction interval not reached
- }
-
- elapsedTestTransTime = 0; // reset elapsed time
-
- // execute test transaction
- testTransaction();
- }
- logger.debug("checkTestTransaction(): exit");
- }
-
- /**
- * Updates Fpc counter in database when write Fpc interval has elapsed.
- */
- private void checkWriteFpc() {
- logger.debug("checkWriteFpc(): entry");
- synchronized (checkWriteFpcLock) {
-
- // test transaction timer checks
- if (writeFpcIntervalMs <= 0) {
- logger.debug("checkWriteFpc(): disabled");
- elapsedWriteFpcTime = 0;
- return; // write Fpc is disabled
- }
-
- elapsedWriteFpcTime = elapsedWriteFpcTime + CYCLE_INTERVAL_MILLIS;
- if (elapsedWriteFpcTime < writeFpcIntervalMs) {
- return; // write Fpc interval not reached
- }
-
- elapsedWriteFpcTime = 0; // reset elapsed time
-
- // write Fpc to database
- try {
- writeFpc();
- } catch (Exception e) {
- logger.error(EXCEPTION_STRING, e);
- }
- }
- logger.debug("checkWriteFpc(): exit");
- }
-
- /**
- * Execute a dependency health check periodically which also updates this resource's state.
- */
- private void checkDependentHealth() {
- logger.debug("checkDependentHealth: entry");
- if (checkDependencyIntervalMs <= 0) {
- logger.debug("checkDependentHealth: disabled");
- return; // dependency monitoring is disabled
- }
-
- long currTime = MonitorTime.getInstance().getMillis();
- logger.debug("checkDependentHealth currTime - lastDependencyCheckTime = {}",
- currTime - lastDependencyCheckTime);
- if ((currTime - lastDependencyCheckTime) > checkDependencyIntervalMs) {
- // execute dependency check and update this resource's state
-
- dependencyCheck();
- }
- logger.debug("checkDependentHealth: exit");
- }
-
- /*
- * 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.
- */
- private void refreshStateAudit() {
- logger.debug("refreshStateAudit(): entry");
- if (refreshStateAuditIntervalMs <= 0) {
- // The audit is disabled
- logger.debug("refreshStateAudit(): disabled");
- return;
- }
- executeRefreshStateAudit();
- logger.debug("refreshStateAudit(): exit");
- }
-
- /**
- * Execute refresh state audit.
- */
- public void executeRefreshStateAudit() {
- logger.debug("executeRefreshStateAudit(): entry");
- synchronized (refreshStateAuditLock) {
- logger.debug("refreshStateAudit: entry");
- var now = MonitorTime.getInstance().getDate();
- long nowMs = now.getTime();
- long lastTimeMs = refreshStateAuditLastRunDate.getTime();
- logger.debug("refreshStateAudit: ms since last run = {}", nowMs - lastTimeMs);
-
- if ((nowMs - lastTimeMs) > refreshStateAuditIntervalMs) {
- String adminState = stateManager.getAdminState();
- logger.debug("refreshStateAudit: adminState = {}", adminState);
- if (adminState.equals(StateManagement.LOCKED)) {
- try {
- logger.debug("refreshStateAudit: calling lock()");
- stateManager.lock();
- } catch (Exception e) {
- logger.error("refreshStateAudit: caught unexpected exception from stateManager.lock(): ", e);
- }
- } else { // unlocked
- try {
- logger.debug("refreshStateAudit: calling unlock()");
- stateManager.unlock();
- } catch (Exception e) {
- logger.error("refreshStateAudit: caught unexpected exception from stateManager.unlock(): ", e);
- }
- }
- refreshStateAuditLastRunDate = MonitorTime.getInstance().getDate();
- logger.debug("refreshStateAudit: exit");
- }
- }
- logger.debug("executeRefreshStateAudit(): exit");
- }
-
- private void runFpManager() {
- logger.debug("FPManager thread running");
-
- try {
- runStarted();
-
- while (fpManager != null) {
- MonitorTime.getInstance().sleep(CYCLE_INTERVAL_MILLIS);
-
- runOnce();
- monitorCompleted();
- }
-
- } catch (InterruptedException e) {
- logger.debug(EXCEPTION_STRING, e);
- Thread.currentThread().interrupt();
- }
- }
-
- private void runOnce() {
- try {
- logger.debug("FPManager calling fpMonitorCycle()");
- // check forward progress timer
- fpMonitorCycle();
-
- logger.debug("FPManager calling checkTestTransaction()");
- // check test transaction timer
- checkTestTransaction();
-
- logger.debug("FPManager calling checkWriteFpc()");
- // check write Fpc timer
- checkWriteFpc();
-
- logger.debug("FPManager calling checkDependentHealth()");
- // check dependency health
- checkDependentHealth();
-
- logger.debug("FPManager calling refreshStateAudit()");
- // check if it is time to run the refreshStateAudit
- refreshStateAudit();
-
- logger.debug("FPManager calling stateAudit()");
- // check if it is time to run the stateAudit
- stateAudit();
-
- } catch (Exception e) {
- logger.error("Ignore FPManager thread processing timer(s) exception: ", e);
- }
- }
-
- /**
- * Set all seems well or not well for the specified key.
- *
- * @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
- */
- public void allSeemsWell(String key, Boolean asw, String msg) {
-
- logger.debug("allSeemsWell entry: key = {}, asw = {}, msg = {}", key, asw, msg);
- if (StringUtils.isEmpty(key)) {
- logger.error("allSeemsWell: 'key' has no visible content");
- throw new IllegalArgumentException("allSeemsWell: 'key' has no visible content");
- }
- if (asw == null) {
- logger.error("allSeemsWell: 'asw' is null");
- throw new IllegalArgumentException("allSeemsWell: 'asw' is null");
- }
- if (StringUtils.isEmpty(msg)) {
- logger.error("allSeemsWell: 'msg' has no visible content");
- throw new IllegalArgumentException("allSeemsWell: 'msg' has no visible content");
- }
-
- if (allSeemsWellMap == null) {
- allSeemsWellMap = new HashMap<>();
- }
-
- if (allNotWellMap == null) {
- allNotWellMap = new HashMap<>();
- }
-
- if (Boolean.TRUE.equals(asw)) {
- logger.info("allSeemsWell: ALL SEEMS WELL: key = {}, msg = {}", key, msg);
- allSeemsWellMap.put(key, msg);
- allNotWellMap.remove(key);
-
- } else {
- logger.error("allSeemsWell: ALL NOT WELL: key = {}, msg = {}", key, msg);
- allSeemsWellMap.remove(key);
- allNotWellMap.put(key, msg);
- }
-
- if (logger.isDebugEnabled()) {
- for (Entry<String, String> entry : allSeemsWellMap.entrySet()) {
- logger.debug("allSeemsWellMap: key = {} msg = {}", entry.getKey(), entry.getValue());
- }
- for (Entry<String, String> entry : allNotWellMap.entrySet()) {
- logger.debug("allNotWellMap: key = {} msg = {}", entry.getKey(), entry.getValue());
- }
- logger.debug("allSeemsWell exit");
- }
- }
-
- /**
- * 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
- */
- private static long toMillis(long value) {
- return (value < 0 ? -1 : value * 1000L);
- }
-
- // these methods may be overridden by junit tests
-
- /**
- * Indicates that the {FpManager#run()} method has started. This method simply returns.
- *
- * @throws InterruptedException can be interrupted
- */
- protected void runStarted() throws InterruptedException {
- // does nothing
- }
-
- /**
- * Indicates that a monitor activity has completed. This method simply returns.
- *
- * @throws InterruptedException can be interrupted
- */
- protected void monitorCompleted() throws InterruptedException {
- // does nothing
- }
-
- /**
- * Get persistence unit.
- *
- * @return the persistence unit to be used
- */
- protected String getPersistenceUnit() {
- return PERSISTENCE_UNIT;
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java
deleted file mode 100644
index 6e1d0c00..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorException.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class IntegrityMonitorException extends Exception {
- private static final long serialVersionUID = 1L;
-
- public IntegrityMonitorException() {
- super();
- }
-
- public IntegrityMonitorException(String message) {
- super(message);
- }
-
- public IntegrityMonitorException(Throwable cause) {
- super(cause);
- }
-
- public IntegrityMonitorException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public IntegrityMonitorException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java
deleted file mode 100644
index 6af7a557..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorProperties.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-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.
- * 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.im;
-
-import lombok.AccessLevel;
-import lombok.NoArgsConstructor;
-
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public final class IntegrityMonitorProperties {
-
- public static final String DB_DRIVER = "jakarta.persistence.jdbc.driver";
- public static final String DB_URL = "jakarta.persistence.jdbc.url";
- public static final String DB_USER = "jakarta.persistence.jdbc.user";
- public static final String DB_PWD = "jakarta.persistence.jdbc.password"; //NOSONAR
-
- // intervals specified are in seconds
- public static final int DEFAULT_MONITOR_INTERVAL = 30;
- public static final int DEFAULT_FAILED_COUNTER_THRESHOLD = 3;
- public static final int DEFAULT_TEST_INTERVAL = 10;
- public static final int DEFAULT_WRITE_FPC_INTERVAL = 5;
- public static final int DEFAULT_MAX_FPC_UPDATE_INTERVAL = 120;
- public static final int DEFAULT_CHECK_DEPENDENCY_INTERVAL = 10;
-
- public static final String FP_MONITOR_INTERVAL = "fp_monitor_interval";
- public static final String FAILED_COUNTER_THRESHOLD = "failed_counter_threshold";
- public static final String TEST_TRANS_INTERVAL = "test_trans_interval";
- public static final String WRITE_FPC_INTERVAL = "write_fpc_interval";
- public static final String CHECK_DEPENDENCY_INTERVAL = "check_dependency_interval";
-
- public static final String DEPENDENCY_GROUPS = "dependency_groups";
- public static final String SITE_NAME = "site_name";
- public static final String NODE_TYPE = "node_type";
-
- public static final String TEST_VIA_JMX = "test_via_jmx";
- public static final String JMX_FQDN = "jmx_fqdn";
- public static final String MAX_FPC_UPDATE_INTERVAL = "max_fpc_update_interval";
- public static final String STATE_AUDIT_INTERVAL_MS = "state_audit_interval_ms";
- public static final String REFRESH_STATE_AUDIT_INTERVAL_MS = "refresh_state_audit_interval_ms";
-
- // AllSeemsWell types
- public static final Boolean ALLNOTWELL = Boolean.FALSE;
- public static final Boolean ALLSEEMSWELL = Boolean.TRUE;
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java
deleted file mode 100644
index d3533f10..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/IntegrityMonitorPropertiesException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class IntegrityMonitorPropertiesException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public IntegrityMonitorPropertiesException() {
- super();
- }
-
- public IntegrityMonitorPropertiesException(String message) {
- super(message);
- }
-
- public IntegrityMonitorPropertiesException(Throwable cause) {
- super(cause);
- }
-
- public IntegrityMonitorPropertiesException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java
deleted file mode 100644
index 61afb682..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/MonitorTime.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018, 2021 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.im;
-
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import org.onap.policy.common.utils.time.CurrentTime;
-
-/**
- * "Current" time used by IntegrityMonitor classes.
- */
-@NoArgsConstructor(access = AccessLevel.PRIVATE)
-public class MonitorTime {
-
- /**
- * Instance to be used. This is overridden by junit tests.
- */
- @Getter
- private static CurrentTime instance = new CurrentTime();
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java
deleted file mode 100644
index 352df386..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StandbyStatusException.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class StandbyStatusException extends IntegrityMonitorException {
-
- private static final long serialVersionUID = -5262512285108747134L;
-
- public StandbyStatusException() {
- super();
- }
-
- public StandbyStatusException(String message) {
- super(message);
- }
-
- public StandbyStatusException(Throwable cause) {
- super(cause);
- }
-
- public StandbyStatusException(String message, Throwable cause) {
- super(message, cause);
- }
-
- public StandbyStatusException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java
deleted file mode 100644
index 5fc111e0..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateChangeNotifier.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017, 2020-2021 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.im;
-
-import lombok.Getter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-/*
- * This is implementing the Observer interface to make it specific for
- * state management.
- *
- * It saves the StateManagement object and a String message that is
- * passed in when notifyObservers is called by the Observable
- * host class.
- *
- * It provides an abstract method for handling the state change
- * so this class must be overwritten and made concrete for the
- * Observer who is monitoring the state changes.
- */
-
-
-
-/**
- * StateChangeNotifier class implements the Observer pattern and is used to distribute state change
- * notifications to any entity that registers a derived class with an instance of the
- * StateManagement class.
- *
- */
-@Getter
-public class StateChangeNotifier {
- private static final Logger logger = LoggerFactory.getLogger(StateChangeNotifier.class);
- // The observable class
- StateManagement stateManagement;
-
- // A string argument passed by the observable class when
- // StateManagement:notifyObservers(String changed) is called
- String message;
-
- /**
- * Invoked to indicate that something observed by this notifier has changed.
- * @param observable item that has changed
- * @param changed message indicating what change was made
- */
- public void update(StateManagement observable, String changed) {
- this.stateManagement = observable;
- this.message = changed;
- handleStateChange();
- }
-
- /**
- * Handle state change.
- */
- public void handleStateChange() {
- if (logger.isDebugEnabled()) {
- logger.debug("handleStateChange, message: {}", this.message);
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java
deleted file mode 100644
index d1bc9cc1..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateElement.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 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.im;
-
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Getter
-@Setter
-@NoArgsConstructor
-public class StateElement {
- private static final Logger logger = LoggerFactory.getLogger(StateElement.class);
-
- String adminState = null;
- String opState = null;
- String availStatus = null;
- String standbyStatus = null;
- String actionName = null;
- String endingAdminState = null;
- String endingOpState = null;
- String endingAvailStatus = null;
- String endingStandbyStatus = null;
- String exception = null;
-
- /**
- * Display the state element.
- */
- public void displayStateElement() {
- if (logger.isDebugEnabled()) {
- logger.debug(
- "adminState=[{}], opState=[{}], availStatus=[{}], standbyStatus=[{}], "
- + "actionName=[{}], endingAdminState=[{}], endingOpState=[{}], "
- + "endingAvailStatus=[{}], endingStandbyStatus=[{}], exception=[{}]",
- getAdminState(), getOpState(), getAvailStatus(), getStandbyStatus(), getActionName(),
- getEndingAdminState(), getEndingOpState(), getEndingAvailStatus(), getEndingStandbyStatus(),
- getException());
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java
deleted file mode 100644
index eace6037..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagement.java
+++ /dev/null
@@ -1,551 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.
- * 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.im;
-
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.EntityManagerFactory;
-import jakarta.persistence.FlushModeType;
-import jakarta.persistence.LockModeType;
-import jakarta.persistence.TypedQuery;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Consumer;
-import org.onap.policy.common.im.exceptions.EntityRetrievalException;
-import org.onap.policy.common.im.jpa.StateManagementEntity;
-import org.onap.policy.common.utils.jpa.EntityMgrCloser;
-import org.onap.policy.common.utils.jpa.EntityTransCloser;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * StateManagement class handles all state changes per the Telecom standard X.731. It extends the
- * Observable class and, thus, has an interface to register instances of the
- * StateChangeNotifier/Observer class. When any state change occurs, the registered observers are
- * notified.
- *
- */
-public class StateManagement {
- private static final String RESOURCE_NAME = "resource";
- private static final String GET_STATE_MANAGEMENT_ENTITY_QUERY =
- "Select p from StateManagementEntity p where p.resourceName=:" + RESOURCE_NAME;
- private static final String FIND_MESSAGE = "findStateManagementEntity for {}";
- private static final Logger logger = LoggerFactory.getLogger(StateManagement.class);
- public static final String LOCKED = "locked";
- public static final String UNLOCKED = "unlocked";
- public static final String ENABLED = "enabled";
- public static final String DISABLED = "disabled";
- public static final String ENABLE_NOT_FAILED_ACTION = "enableNotFailed";
- public static final String DISABLE_FAILED_ACTION = "disableFailed";
- public static final String FAILED = "failed";
- public static final String DEPENDENCY = "dependency";
- public static final String DEPENDENCY_FAILED = "dependency,failed";
- public static final String DISABLE_DEPENDENCY_ACTION = "disableDependency";
- public static final String ENABLE_NO_DEPENDENCY_ACTION = "enableNoDependency";
- public static final String NULL_VALUE = "null";
-
- public static final String LOCK_ACTION = "lock";
- public static final String UNLOCK_ACTION = "unlock";
- public static final String PROMOTE_ACTION = "promote";
- public static final String DEMOTE_ACTION = "demote";
- public static final String HOT_STANDBY = "hotstandby";
- public static final String COLD_STANDBY = "coldstandby";
- public static final String PROVIDING_SERVICE = "providingservice";
-
- public static final String ADMIN_STATE = "adminState";
- public static final String OPERATION_STATE = "opState";
- public static final String AVAILABLE_STATUS = "availStatus";
- public static final String STANDBY_STATUS = "standbyStatus";
-
- private String resourceName = null;
- private String adminState = null;
- private String opState = null;
- private String availStatus = null;
- private String standbyStatus = null;
- private final EntityManagerFactory emf;
- private StateTransition st = null;
-
- /*
- * Guarantees single-threadedness of all actions. Only one action can execute at a time. That
- * avoids race conditions between actions being called from different places.
- *
- * Some actions can take significant time to complete and, if another conflicting action is
- * called during its execution, it could put the system in an inconsistent state. This very
- * thing happened when demote was called and the active/standby algorithm, seeing the state
- * attempted to promote the PDP-D.
- *
- */
- private static final Object SYNCLOCK = new Object();
- private static final Object FLUSHLOCK = new Object();
-
- /**
- * Observers to be notified when this object changes state.
- */
- private final Collection<StateChangeNotifier> observers = new ConcurrentLinkedQueue<>();
-
- /**
- * StateManagement constructor.
- *
- * @param entityManagerFactory the entity manager factory
- * @param resourceName the resource name
- * @throws StateManagementException if an error occurs
- */
- public StateManagement(final EntityManagerFactory entityManagerFactory, final String resourceName)
- throws StateManagementException {
- emf = entityManagerFactory;
- logger.debug("StateManagement: constructor, resourceName: {}", resourceName);
-
- this.resourceName = resourceName;
-
- setState("StateManagement", this.resourceName, sm -> null);
-
- // Load the StateTransition hash table
- st = new StateTransition();
- }
-
- /**
- * initializeState() is called when it is necessary to set the StateManagement to a known
- * initial state. It preserves the Administrative State since it must persist across node
- * reboots. Starting from this state, the IntegrityMonitory will determine the Operational State
- * and the owning application will set the StandbyStatus.
- */
- public void initializeState() throws StateManagementException {
- setState("initializeState", this.resourceName, sm -> {
- sm.setAdminState(sm.getAdminState()); // preserve the Admin state
- sm.setOpState(StateManagement.ENABLED);
- sm.setAvailStatus(StateManagement.NULL_VALUE);
- sm.setStandbyStatus(StateManagement.NULL_VALUE);
- return ADMIN_STATE;
- });
- }
-
- /**
- * Sets the management entity state.
- *
- * @param methodName name of the method that invoked this
- * @param resourceName resource name of the desired entity
- * @param updateState function to update the state; returns a string indicating which item
- * was updated, {@code null} if no change was made
- * @throws StateManagementException if an error occurs
- */
- private void setState(String methodName, String resourceName, ExFunction<StateManagementEntity, String> updateState)
- throws StateManagementException {
-
- synchronized (SYNCLOCK) {
- logger.debug("\nStateManagement: SYNCLOCK {}() operation for resourceName = {}\n", methodName,
- resourceName);
- logger.debug("StateManagement: {}() operation started, resourceName = {}", methodName, resourceName);
-
- final var em = emf.createEntityManager();
-
- try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
-
- logger.debug(FIND_MESSAGE, resourceName);
-
- final var sm = findStateManagementEntity(em, resourceName);
- String changed = updateState.update(sm);
-
- em.persist(sm);
- et.commit();
-
- if (changed != null) {
- notifyObservers(changed);
- }
-
- logger.debug("StateManagement: {}() operation completed, resourceName = {}",
- methodName, resourceName);
- } catch (final Exception ex) {
- throw new StateManagementException("StateManagement." + methodName + "() Exception: " + ex);
- }
- }
- }
-
- /**
- * Adds an observer to list of those to be notified when this changes.
- * @param observer observer to be added
- */
- public void addObserver(StateChangeNotifier observer) {
- observers.add(observer);
- }
-
- private void notifyObservers(String changed) {
- for (StateChangeNotifier obs : observers) {
- obs.update(this, changed);
- }
- }
-
- private void setStateUsingTable(String actionName, String resourceName, String changeName)
- throws StateManagementException {
-
- setState(actionName, resourceName, sm -> {
- final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), actionName);
-
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- return changeName;
- });
- }
-
- /**
- * lock() changes the administrative state to locked.
- *
- * @throws StateManagementException if an error occurs
- */
- public void lock() throws StateManagementException {
- setStateUsingTable(LOCK_ACTION, this.resourceName, ADMIN_STATE);
- }
-
- /**
- * unlock() changes the administrative state to unlocked.
- *
- * @throws StateManagementException if an error occurs
- */
- public void unlock() throws StateManagementException {
- setStateUsingTable(UNLOCK_ACTION, this.resourceName, ADMIN_STATE);
- }
-
- /**
- * enableNotFailed() removes the "failed" availability status and changes the operational state
- * to enabled if no dependency is also failed.
- *
- * @throws StateManagementException if an error occurs
- */
- public void enableNotFailed() throws StateManagementException {
- setStateUsingTable(ENABLE_NOT_FAILED_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * disableFailed() changes the operational state to disabled and adds availability status of
- * "failed".
- *
- * @throws StateManagementException if an error occurs
- */
- public void disableFailed() throws StateManagementException {
- setStateUsingTable(DISABLE_FAILED_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * This version of disableFailed is to be used to manipulate the state of a remote resource in
- * the event that remote resource has failed but its state is still showing that it is viable.
- *
- * @throws StateManagementException if an error occurs
- */
- public void disableFailed(final String otherResourceName) throws StateManagementException {
- if (otherResourceName == null) {
- logger.error(
- "\nStateManagement: SYNCLOCK disableFailed(otherResourceName) operation: resourceName is NULL.\n");
- return;
- }
-
- setStateUsingTable(DISABLE_FAILED_ACTION, otherResourceName, OPERATION_STATE);
- }
-
- /**
- * disableDependency() changes operational state to disabled and adds availability status of
- * "dependency".
- *
- * @throws StateManagementException if an error occurs
- */
- public void disableDependency() throws StateManagementException {
- setStateUsingTable(DISABLE_DEPENDENCY_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * enableNoDependency() removes the availability status of "dependency " and will change the
- * operational state to enabled if not otherwise failed.
- *
- * @throws StateManagementException if an error occurs
- */
- public void enableNoDependency() throws StateManagementException {
- setStateUsingTable(ENABLE_NO_DEPENDENCY_ACTION, this.resourceName, OPERATION_STATE);
- }
-
- /**
- * promote() changes the standby status to providingservice if not otherwise failed.
- *
- * @throws IntegrityMonitorException if the status fails to change
- */
- public void promote() throws IntegrityMonitorException {
- AtomicReference<String> newStatus = new AtomicReference<>();
-
- setState(PROMOTE_ACTION, resourceName, sm -> {
- final var stateElement = st.getEndingState(sm.getAdminState(), sm.getOpState(),
- sm.getAvailStatus(), sm.getStandbyStatus(), PROMOTE_ACTION);
-
- sm.setAdminState(stateElement.getEndingAdminState());
- sm.setOpState(stateElement.getEndingOpState());
- sm.setAvailStatus(stateElement.getEndingAvailStatus());
- sm.setStandbyStatus(stateElement.getEndingStandbyStatus());
-
- newStatus.set(sm.getStandbyStatus());
-
- return STANDBY_STATUS;
- });
-
- if (StateManagement.COLD_STANDBY.equals(newStatus.get())) {
- final String msg =
- "Failure to promote " + this.resourceName + " StandbyStatus = " + StateManagement.COLD_STANDBY;
- throw new StandbyStatusException(msg);
- }
- }
-
- /**
- * demote() changes standbystatus to hotstandby or, if failed, coldstandby.
- *
- * @throws StateManagementException if an error occurs
- */
- public void demote() throws StateManagementException {
- setStateUsingTable(DEMOTE_ACTION, this.resourceName, STANDBY_STATUS);
- }
-
- /**
- * Only used for a remote resource. It will not notify observers. It is used only in cases where
- * the remote resource has failed is such a way that it cannot update its own states. In
- * particular this is observed by PDP-D DroolsPdpsElectionHandler when it is trying to determine
- * which PDP-D should be designated as the lead.
- *
- * @param otherResourceName the resouce name
- * @throws StateManagementException if an error occurs
- */
- public void demote(final String otherResourceName) throws StateManagementException {
- if (otherResourceName == null) {
- logger.error(
- "\nStateManagement: SYNCLOCK demote(otherResourceName) operation: resourceName is NULL.\n");
- return;
- }
-
- setStateUsingTable(DEMOTE_ACTION, otherResourceName, null);
- }
-
- /**
- * Get the administration state.
- *
- * @return the administration state
- */
- public String getAdminState() {
- getEntityState("getAdminState", this.resourceName,
- sm -> this.adminState = sm.getAdminState(),
- () -> this.adminState = null);
- return this.adminState;
- }
-
- private void getEntityState(String methodName, String resourceName, Consumer<StateManagementEntity> function,
- Runnable notFound) {
-
- logger.debug("StateManagement(6/1/16): {} for resourceName {}", methodName, resourceName);
-
- final var em = emf.createEntityManager();
- try (final var emc = new EntityMgrCloser(em)) {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, this.resourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final var stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- function.accept(stateManagementEntity);
- } else {
- notFound.run();
- }
- } catch (final Exception ex) {
- logger.error("StateManagement: {} exception: {}", methodName, ex.getMessage(), ex);
- }
-
- }
-
- /**
- * Get the operational state.
- *
- * @return the operational state
- */
- public String getOpState() {
- getEntityState("getOpState", this.resourceName,
- sm -> this.opState = sm.getOpState(),
- () -> this.opState = null);
- return this.opState;
- }
-
- /**
- * Get the availability status.
- *
- * @return the availability status
- */
- public String getAvailStatus() {
- getEntityState("getAvailStatus", this.resourceName,
- sm -> this.availStatus = sm.getAvailStatus(),
- () -> this.availStatus = null);
- return this.availStatus;
- }
-
- /**
- * Get the standy status.
- *
- * @return the standby status
- */
- public String getStandbyStatus() {
- getEntityState("getStandbyStatus", this.resourceName,
- sm -> this.standbyStatus = sm.getStandbyStatus(),
- () -> this.standbyStatus = null);
- return this.standbyStatus;
- }
-
- /**
- * Get the standbystatus of a particular resource.
- *
- * @param otherResourceName the resource
- * @return the standby status
- */
- public String getStandbyStatus(final String otherResourceName) {
- AtomicReference<String> tempStandbyStatus = new AtomicReference<>();
-
- getEntityState("getStandbyStatus", otherResourceName,
- sm -> tempStandbyStatus.set(sm.getStandbyStatus()),
- () -> logger.error("getStandbyStatus: resourceName ={} not found in statemanagemententity table",
- otherResourceName));
-
- logger.debug("getStandbyStatus: Returning standbyStatus={}", tempStandbyStatus.get());
-
- return tempStandbyStatus.get();
- }
-
- /**
- * Find a StateManagementEntity.
- *
- * @param em the entity manager
- * @param otherResourceName the resource name
- * @return the StateManagementEntity
- */
- private static StateManagementEntity findStateManagementEntity(final EntityManager em,
- final String otherResourceName) {
- logger.debug("StateManagementEntity: findStateManagementEntity: Entry");
- try {
- final TypedQuery<StateManagementEntity> query =
- em.createQuery(GET_STATE_MANAGEMENT_ENTITY_QUERY, StateManagementEntity.class);
-
- query.setParameter(RESOURCE_NAME, otherResourceName);
-
- // Just test that we are retrieving the right object
- final List<StateManagementEntity> resourceList =
- query.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- if (!resourceList.isEmpty()) {
- // exist
- final var stateManagementEntity = resourceList.get(0);
- // refresh the object from DB in case cached data was returned
- em.refresh(stateManagementEntity);
- stateManagementEntity.setModifiedDate(MonitorTime.getInstance().getDate());
- return stateManagementEntity;
- } else {
- // not exist - create one
- final var stateManagementEntity = new StateManagementEntity();
- stateManagementEntity.setResourceName(otherResourceName);
- stateManagementEntity.setAdminState(UNLOCKED);
- stateManagementEntity.setOpState(ENABLED);
- stateManagementEntity.setAvailStatus(NULL_VALUE);
- stateManagementEntity.setStandbyStatus(NULL_VALUE); // default
- return stateManagementEntity;
- }
- } catch (final Exception ex) {
- throw new EntityRetrievalException("findStateManagementEntity exception", ex);
- }
- }
-
- /**
- * Clean up all the StateManagementEntities.
- */
- public void deleteAllStateManagementEntities() {
-
- logger.debug("StateManagement: deleteAllStateManagementEntities: Entering");
-
- /*
- * Start transaction
- */
- final var em = emf.createEntityManager();
-
- try (var emc = new EntityMgrCloser(em); MyTransaction et = new MyTransaction(em)) {
- final TypedQuery<StateManagementEntity> stateManagementEntityListQuery =
- em.createQuery("SELECT p FROM StateManagementEntity p", StateManagementEntity.class);
- final List<StateManagementEntity> stateManagementEntityList = stateManagementEntityListQuery
- .setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
- logger.debug("deleteAllStateManagementEntities: Deleting {} StateManagementEntity records",
- stateManagementEntityList.size());
- for (final StateManagementEntity stateManagementEntity : stateManagementEntityList) {
- logger.debug("deleteAllStateManagementEntities: Deleting statemanagemententity with resourceName={} and"
- + " standbyStatus={}", stateManagementEntity.getResourceName(),
- stateManagementEntity.getStandbyStatus());
- em.remove(stateManagementEntity);
- }
-
- et.commit();
- } catch (final Exception ex) {
- logger.error("StateManagement.deleteAllStateManagementEntities() caught Exception: ", ex);
- }
- logger.debug("deleteAllStateManagementEntities: Exiting");
- }
-
- @FunctionalInterface
- private static interface ExFunction<T, R> {
- public R update(T object) throws IntegrityMonitorException;
- }
-
- private static class MyTransaction extends EntityTransCloser {
-
- /**
- * Create an instance.
- *
- * @param em the entity manager
- */
- public MyTransaction(final EntityManager em) {
- super(em.getTransaction());
- }
-
- @Override
- public void commit() {
- synchronized (FLUSHLOCK) {
- if (getTransaction().isActive()) {
- super.commit();
- }
- }
- }
-
- @Override
- public void rollback() {
- synchronized (FLUSHLOCK) {
- if (getTransaction().isActive()) {
- super.rollback();
- }
- }
- }
-
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java
deleted file mode 100644
index 05597a2a..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateManagementException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class StateManagementException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public StateManagementException() {
- super();
- }
-
- public StateManagementException(final String message) {
- super(message);
- }
-
- public StateManagementException(final Throwable cause) {
- super(cause);
- }
-
- public StateManagementException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java
deleted file mode 100644
index 2ebef874..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransition.java
+++ /dev/null
@@ -1,401 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2019, 2021 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.im;
-
-import com.google.re2j.Pattern;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import org.apache.commons.lang3.tuple.Pair;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * The StateTransition class coordinates all state transitions.
- */
-public class StateTransition {
- private static final Pattern COMMA_PAT = Pattern.compile(",");
-
- private static final String DEPENDENCY_FAILED = "dependency.failed";
-
- private static final String ANY_DISABLED_ANY_COLDSTANDBY = "${1},disabled,${3},coldstandby,";
- private static final String ANY_DISABLED_ANY_COLDSTANDBY_STANDBY_STATUS_EXCEPTION =
- "${1},disabled,${3},coldstandby,StandbyStatusException";
- private static final String LOCKED_ENABLED_NULL_COLDSTANDBY_STANDBY_STATUS_EXCEPTION =
- "locked,enabled,null,coldstandby,StandbyStatusException";
- private static final String UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE = "unlocked,enabled,null,providingservice,";
- private static final String UNLOCKED_DISABLED_DEPENDENCY_HOTSTANDBY = "unlocked,disabled,dependency,hotstandby,";
- private static final String ANY_DISABLED_DEPENDENCY_NULL = "${1},disabled,dependency,null,";
- private static final String ANY_DISABLED_DEPENDENCY_COLDSTANDBY = "${1},disabled,dependency,coldstandby,";
- private static final String ANY_DISABLED_DEPENDENCY_FAILED_NULL = "${1},disabled,dependency.failed,null,";
- private static final String ANY_DISABLED_DEPENDENCY_FAILED_COLDSTANDBY =
- "${1},disabled,dependency.failed,coldstandby,";
- private static final String ANY_DISABLED_FAILED_NULL = "${1},disabled,failed,null,";
- private static final String ANY_DISABLED_FAILED_COLDSTANDBY = "${1},disabled,failed,coldstandby,";
- private static final String UNLOCKED_DISABLED_ANY_NULL = "unlocked,disabled,${3},null,";
- private static final String UNLOCKED_DISABLED_ANY_COLDSTANDBY = "unlocked,disabled,${3},coldstandby,";
- private static final String UNLOCKED_ENABLED_NULL_NULL = "unlocked,enabled,null,null,";
- private static final String LOCKED_DISABLED_ANY_NULL = "locked,disabled,${3},null,";
- private static final String LOCKED_DISABLED_ANY_COLDSTANDBY = "locked,disabled,${3},coldstandby,";
- private static final String UNLOCKED_ENABLED_NULL_HOTSTANDBY = "unlocked,enabled,null,hotstandby,";
- private static final String UNLOCKED_ENABLED_NULL_ANY = "unlocked,enabled,null,${4},";
- private static final String LOCKED_ENABLED_NULL_NULL = "locked,enabled,null,null,";
- private static final String LOCKED_ENABLED_NULL_COLDSTANDBY = "locked,enabled,null,coldstandby,";
- private static final Logger logger = LoggerFactory.getLogger(StateTransition.class);
-
- public static final String ADMIN_STATE = "adminState";
- public static final String OPERATION_STATE = "opState";
- public static final String AVAILABLE_STATUS = "availStatus";
- public static final String STANDBY_STATUS = "standbyStatus";
- public static final String ACTOIN_NAME = "actionName";
-
- /*
- * Common strings.
- */
- private static final String EXCEPTION_STRING = "Exception:StateTransition unable to process state: adminState=[";
- private static final String OPSTATE_STRING = "], opState=[";
- private static final String AVAILSTATUS_STRING = "], availStatus=[";
- private static final String STANDBY_STRING = "], standbyStatus=[";
- private static final String ACTION_STRING = "], actionName=[";
-
- /*
- * Valid values for each type.
- */
- private static final Set<String> VALID_ADMIN_STATE = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.LOCKED,
- StateManagement.UNLOCKED)));
-
- private static final Set<String> VALID_OP_STATE = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.ENABLED,
- StateManagement.DISABLED)));
-
- private static final Set<String> VALID_STANDBY_STATUS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.NULL_VALUE,
- StateManagement.COLD_STANDBY,
- StateManagement.HOT_STANDBY,
- StateManagement.PROVIDING_SERVICE)));
-
- private static final Set<String> VALID_AVAIL_STATUS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.NULL_VALUE,
- StateManagement.DEPENDENCY,
- StateManagement.DEPENDENCY_FAILED,
- StateManagement.FAILED)));
-
- private static final Set<String> VALID_ACTION_NAME = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- StateManagement.DEMOTE_ACTION,
- StateManagement.DISABLE_DEPENDENCY_ACTION,
- StateManagement.DISABLE_FAILED_ACTION,
- StateManagement.ENABLE_NO_DEPENDENCY_ACTION,
- StateManagement.ENABLE_NOT_FAILED_ACTION,
- StateManagement.LOCK_ACTION,
- StateManagement.PROMOTE_ACTION,
- StateManagement.UNLOCK_ACTION)));
-
- /**
- * This is only used while populating {@link #STATE_TABLE}.
- */
- private static final List<Pair<String, String[]>> TRANSITION_ITEMS = new ArrayList<>(10);
-
- /**
- * State-transition table.
- */
- private static final Map<String, String> STATE_TABLE = new HashMap<>();
-
- static {
- populateStateTable();
- }
-
-
- /**
- * Calculates the state transition and returns the end state.
- *
- * @param adminState the administration state
- * @param opState the operational state
- * @param availStatus the availability status
- * @param standbyStatus the standby status
- * @param actionName the action name
- * @return the StateEement
- * @throws StateTransitionException if an error occurs
- */
- public StateElement getEndingState(String adminState, String opState, String availStatus, String standbyStatus,
- String actionName) throws StateTransitionException {
- logger.debug("getEndingState");
- logger.debug("adminState=[{}], opState=[{}], availStatus=[{}], standbyStatus=[{}], actionName[{}]",
- adminState, opState, availStatus, standbyStatus, actionName);
-
- if (availStatus == null) {
- availStatus = StateManagement.NULL_VALUE;
- }
- if (standbyStatus == null) {
- standbyStatus = StateManagement.NULL_VALUE;
- }
-
- if (!VALID_ADMIN_STATE.contains(adminState) || !VALID_OP_STATE.contains(opState)
- || !VALID_STANDBY_STATUS.contains(standbyStatus)) {
- throw new StateTransitionException(
- EXCEPTION_STRING + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus
- + STANDBY_STRING + standbyStatus + ACTION_STRING + actionName + "]");
- }
-
- if (!VALID_AVAIL_STATUS.contains(availStatus) || !VALID_ACTION_NAME.contains(actionName)) {
- throw new StateTransitionException(
- EXCEPTION_STRING + adminState + OPSTATE_STRING + opState + AVAILSTATUS_STRING + availStatus
- + STANDBY_STRING + standbyStatus + ACTION_STRING + actionName + "]");
- }
-
-
- var stateElement = new StateElement();
-
- // dependency,failed is stored as dependency.failed in StateTable
- String availStatus2 = availStatus;
- if (availStatus2 != null) {
- availStatus2 = availStatus.replace(",", ".");
- }
- String key = adminState + "," + opState + "," + availStatus2 + "," + standbyStatus + "," + actionName;
- logger.debug("Ending State search key: {}", key);
- String value = STATE_TABLE.get(key);
-
- if (value != null) {
- String[] parts = COMMA_PAT.split(value, 5);
- stateElement.setEndingAdminState(parts[0].trim());
- stateElement.setEndingOpState(parts[1].trim());
- stateElement.setEndingAvailStatus(parts[2].trim().replace(".", ","));
- stateElement.setEndingStandbyStatus(parts[3].trim());
- stateElement.setException(parts[4].trim());
- stateElement.setAdminState(adminState);
- stateElement.setOpState(opState);
- stateElement.setAvailStatus(availStatus);
- stateElement.setStandbyStatus(standbyStatus);
- stateElement.setActionName(actionName);
-
- stateElement.displayStateElement();
-
- } else {
- String msg = "Ending state not found, adminState=[" + adminState + OPSTATE_STRING + opState
- + AVAILSTATUS_STRING + availStatus + STANDBY_STRING + standbyStatus + ACTION_STRING
- + actionName + "]";
- logger.error("{}", msg);
- throw new StateTransitionException(msg);
- }
-
- return stateElement;
- }
-
- /**
- * Adding State Transition info into HashMap. It includes all state/status and action
- * combinations key : adminState,opState,availStatus,standbyStatus,actionName value:
- * endingAdminState,endingOpState,endingAvailStatus,endingStandbyStatus,exception Note : Use
- * period instead of comma as seperator when store multi-value endingStandbyStatus (convert to
- * comma during retrieval)
- *
- * <p>Note on illegal state/status combinations: This table has many state/status combinations
- * that should never occur. However, they *may* occur due to corruption or manual manipulation
- * of the DB. So, in each case of an illegal combination, the state/status is first corrected
- * before applying the action. It is assumed that the administrative and operational states are
- * always correct. Second, if the availability status is in "agreement" with the operational
- * state, it is assumed correct. If it is null and the operational state is disabled, the
- * availability status is left null until a disabledfailed or disableddependency action is
- * received. Or, if a enableNotFailed or enableNoDependency is received while the availability
- * status is null, it will remain null, but the Operational state will change to enabled.
- *
- * <p>If the standby status is not in agreement with the administrative and/or operational
- * states, it is brought into agreement. For example, if the administrative state is locked and
- * the standby status is providingservice, the standby status is changed to coldstandby.
- *
- * <p>After bringing the states/status attributes into agreement, *then* the action is applied
- * to them. For example, if the administrative state is locked, the operational state is
- * enabled, the availability status is null, the standby status is providingservice and the
- * action is unlock, the standby status is changed to coldstandby and then the unlock action is
- * applied. This will change the final state/status to administrative state = unlocked,
- * operational state = disabled, availability status = null and standby status = hotstandby.
- *
- * <p>Note on standby status: If the starting state of standby status is null and either a
- * promote or demote action is made, the assumption is that standbystatus is supported and
- * therefore, the standby status will be changed to providingservice, hotstandby or coldstandby
- * - depending on the value of the administrative and operational states. If an attempt to
- * promote is made when the administrative state is locked or operational state is disabled, a
- * StandbyStatusException will be thrown since promotion (state transition) is not possible. If
- * the standby status is coldstandby and a transition occurs on the administrative or
- * operational state such that they are unlocked and enabled, the standby status is
- * automatically transitioned to hotstandby since it is only those two states that can hold the
- * standby status in the coldstandby value.
- */
-
- private static void populateStateTable() {
- /*
- * These are the items we'll be using while populating the state transition table.
- */
- TRANSITION_ITEMS.clear();
- TRANSITION_ITEMS.add(Pair.of("${1}", new String[] {"unlocked", "locked"}));
- TRANSITION_ITEMS.add(Pair.of("${2}", new String[] {"enabled", "disabled"}));
- TRANSITION_ITEMS.add(Pair.of("${3}", new String[] {"null", "failed", "dependency", DEPENDENCY_FAILED}));
- TRANSITION_ITEMS.add(Pair.of("${3:fail}", new String[] {"failed", DEPENDENCY_FAILED}));
- TRANSITION_ITEMS.add(Pair.of("${3:dep}", new String[] {"dependency", DEPENDENCY_FAILED}));
- TRANSITION_ITEMS.add(Pair.of("${4}", new String[] {"null", "coldstandby", "hotstandby", "providingservice"}));
-
- STATE_TABLE.clear();
-
- // lock
- populate("${1},enabled,${3},${4},lock", LOCKED_ENABLED_NULL_COLDSTANDBY);
- populate("${1},enabled,${3},null,lock", LOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3},${4},lock", LOCKED_DISABLED_ANY_COLDSTANDBY);
- populate("${1},disabled,${3},null,lock", LOCKED_DISABLED_ANY_NULL);
-
-
- // unlock
- populate("unlocked,enabled,${3},${4},unlock", UNLOCKED_ENABLED_NULL_ANY);
- populate("unlocked,enabled,${3},coldstandby,unlock", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("locked,enabled,${3},${4},unlock", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
- populate("locked,enabled,${3},null,unlock", UNLOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3},${4},unlock", UNLOCKED_DISABLED_ANY_COLDSTANDBY);
- populate("${1},disabled,${3},null,unlock", UNLOCKED_DISABLED_ANY_NULL);
-
-
- // disableFailed
- populate("${1},${2},${3},${4},disableFailed", ANY_DISABLED_FAILED_COLDSTANDBY);
- populate("${1},${2},${3},null,disableFailed", ANY_DISABLED_FAILED_NULL);
-
- populate("${1},disabled,${3:dep},${4},disableFailed", ANY_DISABLED_DEPENDENCY_FAILED_COLDSTANDBY);
- populate("${1},disabled,${3:dep},null,disableFailed", ANY_DISABLED_DEPENDENCY_FAILED_NULL);
-
-
- // enableNotFailed
- populate("unlocked,${2},${3},${4},enableNotFailed", UNLOCKED_ENABLED_NULL_ANY);
- populate("unlocked,${2},${3},coldstandby,enableNotFailed", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("unlocked,disabled,${3},${4},enableNotFailed", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
- populate("unlocked,disabled,${3},null,enableNotFailed", UNLOCKED_ENABLED_NULL_NULL);
-
- populate("locked,${2},${3},${4},enableNotFailed", LOCKED_ENABLED_NULL_COLDSTANDBY);
- populate("locked,${2},${3},null,enableNotFailed", LOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3:dep},${4},enableNotFailed", ANY_DISABLED_DEPENDENCY_COLDSTANDBY);
- populate("${1},disabled,${3:dep},null,enableNotFailed", ANY_DISABLED_DEPENDENCY_NULL);
-
-
- // disableDependency
- populate("${1},${2},${3},${4},disableDependency", ANY_DISABLED_DEPENDENCY_COLDSTANDBY);
- populate("${1},${2},${3},null,disableDependency", ANY_DISABLED_DEPENDENCY_NULL);
-
- populate("${1},disabled,${3:fail},${4},disableDependency", ANY_DISABLED_DEPENDENCY_FAILED_COLDSTANDBY);
- populate("${1},disabled,${3:fail},null,disableDependency", ANY_DISABLED_DEPENDENCY_FAILED_NULL);
-
- populate("unlocked,enabled,dependency,hotstandby,disableDependency", UNLOCKED_DISABLED_DEPENDENCY_HOTSTANDBY);
-
-
- // enableNoDependency
- populate("unlocked,enabled,${3},${4},enableNoDependency", UNLOCKED_ENABLED_NULL_ANY);
- populate("unlocked,enabled,${3},coldstandby,enableNoDependency", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("unlocked,disabled,${3},${4},enableNoDependency", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
- populate("unlocked,disabled,${3},null,enableNoDependency", UNLOCKED_ENABLED_NULL_NULL);
-
- populate("locked,${2},${3},${4},enableNoDependency", LOCKED_ENABLED_NULL_COLDSTANDBY);
- populate("locked,${2},${3},null,enableNoDependency", LOCKED_ENABLED_NULL_NULL);
-
- populate("${1},disabled,${3:fail},${4},enableNoDependency", ANY_DISABLED_FAILED_COLDSTANDBY);
- populate("${1},disabled,${3:fail},null,enableNoDependency", ANY_DISABLED_FAILED_NULL);
-
-
- // promote
- populate("unlocked,enabled,${3},${4},promote", UNLOCKED_ENABLED_NULL_PROVIDINGSERVICE);
-
- populate("locked,enabled,${3},${4},promote", LOCKED_ENABLED_NULL_COLDSTANDBY_STANDBY_STATUS_EXCEPTION);
-
- populate("${1},disabled,${3},${4},promote", ANY_DISABLED_ANY_COLDSTANDBY_STANDBY_STATUS_EXCEPTION);
-
-
- // demote
- populate("unlocked,enabled,${3},${4},demote", UNLOCKED_ENABLED_NULL_HOTSTANDBY);
-
- populate("locked,enabled,${3},${4},demote", LOCKED_ENABLED_NULL_COLDSTANDBY);
-
- populate("${1},disabled,${3},${4},demote", ANY_DISABLED_ANY_COLDSTANDBY);
- }
-
- /**
- * Populates {@link #STATE_TABLE} with the incoming and outgoing strings, trying all
- * substitutions of the item place-holders that appear within the strings.
- * @param incoming incoming string, with optional item place-holders
- * @param outgoing outgoing string, with optional item place-holders
- */
- private static void populate(String incoming, String outgoing) {
- populate(incoming, outgoing, 0);
- }
-
- /**
- * Makes appropriate substitutions within the incoming and outgoing strings, looping
- * through all possible items at the given position. Once the position has reached the
- * end of the item table, the incoming/outgoing result is added to
- * {@link #STATE_TABLE}.
- *
- * @param incoming incoming string, with optional item place-holders
- * @param outgoing outgoing string, with optional item place-holders
- * @param pos current position within the transition items
- */
- private static void populate(String incoming, String outgoing, int pos) {
-
- if (pos >= TRANSITION_ITEMS.size()) {
- // used up all possible replacements - add result to the table
- STATE_TABLE.put(incoming, outgoing);
- return;
- }
-
- Pair<String, String[]> pair = TRANSITION_ITEMS.get(pos);
- String key = pair.getKey();
-
- if (!incoming.contains(key) && !outgoing.contains(key)) {
- // strings do not contain a place-holder for this position - try the next
- populate(incoming, outgoing, pos + 1);
- return;
- }
-
- // process all items associated with this place-holder
- for (String item : pair.getValue()) {
- String incoming2 = incoming.replace(key, item);
- String outgoing2 = outgoing.replace(key, item);
- populate(incoming2, outgoing2, pos + 1);
- }
- }
-
- /**
- * Display the state table.
- */
- public void displayStateTable() {
- if (!logger.isDebugEnabled()) {
- return;
- }
-
- for (Entry<String, String> me : STATE_TABLE.entrySet()) {
- String key = me.getKey() + me.getValue().replace(".", ",");
- logger.debug("{}", key);
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java
deleted file mode 100644
index 0f4ea2fd..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/StateTransitionException.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im;
-
-public class StateTransitionException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public StateTransitionException() {
- super();
- }
-
- public StateTransitionException(String message) {
- super(message);
- }
-
- public StateTransitionException(Throwable cause) {
- super(cause);
- }
-
- public StateTransitionException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java
deleted file mode 100644
index 9387805c..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/exceptions/EntityRetrievalException.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2018 Ericsson. 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.im.exceptions;
-
-public class EntityRetrievalException extends RuntimeException {
-
- private static final long serialVersionUID = 8761143697306009072L;
-
- public EntityRetrievalException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java
deleted file mode 100644
index 8cbdaa7d..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdmin.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-2021 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.im.jmx;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.InstanceNotFoundException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import org.onap.policy.common.im.IntegrityMonitor;
-import org.onap.policy.common.im.IntegrityMonitorException;
-import org.onap.policy.common.im.StateManagement;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Base class for component MBeans.
- */
-public class ComponentAdmin implements ComponentAdminMBean {
- private static final String STATE_MANAGER = "stateManager";
-
- private static final Logger logger = LoggerFactory.getLogger(ComponentAdmin.class.getName());
-
- private final String name;
- private MBeanServer registeredMBeanServer;
- private ObjectName registeredObjectName;
- private IntegrityMonitor integrityMonitor = null;
- private StateManagement stateManager = null;
-
- /**
- * Constructor.
- *
- * @param name the MBean name
- * @param integrityMonitor the integrity monitor
- * @param stateManager the state manager
- * @throws ComponentAdminException if an error occurs
- */
- public ComponentAdmin(String name, IntegrityMonitor integrityMonitor, StateManagement stateManager)
- throws ComponentAdminException {
- if ((name == null) || (integrityMonitor == null) || (stateManager == null)) {
- logger.error("Error: ComponentAdmin constructor called with invalid input");
- throw new ComponentAdminException("null input");
- }
-
- this.name = "ONAP_POLICY_COMP:name=" + name;
- this.integrityMonitor = integrityMonitor;
- this.stateManager = stateManager;
-
- try {
- register();
- } catch (ComponentAdminException e) {
- logger.debug("Failed to register ComponentAdmin MBean");
- throw e;
- }
- }
-
- /**
- * Registers with the MBean server.
- *
- * @throws ComponentAdminException a JMX exception
- */
- public synchronized void register() throws ComponentAdminException {
-
- try {
- logger.debug("Registering {} MBean", name);
-
- var mbeanServer = findMBeanServer();
-
- if (mbeanServer == null) {
- return;
- }
-
- var objectName = new ObjectName(name);
-
- if (mbeanServer.isRegistered(objectName)) {
- logger.debug("Unregistering a previously registered {} MBean", name);
- mbeanServer.unregisterMBean(objectName);
- }
-
- mbeanServer.registerMBean(this, objectName);
- registeredMBeanServer = mbeanServer;
- registeredObjectName = objectName;
-
- } catch (MalformedObjectNameException | MBeanRegistrationException | InstanceNotFoundException
- | InstanceAlreadyExistsException | NotCompliantMBeanException e) {
- throw new ComponentAdminException(e);
- }
- }
-
- /**
- * Checks if this MBean is registered with the MBeanServer.
- *
- * @return true if this MBean is registered with the MBeanServer.
- */
- public boolean isRegistered() {
- return registeredObjectName != null;
- }
-
- /**
- * Unregisters with the MBean server.
- *
- * @throws ComponentAdminException a JMX exception
- */
- public synchronized void unregister() throws ComponentAdminException {
-
- if (registeredObjectName == null) {
- return;
- }
-
-
- try {
- registeredMBeanServer.unregisterMBean(registeredObjectName);
-
- } catch (MBeanRegistrationException | InstanceNotFoundException e) {
- throw new ComponentAdminException(e);
- }
-
- registeredMBeanServer = null;
- registeredObjectName = null;
- }
-
- @Override
- public String toString() {
- return ComponentAdmin.class.getSimpleName() + "[" + name + "]";
- }
-
- /**
- * Finds the MBeanServer.
- *
- * @return the MBeanServer, or null if it is not found
- */
- public static MBeanServer findMBeanServer() {
- ArrayList<MBeanServer> mbeanServers = MBeanServerFactory.findMBeanServer(null);
-
- Iterator<MBeanServer> iter = mbeanServers.iterator();
- MBeanServer mbeanServer;
-
- while (iter.hasNext()) {
- mbeanServer = iter.next();
- if ("DefaultDomain".equals(mbeanServer.getDefaultDomain())) {
- return mbeanServer;
- }
- }
-
- return null;
- }
-
- /**
- * Creates the MBeanServer (intended for unit testing only).
- *
- * @return the MBeanServer
- */
- public static MBeanServer createMBeanServer() {
- return MBeanServerFactory.createMBeanServer("DefaultDomain");
- }
-
- /**
- * Get the MBean object name for the specified feature name.
- *
- * @param componentName component name
- * @return the object name
- * @throws MalformedObjectNameException a JMX exception
- */
- public static ObjectName getObjectName(String componentName) throws MalformedObjectNameException {
- return new ObjectName("ONAP_POLICY_COMP:name=" + componentName);
- }
-
- @Override
- public void test() throws IntegrityMonitorException {
- // Call evaluateSanity on IntegrityMonitor to run the test
- logger.debug("test() called...");
- if (integrityMonitor != null) {
- integrityMonitor.evaluateSanity();
- } else {
- logger.error("Unable to invoke test() - state manager instance is null");
- throw new ComponentAdminException(STATE_MANAGER);
- }
-
- }
-
- @Override
- public void lock() throws IntegrityMonitorException {
- logger.debug("lock() called...");
- if (stateManager != null) {
- stateManager.lock();
- } else {
- logger.error("Unable to invoke lock() - state manager instance is null");
- throw new ComponentAdminException(STATE_MANAGER);
- }
- }
-
- @Override
- public void unlock() throws IntegrityMonitorException {
- logger.debug("unlock() called...");
- if (stateManager != null) {
- stateManager.unlock();
- } else {
- logger.error("Unable to invoke unlock() - state manager instance is null");
- throw new ComponentAdminException(STATE_MANAGER);
- }
-
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java
deleted file mode 100644
index dcc4da0a..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminException.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * ============LICENSE_START=======================================================
- * Integrity Audit
- * ================================================================================
- * Copyright (C) 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.im.jmx;
-
-import org.onap.policy.common.im.IntegrityMonitorException;
-
-public class ComponentAdminException extends IntegrityMonitorException {
- private static final long serialVersionUID = 1L;
-
- public ComponentAdminException() {
- super();
- }
-
- public ComponentAdminException(String message) {
- super(message);
- }
-
- public ComponentAdminException(Throwable cause) {
- super(cause);
- }
-
- public ComponentAdminException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java
deleted file mode 100644
index 3276cf63..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/ComponentAdminMBean.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.im.jmx;
-
-import org.onap.policy.common.im.IntegrityMonitorException;
-
-/**
- * Provides operations to test health, lock and unlock components.
- */
-public interface ComponentAdminMBean {
- /**
- * Test health of component.
- *
- * @throws IntegrityMonitorException if the component fails the health check
- */
- void test() throws IntegrityMonitorException;
-
- /**
- * Administratively lock component.
- *
- * @throws IntegrityMonitorException if the component lock fails
- */
- void lock() throws IntegrityMonitorException;
-
- /**
- * Administratively unlock component.
- *
- * @throws IntegrityMonitorException if the component unlock fails
- */
- void unlock() throws IntegrityMonitorException;
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java
deleted file mode 100644
index a2d8c091..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jmx/JmxAgentConnection.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2019 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.im.jmx;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import javax.management.MBeanServerConnection;
-import javax.management.remote.JMXConnectionNotification;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import org.onap.policy.common.im.IntegrityMonitorException;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-/**
- * Class to create a JMX RMI connection to the JmxAgent.
- */
-public final class JmxAgentConnection {
-
- private static final Logger logger = FlexLogger.getLogger(JmxAgentConnection.class);
-
-
- private static final String DEFAULT_HOST = "localhost";
- private static final String DEFAULT_PORT = "9996";
-
- private String host;
- private String port;
- private JMXConnector connector;
- private String jmxUrl = null;
-
- /**
- * Set up the host/port from the properties. Use defaults if missing from the properties.
- */
- public JmxAgentConnection() {
- host = DEFAULT_HOST;
- port = DEFAULT_PORT;
- }
-
- public JmxAgentConnection(String url) {
- jmxUrl = url;
- }
-
- /**
- * Generate jmxAgent url. service:jmx:rmi:///jndi/rmi://host.domain:9999/jmxAgent
- *
- * @param host host.domain
- * @param port 9999
- * @return jmxAgent url.
- */
- private static String jmxAgentUrl(String host, String port) {
-
- return "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
- }
-
- /**
- * Get a connection to the jmxAgent MBeanServer.
- *
- * @return the connection
- * @throws IntegrityMonitorException on error
- */
- public MBeanServerConnection getMBeanConnection() throws IntegrityMonitorException {
-
- try {
- JMXServiceURL url;
- if (jmxUrl == null) {
- url = new JMXServiceURL(jmxAgentUrl(host, port));
- } else {
- url = new JMXServiceURL(jmxUrl);
- }
- Map<String, Object> env = new HashMap<>();
-
- connector = JMXConnectorFactory.newJMXConnector(url, env);
- connector.connect();
- connector.addConnectionNotificationListener((notification, handback) -> {
- if (notification.getType().equals(JMXConnectionNotification.FAILED)) {
- // handle disconnect
- disconnect();
- }
- }, null, null);
-
- return connector.getMBeanServerConnection();
-
- } catch (IOException e) {
- throw new IntegrityMonitorException(e);
- }
- }
-
- /**
- * Disconnect.
- */
- public void disconnect() {
- if (connector != null) {
- try {
- connector.close();
- } catch (IOException e) {
- logger.debug(e);
- }
- }
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java
deleted file mode 100644
index 5213baef..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/DateEntity.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 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.
- * 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.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.MappedSuperclass;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.im.MonitorTime;
-
-/*
- * Superclass of Entities having create and update timestamps.
- */
-@MappedSuperclass
-@Getter
-@Setter
-@NoArgsConstructor
-public class DateEntity implements Serializable {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_date", updatable = false)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "last_updated")
- private Date lastUpdated;
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- public void prePersist() {
- var date = MonitorTime.getInstance().getDate();
- this.createdDate = date;
- this.lastUpdated = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.lastUpdated = MonitorTime.getInstance().getDate();
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java
deleted file mode 100644
index 7c9698b3..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ForwardProgressEntity.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-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.
- * 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.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.Table;
-import java.io.Serial;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-
-@Entity
-@Table(name = "ForwardProgressEntity")
-@NamedQuery(name = " ForwardProgressEntity.findAll", query = "SELECT e FROM ForwardProgressEntity e ")
-@NamedQuery(name = "ForwardProgressEntity.deleteAll", query = "DELETE FROM ForwardProgressEntity WHERE 1=1")
-@Getter
-@Setter
-@NoArgsConstructor
-public class ForwardProgressEntity extends DateEntity {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "forwardProgressId")
- @Setter(AccessLevel.NONE)
- private long forwardProgressId;
-
- @Column(name = "resourceName", nullable = false, length = 100, unique = true)
- private String resourceName;
-
- @Column(name = "fpc_count", nullable = false)
- private long fpcCount;
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- @Override
- public void prePersist() {
- this.fpcCount = 0;
- super.prePersist();
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java
deleted file mode 100644
index e70a000b..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ImTestEntity.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-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.
- * 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.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Table;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.im.MonitorTime;
-
-@Entity
-@Table(name = "ImTestEntity")
-@NamedQuery(name = " ImTestEntity.findAll", query = "SELECT e FROM ImTestEntity e ")
-@NamedQuery(name = "ImTestEntity.deleteAll", query = "DELETE FROM ImTestEntity WHERE 1=1")
-@Getter
-@Setter
-@NoArgsConstructor
-public class ImTestEntity implements Serializable {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "ImTestId")
- @Setter(AccessLevel.NONE)
- private long imTestId;
-
- @Column(name = "created_by", nullable = false, length = 255)
- private String createdBy = "guest";
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_date", updatable = false)
- private Date createdDate;
-
- @Column(name = "modified_by", nullable = false, length = 255)
- private String modifiedBy = "guest";
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "modified_date", nullable = false)
- private Date modifiedDate;
-
- /**
- * PrePersist callback method.
- */
- @PrePersist
- public void prePersist() {
- var date = MonitorTime.getInstance().getDate();
- this.createdDate = date;
- this.modifiedDate = date;
- }
-
- @PreUpdate
- public void preUpdate() {
- this.modifiedDate = MonitorTime.getInstance().getDate();
- }
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java
deleted file mode 100644
index a771ba09..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * Copyright (C) 2017-2018, 2020-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.
- * 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.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQueries;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.Table;
-import java.io.Serial;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-/*
- * The Entity class to persist a policy object ResourceRegistration
- */
-
-@Entity
-@Table(name = "ResourceRegistrationEntity")
-@NamedQuery(name = " ResourceRegistrationEntity.findAll", query = "SELECT e FROM ResourceRegistrationEntity e ")
-@NamedQuery(name = "ResourceRegistrationEntity.deleteAll", query = "DELETE FROM ResourceRegistrationEntity WHERE 1=1")
-@Getter
-@Setter
-@NoArgsConstructor
-public class ResourceRegistrationEntity extends DateEntity {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "ResourceRegistrationId")
- @Setter(AccessLevel.NONE)
- private long resourceRegistrationId;
-
- @Column(name = "resourceName", nullable = false, length = 100, unique = true)
- private String resourceName;
-
- @Column(name = "resourceUrl", nullable = false, length = 255, unique = true)
- private String resourceUrl;
-
- @Column(name = "site", nullable = true, length = 50)
- private String site;
-
- @Column(name = "nodeType", nullable = true, length = 50)
- private String nodeType;
-}
diff --git a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java b/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java
deleted file mode 100644
index b03ec71b..00000000
--- a/integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/StateManagementEntity.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Integrity Monitor
- * ================================================================================
- * 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.
- * 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.im.jpa;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.NamedQuery;
-import jakarta.persistence.PrePersist;
-import jakarta.persistence.PreUpdate;
-import jakarta.persistence.Table;
-import jakarta.persistence.Temporal;
-import jakarta.persistence.TemporalType;
-import java.io.Serial;
-import java.io.Serializable;
-import java.util.Date;
-import lombok.AccessLevel;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.onap.policy.common.im.MonitorTime;
-
-@Entity
-@Table(name = "StateManagementEntity")
-@NamedQuery(name = "StateManagementEntity.findAll", query = "SELECT e FROM StateManagementEntity e")
-@Getter
-@Setter
-@NoArgsConstructor
-public class StateManagementEntity implements Serializable {
- @Serial
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- @Column(name = "id")
- @Getter(AccessLevel.NONE)
- @Setter(AccessLevel.NONE)
- private long id;
-
- @Column(name = "resourceName", nullable = false, length = 100, unique = true)
- private String resourceName;
-
- @Column(name = "adminState", nullable = false, length = 20)
- private String adminState;
-
- @Column(name = "opState", nullable = false, length = 20)
- private String opState;
-
- @Column(name = "availStatus", nullable = false, length = 20)
- private String availStatus;
-
- @Column(name = "standbyStatus", nullable = false, length = 20)
- private String standbyStatus;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_Date", updatable = false)
- @Setter(AccessLevel.NONE)
- private Date createdDate;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "modifiedDate", nullable = false)
- private Date modifiedDate;
-
- @PrePersist
- public void prePersist() {
- this.createdDate = MonitorTime.getInstance().getDate();
- this.modifiedDate = MonitorTime.getInstance().getDate();
- }
-
- @PreUpdate
- public void preUpdate() {
- this.modifiedDate = MonitorTime.getInstance().getDate();
- }
-
- /**
- * Clone a StateManagementEntity.
- *
- * @param sm the StateManagementEntity to clone
- * @return a new StateManagementEntity
- */
- public static StateManagementEntity clone(StateManagementEntity sm) {
- var newStateManagementEntity = new StateManagementEntity();
- newStateManagementEntity.setResourceName(sm.getResourceName());
- newStateManagementEntity.setAdminState(sm.getResourceName());
- newStateManagementEntity.setOpState(sm.getOpState());
- newStateManagementEntity.setAdminState(sm.getAdminState());
- newStateManagementEntity.setAvailStatus(sm.getAvailStatus());
- newStateManagementEntity.setStandbyStatus(sm.getStandbyStatus());
-
- return newStateManagementEntity;
- }
-}
diff --git a/integrity-monitor/src/main/resources/META-INF/persistence.xml b/integrity-monitor/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index ecba25cc..00000000
--- a/integrity-monitor/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ============LICENSE_START=======================================================
- Integrity Monitor
- ================================================================================
- Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
- Modifications Copyright (C) 2023-2024 Nordix Foundation.
- ================================================================================
- 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=========================================================
- -->
-
-<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
- <persistence-unit name="schemaPU" transaction-type="RESOURCE_LOCAL">
- <!-- Limited use for generating the DB and schema files for imtest DB - uses hibernate -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
- <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
- <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
- <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <property name="jakarta.persistence.schema-generation.database.action" value="drop-and-create" />
- </properties>
- </persistence-unit>
-
- <persistence-unit name="operationalPU" transaction-type="RESOURCE_LOCAL">
- <!-- For operational use -->
- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
- <class>org.onap.policy.common.im.jpa.ImTestEntity</class>
- <class>org.onap.policy.common.im.jpa.StateManagementEntity</class>
- <class>org.onap.policy.common.im.jpa.ForwardProgressEntity</class>
- <class>org.onap.policy.common.im.jpa.ResourceRegistrationEntity</class>
- <shared-cache-mode>NONE</shared-cache-mode>
- <properties>
- <!-- none -->
- </properties>
- </persistence-unit>
-</persistence>
diff --git a/integrity-monitor/src/main/resources/log4j.properties b/integrity-monitor/src/main/resources/log4j.properties
deleted file mode 100644
index fde133de..00000000
--- a/integrity-monitor/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,48 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# Integrity Monitor
-# ================================================================================
-# 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=========================================================
-###
-
-#
-# Use this properties for debugging and development.
-#
-#
-# Set root logger level to DEBUG and its only appender to A1.
-log4j.rootLogger=INFO, FILE
-
-# A1 is set to be a DailyRollingFileAppender.
-log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
-
-# Set the name of the file
-log4j.appender.FILE.File=IntegrityMonitor.log
-
-# Set the immediate flush to true (default)
-log4j.appender.FILE.ImmediateFlush=true
-
-# Set the threshold to debug mode
-log4j.appender.FILE.Threshold=debug
-
-# Set the append to false, should not overwrite
-log4j.appender.FILE.Append=true
-
-# Set the DatePattern
-log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
-
-# A1 uses PatternLayout.
-log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
-log4j.appender.FILE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n