From 7602a4380488d872b25cd718176b23369bf9e472 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Wed, 24 Jul 2019 13:19:28 -0400 Subject: Add coverage to feature-active-standby-management Also removed some logger.isXxx() tests, which should reduce the number of branches that need to be tested. Removed unneeded objects and methods from feature-lifecyle. Change-Id: Ic3eb9c0b63a2ad5585846525eb0ebda81fc55d5e Issue-ID: POLICY-1772 Signed-off-by: Jim Hahn --- .../drools/activestandby/ActiveStandbyFeature.java | 20 +- .../activestandby/ActiveStandbyProperties.java | 16 +- .../drools/activestandby/DroolsPdpObject.java | 55 ++-- .../activestandby/DroolsPdpsElectionHandler.java | 327 +++++++-------------- .../activestandby/JpaDroolsPdpsConnector.java | 194 ++++-------- .../PmStandbyStateChangeNotifier.java | 253 ++++++---------- .../activestandby/ActiveStandbyPropertiesTest.java | 53 ++++ .../drools/activestandby/DroolsPdpObjectTest.java | 153 ++++++++++ .../PmStandbyStateChangeNotifierTest.java | 284 ++++++++++++++++++ .../drools/controller/test/AllSeemsWellTest.java | 2 +- 10 files changed, 800 insertions(+), 557 deletions(-) create mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/ActiveStandbyPropertiesTest.java create mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java create mode 100644 feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java (limited to 'feature-active-standby-management') diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java index 5b1caeae..2be44458 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java @@ -47,7 +47,7 @@ import org.slf4j.LoggerFactory; * 'PolicyContainer' and 'Main'. It was moved here as part of making this * a separate optional feature. */ -public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, +public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, PolicySessionFeatureApi, PolicyEngineFeatureApi { // get an instance of logger private static final Logger logger = @@ -84,20 +84,16 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { if (feature.getResourceName().equals(myPdp.getPdpId())) { - if (logger.isDebugEnabled()) { - logger.debug("ActiveStandbyFeature.globalInit: Found StateManagementFeature" - + " with resourceName: {}", myPdp.getPdpId()); - } + logger.debug("ActiveStandbyFeature.globalInit: Found StateManagementFeature" + + " with resourceName: {}", myPdp.getPdpId()); stateManagementFeature = feature; break; } } if (stateManagementFeature == null) { - if (logger.isDebugEnabled()) { - logger.debug("ActiveStandbyFeature failed to initialize. " - + "Unable to get instance of StateManagementFeatureApi " - + "with resourceID: {}", myPdp.getPdpId()); - } + logger.debug("ActiveStandbyFeature failed to initialize. " + + "Unable to get instance of StateManagementFeatureApi " + + "with resourceID: {}", myPdp.getPdpId()); logger.error("ActiveStandbyFeature failed to initialize. " + "Unable to get instance of StateManagementFeatureApi " + "with resourceID: {}", myPdp.getPdpId()); @@ -114,9 +110,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi, //Register the PMStandbyStateChangeNotifier Observer stateManagementFeature.addObserver(pmNotifier); - if (logger.isDebugEnabled()) { - logger.debug("ActiveStandbyFeature.globalInit() exit"); - } + logger.debug("ActiveStandbyFeature.globalInit() exit"); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyProperties.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyProperties.java index 009ff8c6..3a0ba4d1 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyProperties.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyProperties.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * feature-active-standby-management * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * 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. @@ -25,7 +25,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActiveStandbyProperties { - // get an instance of logger + // get an instance of logger private static final Logger logger = LoggerFactory.getLogger(ActiveStandbyProperties.class); public static final String PDP_CHECK_INVERVAL = "pdp.checkInterval"; @@ -47,17 +47,17 @@ public class ActiveStandbyProperties { private static Properties properties = null; private ActiveStandbyProperties() { - throw new IllegalStateException("Utility class"); + // do nothing } - + /** * Initialize the parameter values from the droolsPersitence.properties file values. - * + * *

This is designed so that the Properties object is obtained from properties * file and then is passed to this method to initialize the value of the parameters. * This allows the flexibility of JUnit tests using getProperties(filename) to get the * properties while runtime methods can use getPropertiesFromClassPath(filename). - * + * * @param prop properties */ public static void initProperties(Properties prop) { diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java index 49f6b02d..8ac14f0e 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * feature-active-standby-management * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * 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. @@ -31,47 +31,38 @@ public abstract class DroolsPdpObject implements DroolsPdp { return false; } } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (this.getPdpId() == null ? 0 : this.getPdpId().hashCode()); - result = prime * result + (this.getSiteName() == null ? 0 : this.getSiteName().hashCode()); - result = prime * result + this.getPriority(); - return super.hashCode(); - } - + private int nullSafeCompare(String one, String two) { - if (one != null && two != null) { - return one.compareTo(two); - } - if (one == null && two != null) { + if (one != null) { + if (two != null) { + return one.compareTo(two); + + } else { + return 1; + } + + } else if (two != null) { return -1; + + } else { + return 0; } - if (one != null && two == null) { - return 1; - } - return 0; } - + @Override public int comparePriority(DroolsPdp other) { - if (nullSafeCompare(this.getSiteName(),other.getSiteName()) == 0) { - if (this.getPriority() != other.getPriority()) { - return this.getPriority() - other.getPriority(); - } - return this.getPdpId().compareTo(other.getPdpId()); - } else { - return nullSafeCompare(this.getSiteName(),other.getSiteName()); - } + return commonCompare(other); } - + @Override public int comparePriority(DroolsPdp other, String previousSite) { if (previousSite == null || previousSite.isEmpty()) { return comparePriority(other); } + return commonCompare(other); + } + + private int commonCompare(DroolsPdp other) { if (nullSafeCompare(this.getSiteName(),other.getSiteName()) == 0) { if (this.getPriority() != other.getPriority()) { return this.getPriority() - other.getPriority(); diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java index 85a0e3ab..cd8d369f 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java @@ -137,10 +137,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { if (feature.getResourceName().equals(myPdp.getPdpId())) { - if (logger.isDebugEnabled()) { - logger.debug("DroolsPdpsElectionHandler: Found StateManagementFeature" - + " with resourceName: {}", myPdp.getPdpId()); - } + logger.debug("DroolsPdpsElectionHandler: Found StateManagementFeature" + + " with resourceName: {}", myPdp.getPdpId()); stateManagementFeature = feature; break; } @@ -168,9 +166,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { * @param designated is designated value */ public static void setMyPdpDesignated(boolean designated) { - if (logger.isDebugEnabled()) { - logger.debug("setMyPdpDesignated: designated= {}", designated); - } + logger.debug("setMyPdpDesignated: designated= {}", designated); myPdp.setDesignated(designated); } @@ -181,24 +177,18 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { @Override public void run() { try { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: Entering"); - } + logger.debug("DesignatedWaiter.run: Entering"); //This is for testing the checkWaitTimer if (isUnitTesting && isStalled) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: isUnitTesting = {} isStalled = {}", - isUnitTesting, isStalled); - } + logger.debug("DesignatedWaiter.run: isUnitTesting = {} isStalled = {}", + isUnitTesting, isStalled); return; } synchronized (designationWaiterLock) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: Entering synchronized block"); - } + logger.debug("DesignatedWaiter.run: Entering synchronized block"); //It is possible that multiple PDPs are designated lead. So, we will make a list of all designated //PDPs and then decide which one really should be designated at the end. @@ -206,19 +196,13 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { Collection pdps = pdpsConnector.getDroolsPdps(); - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: pdps.size= {}", pdps.size()); - } + logger.debug("DesignatedWaiter.run: pdps.size= {}", pdps.size()); //This is only true if all designated PDPs have failed boolean designatedPdpHasFailed = pdpsConnector.hasDesignatedPdpFailed(pdps); - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: designatedPdpHasFailed= {}", designatedPdpHasFailed); - } + logger.debug("DesignatedWaiter.run: designatedPdpHasFailed= {}", designatedPdpHasFailed); for (DroolsPdp pdp : pdps) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: evaluating pdp ID: {}", pdp.getPdpId()); - } + logger.debug("DesignatedWaiter.run: evaluating pdp ID: {}", pdp.getPdpId()); /* * Note: side effect of isPdpCurrent is that any stale but @@ -238,9 +222,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { // single-node test environment. standbyStatus = StateManagement.COLD_STANDBY; } - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: PDP= {}, isCurrent= {}", pdp.getPdpId(), isCurrent); - } + logger.debug("DesignatedWaiter.run: PDP= {}, isCurrent= {}", pdp.getPdpId(), isCurrent); /* * There are 4 combinations of isDesignated and isCurrent. We will examine each one in-turn @@ -253,11 +235,9 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { //If so, we need to stand it down and demote it if (!standbyStatus.equals(StateManagement.PROVIDING_SERVICE)) { if (pdp.getPdpId().equals(myPdp.getPdpId())) { - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp {} is current and designated, " - + "butstandbystatus is not providingservice. " - + " Executing stateManagement.demote()" + "\n\n", myPdp.getPdpId()); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp {} is current and designated, " + + "butstandbystatus is not providingservice. " + + " Executing stateManagement.demote()" + "\n\n", myPdp.getPdpId()); // So, we must demote it try { //Keep the order like this. StateManagement is last since it @@ -285,23 +265,19 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } } else { // Don't demote a remote PDP that is current. It should catch itself - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp {} is current and designated, " - + "but standbystatus is not providingservice. " - + " Cannot execute stateManagement.demote() " - + "since it it is not myPdp\n\n", - myPdp.getPdpId()); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp {} is current and designated, " + + "but standbystatus is not providingservice. " + + " Cannot execute stateManagement.demote() " + + "since it it is not myPdp\n\n", + myPdp.getPdpId()); } } else { // If we get here, it is ok to be on the list - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: PDP= {} is designated, " - + "current and {} Noting PDP as " - + "designated, standbyStatus= {}", - pdp.getPdpId(), standbyStatus, standbyStatus); - } + logger.debug("DesignatedWaiter.run: PDP= {} is designated, " + + "current and {} Noting PDP as " + + "designated, standbyStatus= {}", + pdp.getPdpId(), standbyStatus, standbyStatus); listOfDesignated.add(pdp); } @@ -317,12 +293,10 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { * its standbyStatus is). None of these go on the list. */ if (pdp.isDesignated() && !isCurrent) { - if (logger.isDebugEnabled()) { - logger.debug("INFO: DesignatedWaiter.run: PDP= {} is currently " - + "designated but is not current; " - + "it has failed. Standing down. standbyStatus= {}", - pdp.getPdpId(), standbyStatus); - } + logger.debug("INFO: DesignatedWaiter.run: PDP= {} is currently " + + "designated but is not current; " + + "it has failed. Standing down. standbyStatus= {}", + pdp.getPdpId(), standbyStatus); /* * Changes designated to 0 but it is still potentially providing service * Will affect isDesignated, so, it can enter an if(combination) below @@ -331,10 +305,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { //need to change standbystatus to coldstandby if (pdp.getPdpId().equals(myPdp.getPdpId())) { - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp {} is not Current. " - + " Executing stateManagement.disableFailed()\n\n", myPdp.getPdpId()); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp {} is not Current. " + + " Executing stateManagement.disableFailed()\n\n", myPdp.getPdpId()); // We found that myPdp is designated but not current // So, we must cause it to disableFail try { @@ -348,11 +320,9 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { myPdp.getPdpId(), myPdp.getPdpId(), e); } } else { //it is a remote PDP that is failed - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: PDP {} is not Current. " - + " Executing stateManagement.disableFailed(otherResourceName)\n\n", - pdp.getPdpId() ); - } + logger.debug("\n\nDesignatedWaiter.run: PDP {} is not Current. " + + " Executing stateManagement.disableFailed(otherResourceName)\n\n", + pdp.getPdpId() ); // We found a PDP is designated but not current // We already called standdown(pdp) which will change designated to false // Now we need to disableFail it to get its states in synch. The standbyStatus @@ -379,20 +349,16 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { if (!pdp.isDesignated() && isCurrent) { if (!(standbyStatus.equals(StateManagement.HOT_STANDBY) || standbyStatus.equals(StateManagement.COLD_STANDBY))) { - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: PDP {}" - + " is NOT designated but IS current and" - + " has a standbystatus= {}", pdp.getPdpId(), standbyStatus); - } + logger.debug("\n\nDesignatedWaiter.run: PDP {}" + + " is NOT designated but IS current and" + + " has a standbystatus= {}", pdp.getPdpId(), standbyStatus); // Since it is current, we assume it can adjust its own state. // We will demote if it is myPdp if (pdp.getPdpId().equals(myPdp.getPdpId())) { //demote it - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: PDP {} going to " - + "setDesignated = false and calling stateManagement.demote", - pdp.getPdpId()); - } + logger.debug("DesignatedWaiter.run: PDP {} going to " + + "setDesignated = false and calling stateManagement.demote", + pdp.getPdpId()); try { //Keep the order like this. //StateManagement is last since it triggers controller shutdown @@ -414,12 +380,10 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } if (standbyStatus.equals(StateManagement.HOT_STANDBY) && designatedPdpHasFailed) { //add it to the list - if (logger.isDebugEnabled()) { - logger.debug("INFO: DesignatedWaiter.run: PDP= {}" - + " is not designated but is {} and designated PDP " - + "has failed. standbyStatus= {}", pdp.getPdpId(), - standbyStatus, standbyStatus); - } + logger.debug("INFO: DesignatedWaiter.run: PDP= {}" + + " is not designated but is {} and designated PDP " + + "has failed. standbyStatus= {}", pdp.getPdpId(), + standbyStatus, standbyStatus); listOfDesignated.add(pdp); } continue; //done with this one @@ -433,27 +397,24 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { * */ if (!pdp.isDesignated() && !isCurrent) { - if (logger.isDebugEnabled()) { - logger.debug("INFO: DesignatedWaiter.run: PDP= {} " - + "designated= {}, current= {}, " - + "designatedPdpHasFailed= {}, " - + "standbyStatus= {}",pdp.getPdpId(), - pdp.isDesignated(), isCurrent, designatedPdpHasFailed, standbyStatus); - } + logger.debug("INFO: DesignatedWaiter.run: PDP= {} " + + "designated= {}, current= {}, " + + "designatedPdpHasFailed= {}, " + + "standbyStatus= {}",pdp.getPdpId(), + pdp.isDesignated(), isCurrent, designatedPdpHasFailed, standbyStatus); if (!standbyStatus.equals(StateManagement.COLD_STANDBY)) { //stand it down //disableFail it pdpsConnector.standDownPdp(pdp.getPdpId()); if (pdp.getPdpId().equals(myPdp.getPdpId())) { /* - * I don't actually know how this condition could happen, - * but if it did, we would want - * to declare it failed. + * I don't actually know how this condition could + * happen, but if it did, we would want to declare it + * failed. */ - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp {} is !current and !designated, " - + " Executing stateManagement.disableFailed()\n\n", myPdp.getPdpId()); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp {} is !current and !designated, " + + " Executing stateManagement.disableFailed()\n\n", + myPdp.getPdpId()); // So, we must disableFail it try { //Keep the order like this. @@ -468,11 +429,9 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { myPdp.getPdpId(), myPdp.getPdpId(), e); } } else { //it is remote - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp {} is !current and !designated, " - + " Executing stateManagement.disableFailed({})\n\n", - myPdp.getPdpId(), pdp.getPdpId()); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp {} is !current and !designated, " + + " Executing stateManagement.disableFailed({})\n\n", + myPdp.getPdpId(), pdp.getPdpId()); // We already called standdown(pdp) which will change designated to false // Now we need to disableFail it to get its states in sync. // StandbyStatus = coldstandby @@ -541,19 +500,15 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { isDesignated = false; waitTimerLastRunDate = new Date(); - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run (designatedPdp == null) waitTimerLastRunDate = {}", - waitTimerLastRunDate); - } + logger.debug("DesignatedWaiter.run (designatedPdp == null) waitTimerLastRunDate = {}", + waitTimerLastRunDate); myPdp.setUpdatedDate(waitTimerLastRunDate); pdpsConnector.update(myPdp); return; } else if (designatedPdp.getPdpId().equals(myPdp.getPdpId())) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: designatedPdp is PDP={}", myPdp.getPdpId()); - } + logger.debug("DesignatedWaiter.run: designatedPdp is PDP={}", myPdp.getPdpId()); /* * update function expects myPdp.isDesignated to be true. */ @@ -601,10 +556,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } waitTimerLastRunDate = new Date(); - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run (designatedPdp.getPdpId().equals(myPdp.getPdpId())) " - + "waitTimerLastRunDate = " + waitTimerLastRunDate); - } + logger.debug("DesignatedWaiter.run (designatedPdp.getPdpId().equals(myPdp.getPdpId())) " + + "waitTimerLastRunDate = " + waitTimerLastRunDate); myPdp.setUpdatedDate(waitTimerLastRunDate); pdpsConnector.update(myPdp); @@ -613,15 +566,11 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { isDesignated = false; } // end synchronized - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: myPdp: {}; Returning, isDesignated= {}", - isDesignated, myPdp.getPdpId()); - } + logger.debug("DesignatedWaiter.run: myPdp: {}; Returning, isDesignated= {}", + isDesignated, myPdp.getPdpId()); Date tmpDate = new Date(); - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run (end of run) waitTimerLastRunDate = {}", tmpDate); - } + logger.debug("DesignatedWaiter.run (end of run) waitTimerLastRunDate = {}", tmpDate); waitTimerLastRunDate = tmpDate; myPdp.setUpdatedDate(waitTimerLastRunDate); @@ -645,10 +594,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { boolean containsHotStandby = false; List listForRemoval = new ArrayList<>(); for (DroolsPdp pdp : listOfDesignated) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run sanitizing: pdp = {}" - + " isDesignated = {}",pdp.getPdpId(), pdp.isDesignated()); - } + logger.debug("DesignatedWaiter.run sanitizing: pdp = {}" + + " isDesignated = {}",pdp.getPdpId(), pdp.isDesignated()); if (pdp.isDesignated()) { containsDesignated = true; } else { @@ -679,32 +626,22 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } DroolsPdp mostRecentPrimary = new DroolsPdpImpl(null, true, 1, new Date(0)); mostRecentPrimary.setSiteName(null); - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run listOfDesignated.size() = {}", listOfDesignated.size()); - } + logger.debug("DesignatedWaiter.run listOfDesignated.size() = {}", listOfDesignated.size()); if (listOfDesignated.size() <= 1) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWainter.run: listOfDesignated.size <=1"); - } + logger.debug("DesignatedWainter.run: listOfDesignated.size <=1"); //Only one or none is designated or hot standby. Choose the latest designated date for (DroolsPdp pdp : pdps) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run pdp = {}" - + " pdp.getDesignatedDate() = {}", - pdp.getPdpId(), pdp.getDesignatedDate()); - } + logger.debug("DesignatedWaiter.run pdp = {}" + + " pdp.getDesignatedDate() = {}", + pdp.getPdpId(), pdp.getDesignatedDate()); if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", - mostRecentPrimary.getPdpId()); - } + logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", + mostRecentPrimary.getPdpId()); } } } else if (listOfDesignated.size() == pdps.size()) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWainter.run: listOfDesignated.size = pdps.size() which is {}", pdps.size()); - } + logger.debug("DesignatedWainter.run: listOfDesignated.size = pdps.size() which is {}", pdps.size()); //They are all designated or all hot standby. mostRecentPrimary = null; for (DroolsPdp pdp : pdps) { @@ -715,28 +652,20 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { if (containsDesignated) { //Choose the site of the first designated date if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) < 0) { mostRecentPrimary = pdp; - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); - } + logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); } } else { //Choose the site with the latest designated date if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); - } + logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); } } } } else { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWainter.run: Some but not all are designated or hot standby. "); - } + logger.debug("DesignatedWainter.run: Some but not all are designated or hot standby. "); //Some but not all are designated or hot standby. if (containsDesignated) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWainter.run: containsDesignated = {}", containsDesignated); - } + logger.debug("DesignatedWainter.run: containsDesignated = {}", containsDesignated); /* * The list only contains designated. This is a problem. It is most likely a race * condition that resulted in two thinking they should be designated. Choose the @@ -750,22 +679,16 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { } if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); - } + logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); } } } else { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWainter.run: containsDesignated = {}", containsDesignated); - } + logger.debug("DesignatedWainter.run: containsDesignated = {}", containsDesignated); //The list only contains hot standby. Choose the site of the latest designated date for (DroolsPdp pdp : pdps) { if (pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0) { mostRecentPrimary = pdp; - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); - } + logger.debug("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); } } } @@ -784,10 +707,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { DroolsPdp designatedPdp = null; DroolsPdp lowestPriorityPdp = null; if (listOfDesignated.size() > 1) { - if (logger.isDebugEnabled()) { - logger.debug("DesignatedWaiter.run: myPdp: {} listOfDesignated.size(): {}", myPdp.getPdpId(), - listOfDesignated.size()); - } + logger.debug("DesignatedWaiter.run: myPdp: {} listOfDesignated.size(): {}", myPdp.getPdpId(), + listOfDesignated.size()); DroolsPdp rejectedPdp = null; DroolsPdp lowestPrioritySameSite = null; DroolsPdp lowestPriorityDifferentSite = null; @@ -804,21 +725,17 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { continue;//nothing to compare } if (pdp.comparePriority(lowestPrioritySameSite) < 0) { - if (logger.isDebugEnabled()) { - logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}" - + " has lower priority than pdp ID: {}",myPdp.getPdpId(), pdp.getPdpId(), - lowestPrioritySameSite.getPdpId()); - } + logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}" + + " has lower priority than pdp ID: {}",myPdp.getPdpId(), pdp.getPdpId(), + lowestPrioritySameSite.getPdpId()); //we need to reject lowestPrioritySameSite rejectedPdp = lowestPrioritySameSite; lowestPrioritySameSite = pdp; } else { //we need to reject pdp and keep lowestPrioritySameSite - if (logger.isDebugEnabled()) { - logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {} " - + " has higher priority than pdp ID: {}", myPdp.getPdpId(),pdp.getPdpId(), - lowestPrioritySameSite.getPdpId()); - } + logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {} " + + " has higher priority than pdp ID: {}", myPdp.getPdpId(),pdp.getPdpId(), + lowestPrioritySameSite.getPdpId()); rejectedPdp = pdp; } } @@ -835,21 +752,17 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { continue;//nothing to compare } if (pdp.comparePriority(lowestPriorityDifferentSite) < 0) { - if (logger.isDebugEnabled()) { - logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}" - + " has lower priority than pdp ID: {}", myPdp.getPdpId(), pdp.getPdpId(), - lowestPriorityDifferentSite.getPdpId()); - } + logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}" + + " has lower priority than pdp ID: {}", myPdp.getPdpId(), pdp.getPdpId(), + lowestPriorityDifferentSite.getPdpId()); //we need to reject lowestPriorityDifferentSite rejectedPdp = lowestPriorityDifferentSite; lowestPriorityDifferentSite = pdp; } else { //we need to reject pdp and keep lowestPriorityDifferentSite - if (logger.isDebugEnabled()) { - logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}" - + " has higher priority than pdp ID: {}", myPdp.getPdpId(), pdp.getPdpId(), - lowestPriorityDifferentSite.getPdpId()); - } + logger.debug("\nDesignatedWaiter.run: myPdp {} listOfDesignated pdp ID: {}" + + " has higher priority than pdp ID: {}", myPdp.getPdpId(), pdp.getPdpId(), + lowestPriorityDifferentSite.getPdpId()); rejectedPdp = pdp; } } @@ -857,12 +770,10 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { // If the rejectedPdp is myPdp, we need to stand it down and demote it. Each pdp is responsible // for demoting itself if (rejectedPdp != null && nullSafeEquals(rejectedPdp.getPdpId(),myPdp.getPdpId())) { - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp: {} listOfDesignated myPdp ID: {}" - + " is NOT the lowest priority. Executing stateManagement.demote()\n\n", - myPdp.getPdpId(), - myPdp.getPdpId()); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp: {} listOfDesignated myPdp ID: {}" + + " is NOT the lowest priority. Executing stateManagement.demote()\n\n", + myPdp.getPdpId(), + myPdp.getPdpId()); // We found that myPdp is on the listOfDesignated and it is not the lowest priority // So, we must demote it try { @@ -896,24 +807,18 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { lowestPriorityPdp = lowestPriorityDifferentSite; } //now we have a valid value for lowestPriorityPdp - if (logger.isDebugEnabled()) { - logger.debug("\n\nDesignatedWaiter.run: myPdp: {} listOfDesignated " - + "found the LOWEST priority pdp ID: {} " - + " It is now the designatedPpd from the perspective of myPdp ID: {} \n\n", - myPdp.getPdpId(), lowestPriorityPdp.getPdpId(), myPdp); - } + logger.debug("\n\nDesignatedWaiter.run: myPdp: {} listOfDesignated " + + "found the LOWEST priority pdp ID: {} " + + " It is now the designatedPpd from the perspective of myPdp ID: {} \n\n", + myPdp.getPdpId(), lowestPriorityPdp.getPdpId(), myPdp); designatedPdp = lowestPriorityPdp; } else if (listOfDesignated.isEmpty()) { - if (logger.isDebugEnabled()) { - logger.debug("\nDesignatedWaiter.run: myPdp: {} listOfDesignated is: EMPTY.", myPdp.getPdpId()); - } + logger.debug("\nDesignatedWaiter.run: myPdp: {} listOfDesignated is: EMPTY.", myPdp.getPdpId()); designatedPdp = null; } else { //only one in listOfDesignated - if (logger.isDebugEnabled()) { - logger.debug("\nDesignatedWaiter.run: myPdp: {} listOfDesignated " - + "has ONE entry. PDP ID: {}", myPdp.getPdpId(), listOfDesignated.get(0).getPdpId()); - } + logger.debug("\nDesignatedWaiter.run: myPdp: {} listOfDesignated " + + "has ONE entry. PDP ID: {}", myPdp.getPdpId(), listOfDesignated.get(0).getPdpId()); designatedPdp = listOfDesignated.get(0); } return designatedPdp; @@ -925,16 +830,12 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { @Override public void run() { try { - if (logger.isDebugEnabled()) { - logger.debug("TimerUpdateClass.run: entry"); - } + logger.debug("TimerUpdateClass.run: entry"); checkWaitTimer(); } catch (Exception e) { logger.error("TimerUpdateClass.run caught an unexpected exception: ", e); } - if (logger.isDebugEnabled()) { - logger.debug("TimerUpdateClass.run.exit"); - } + logger.debug("TimerUpdateClass.run.exit"); } } @@ -946,9 +847,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { private void checkWaitTimer() { synchronized (checkWaitTimerLock) { try { - if (logger.isDebugEnabled()) { - logger.debug("checkWaitTimer: entry"); - } + logger.debug("checkWaitTimer: entry"); Date now = new Date(); long nowMs = now.getTime(); long waitTimerMs = waitTimerLastRunDate.getTime(); @@ -957,9 +856,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { if ((nowMs - waitTimerMs) > 10 * pdpUpdateInterval) { if (allSeemsWell == null || allSeemsWell) { allSeemsWell = false; - if (logger.isDebugEnabled()) { - logger.debug("checkWaitTimer: calling allSeemsWell with ALLNOTWELL param"); - } + logger.debug("checkWaitTimer: calling allSeemsWell with ALLNOTWELL param"); stateManagementFeature.allSeemsWell(this.getClass().getName(), StateManagementFeatureApi.ALLNOTWELL_STATE, "DesignationWaiter/ElectionHandler has STALLED"); @@ -974,9 +871,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker { "DesignationWaiter/ElectionHandler has RESUMED"); logger.info("DesignationWaiter/ElectionHandler has RESUMED"); } - if (logger.isDebugEnabled()) { - logger.debug("checkWaitTimer: exit"); - } + logger.debug("checkWaitTimer: exit"); } catch (Exception e) { logger.error("checkWaitTimer: caught unexpected exception: ", e); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java index 04448052..30952af1 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * feature-active-standby-management * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * 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. @@ -36,17 +36,17 @@ import org.slf4j.LoggerFactory; public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { - // get an instance of logger + // get an instance of logger private static final Logger logger = LoggerFactory.getLogger(JpaDroolsPdpsConnector.class); private EntityManagerFactory emf; - //not sure if we want to use the same entity manager factory + //not sure if we want to use the same entity manager factory //for drools session and pass it in here, or create a new one public JpaDroolsPdpsConnector(EntityManagerFactory emf) { this.emf = emf; } - + @Override public Collection getDroolsPdps() { //return a list of all the DroolsPdps in the database @@ -96,9 +96,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { @Override public void update(DroolsPdp pdp) { - if (logger.isDebugEnabled()) { - logger.debug("update: Entering, pdpId={}", pdp.getPdpId()); - } + logger.debug("update: Entering, pdpId={}", pdp.getPdpId()); //this is to update our own pdp in the database EntityManager em = emf.createEntityManager(); @@ -123,17 +121,13 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { logger.error("Could not get PDP timeout property, using default.", e); } boolean isCurrent = difference < pdpTimeout; - if (logger.isDebugEnabled()) { - logger.debug("update: PDP= {}, isCurrent={}" - + " difference= {}" - + ", pdpTimeout= {}, designated= {}", - pdp.getPdpId(), isCurrent, difference, pdpTimeout, droolsPdpEntity.isDesignated()); - } + logger.debug("update: PDP= {}, isCurrent={}" + + " difference= {}" + + ", pdpTimeout= {}, designated= {}", + pdp.getPdpId(), isCurrent, difference, pdpTimeout, droolsPdpEntity.isDesignated()); } else { - if (logger.isDebugEnabled()) { - logger.debug("update: For PDP={}" - + ", instantiating new DroolsPdpEntity", pdp.getPdpId()); - } + logger.debug("update: For PDP={}" + + ", instantiating new DroolsPdpEntity", pdp.getPdpId()); droolsPdpEntity = new DroolsPdpEntity(); em.persist(droolsPdpEntity); droolsPdpEntity.setPdpId(pdp.getPdpId()); @@ -149,14 +143,12 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { } if (droolsPdpEntity.isDesignated() != pdp.isDesignated()) { - if (logger.isDebugEnabled()) { - logger.debug("update: pdpId={}" - + ", pdp.isDesignated={}" - + ", droolsPdpEntity.pdpId= {}" - + ", droolsPdpEntity.isDesignated={}", - pdp.getPdpId(), pdp.isDesignated(), - droolsPdpEntity.getPdpId(), droolsPdpEntity.isDesignated()); - } + logger.debug("update: pdpId={}" + + ", pdp.isDesignated={}" + + ", droolsPdpEntity.pdpId= {}" + + ", droolsPdpEntity.isDesignated={}", + pdp.getPdpId(), pdp.isDesignated(), + droolsPdpEntity.getPdpId(), droolsPdpEntity.isDesignated()); droolsPdpEntity.setDesignated(pdp.isDesignated()); //The isDesignated value is not the same and the new one == true if (pdp.isDesignated()) { @@ -168,14 +160,12 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { cleanup(em, "update"); } - if (logger.isDebugEnabled()) { - logger.debug("update: Exiting"); - } + logger.debug("update: Exiting"); } /* - * Note: A side effect of this boolean method is that if the PDP is designated but not current, the + * Note: A side effect of this boolean method is that if the PDP is designated but not current, the * droolspdpentity.DESIGNATED column will be set to false (the PDP will be un-designated, i.e. marked as * being in standby mode) */ @@ -193,23 +183,19 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { List droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE) .setFlushMode(FlushModeType.COMMIT).getResultList(); if (droolsPdpsList.size() == 1 && droolsPdpsList.get(0) instanceof DroolsPdpEntity) { - if (logger.isDebugEnabled()) { - logger.debug("isPdpCurrent: PDP={} designated but not current; setting designated to false", - pdp.getPdpId()); - } + logger.debug("isPdpCurrent: PDP={} designated but not current; setting designated to false", + pdp.getPdpId()); DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity)droolsPdpsList.get(0); droolsPdpEntity.setDesignated(false); em.getTransaction().commit(); } else { logger.warn("isPdpCurrent: PDP={} is designated but not current; " - + "however it does not have a DB entry, so cannot set DESIGNATED to false!", + + "however it does not have a DB entry, so cannot set DESIGNATED to false!", pdp.getPdpId()); } } else { - if (logger.isDebugEnabled()) { - logger.debug("isPdpCurrent: For PDP= {}, " - + "designated={}, isCurrent={}", pdp.getPdpId(), pdp.isDesignated(), isCurrent); - } + logger.debug("isPdpCurrent: For PDP= {}, " + + "designated={}, isCurrent={}", pdp.getPdpId(), pdp.isDesignated(), isCurrent); } } catch (Exception e) { logger.error("Could not update expired record marked as designated in the database", e); @@ -223,10 +209,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { @Override public void setDesignated(DroolsPdp pdp, boolean designated) { - if (logger.isDebugEnabled()) { - logger.debug("setDesignated: Entering, pdpId={}" - + ", designated={}", pdp.getPdpId(), designated); - } + logger.debug("setDesignated: Entering, pdpId={}" + + ", designated={}", pdp.getPdpId(), designated); EntityManager em = null; try { @@ -242,16 +226,14 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList .get(0); - if (logger.isDebugEnabled()) { - logger.debug("setDesignated: PDP={}" - + " found, designated= {}" - + ", setting to {}", pdp.getPdpId(), droolsPdpEntity.isDesignated(), - designated); - } + logger.debug("setDesignated: PDP={}" + + " found, designated= {}" + + ", setting to {}", pdp.getPdpId(), droolsPdpEntity.isDesignated(), + designated); droolsPdpEntity.setDesignated(designated); if (designated) { em.refresh(droolsPdpEntity); //make sure we get the DB value - if (!droolsPdpEntity.isDesignated()) { + if (!droolsPdpEntity.isDesignated()) { droolsPdpEntity.setDesignatedDate(new Date()); } @@ -267,18 +249,14 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { cleanup(em, "setDesignated"); } - if (logger.isDebugEnabled()) { - logger.debug("setDesignated: Exiting"); - } + logger.debug("setDesignated: Exiting"); } @Override public void standDownPdp(String pdpId) { - if (logger.isDebugEnabled()) { - logger.debug("standDownPdp: Entering, pdpId={}", pdpId); - } + logger.debug("standDownPdp: Entering, pdpId={}", pdpId); EntityManager em = null; try { @@ -303,9 +281,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0); droolsPdpEntity.setDesignated(false); em.persist(droolsPdpEntity); - if (logger.isDebugEnabled()) { - logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId ); - } + logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId ); } else { logger.error("standDownPdp: Missing record in droolspdpentity for pdpId={}" + "; cannot stand down PDP", pdpId); @@ -328,24 +304,20 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { } finally { cleanup(em, "standDownPdp"); } - if (logger.isDebugEnabled()) { - logger.debug("standDownPdp: Exiting"); - } + logger.debug("standDownPdp: Exiting"); } /* * Determines whether or not a designated PDP has failed. - * + * * Note: The update method, which is run periodically by the * TimerUpdateClass, will un-designate a PDP that is stale. */ @Override public boolean hasDesignatedPdpFailed(Collection pdps) { - if (logger.isDebugEnabled()) { - logger.debug("hasDesignatedPdpFailed: Entering, pdps.size()={}", pdps.size()); - } + logger.debug("hasDesignatedPdpFailed: Entering, pdps.size()={}", pdps.size()); boolean failed = true; boolean foundDesignatedPdp = false; @@ -356,40 +328,32 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { * Normally, the update method will un-designate any stale PDP, but * we check here to see if the PDP has gone stale since the update * method was run. - * + * * Even if we determine that the designated PDP is current, we keep * going (we don't break), so we can get visibility into the other * PDPs, when in DEBUG mode. */ if (pdp.isDesignated() && isCurrent(pdp)) { - if (logger.isDebugEnabled()) { - logger.debug("hasDesignatedPdpFailed: Designated PDP={} is current", pdp.getPdpId()); - } + logger.debug("hasDesignatedPdpFailed: Designated PDP={} is current", pdp.getPdpId()); failed = false; foundDesignatedPdp = true; } else if (pdp.isDesignated() && !isCurrent(pdp)) { logger.error("hasDesignatedPdpFailed: Designated PDP={} has failed", pdp.getPdpId()); foundDesignatedPdp = true; } else { - if (logger.isDebugEnabled()) { - logger.debug("hasDesignatedPdpFailed: PDP={} is not designated", pdp.getPdpId()); - } + logger.debug("hasDesignatedPdpFailed: PDP={} is not designated", pdp.getPdpId()); } } - if (logger.isDebugEnabled()) { - logger.debug("hasDesignatedPdpFailed: Exiting and returning, foundDesignatedPdp={}", - foundDesignatedPdp); - } + logger.debug("hasDesignatedPdpFailed: Exiting and returning, foundDesignatedPdp={}", + foundDesignatedPdp); return failed; } private boolean isCurrent(DroolsPdp pdp) { - if (logger.isDebugEnabled()) { - logger.debug("isCurrent: Entering, pdpId={}", pdp.getPdpId()); - } + logger.debug("isCurrent: Entering, pdpId={}", pdp.getPdpId()); boolean current = false; @@ -405,18 +369,14 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { try { pdpTimeout = Long.parseLong(ActiveStandbyProperties .getProperty(ActiveStandbyProperties.PDP_TIMEOUT)); - if (logger.isDebugEnabled()) { - logger.debug("isCurrent: pdp.timeout={}", pdpTimeout); - } + logger.debug("isCurrent: pdp.timeout={}", pdpTimeout); } catch (Exception e) { logger.error("isCurrent: Could not get PDP timeout property, using default.", e); } current = difference < pdpTimeout; - if (logger.isDebugEnabled()) { - logger.debug("isCurrent: Exiting, difference={}, pdpTimeout={}" - + "; returning current={}", difference, pdpTimeout, current); - } + logger.debug("isCurrent: Exiting, difference={}, pdpTimeout={}" + + "; returning current={}", difference, pdpTimeout, current); return current; } @@ -429,9 +389,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { @Override public DroolsPdpEntity getPdp(String pdpId) { - if (logger.isDebugEnabled()) { - logger.debug("getPdp: Entering and getting PDP with pdpId={}", pdpId); - } + logger.debug("getPdp: Entering and getting PDP with pdpId={}", pdpId); DroolsPdpEntity droolsPdpEntity = null; @@ -447,14 +405,12 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { if (droolsPdpsList.size() == 1 && droolsPdpsList.get(0) instanceof DroolsPdpEntity) { droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0); - if (logger.isDebugEnabled()) { - logger.debug("getPdp: PDP={}" - + " found, isDesignated={}," - + " updatedDate={}, " - + "priority={}", pdpId, - droolsPdpEntity.isDesignated(), droolsPdpEntity.getUpdatedDate(), - droolsPdpEntity.getPriority()); - } + logger.debug("getPdp: PDP={}" + + " found, isDesignated={}," + + " updatedDate={}, " + + "priority={}", pdpId, + droolsPdpEntity.isDesignated(), droolsPdpEntity.getUpdatedDate(), + droolsPdpEntity.getPriority()); // Make sure the droolsPdpEntity is not a cached version em.refresh(droolsPdpEntity); @@ -469,9 +425,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { cleanup(em, "getPdp"); } - if (logger.isDebugEnabled()) { - logger.debug("getPdp: Returning droolsPdpEntity={}", droolsPdpEntity); - } + logger.debug("getPdp: Returning droolsPdpEntity={}", droolsPdpEntity); return droolsPdpEntity; } @@ -482,9 +436,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { */ @Override public void insertPdp(DroolsPdp pdp) { - if (logger.isDebugEnabled()) { - logger.debug("insertPdp: Entering and manually inserting PDP"); - } + logger.debug("insertPdp: Entering and manually inserting PDP"); /* * Start transaction @@ -511,9 +463,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { } finally { cleanup(em, "insertPdp"); } - if (logger.isDebugEnabled()) { - logger.debug("insertPdp: Exiting"); - } + logger.debug("insertPdp: Exiting"); } @@ -524,9 +474,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { @Override public void deleteAllPdps() { - if (logger.isDebugEnabled()) { - logger.debug("deleteAllPdps: Entering"); - } + logger.debug("deleteAllPdps: Entering"); /* * Start transaction @@ -540,9 +488,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { @SuppressWarnings("unchecked") List droolsPdpsList = droolsPdpsListQuery.setLockMode( LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); - if (logger.isDebugEnabled()) { - logger.debug("deleteAllPdps: Deleting {} PDPs", droolsPdpsList.size()); - } + logger.debug("deleteAllPdps: Deleting {} PDPs", droolsPdpsList.size()); for (DroolsPdp droolsPdp : droolsPdpsList) { String pdpId = droolsPdp.getPdpId(); deletePdp(pdpId); @@ -555,9 +501,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { } finally { cleanup(em, "deleteAllPdps"); } - if (logger.isDebugEnabled()) { - logger.debug("deleteAllPdps: Exiting"); - } + logger.debug("deleteAllPdps: Exiting"); } @@ -567,9 +511,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { */ @Override public void deletePdp(String pdpId) { - if (logger.isDebugEnabled()) { - logger.debug("deletePdp: Entering and manually deleting pdpId={}", pdpId); - } + logger.debug("deletePdp: Entering and manually deleting pdpId={}", pdpId); /* * Start transaction @@ -583,14 +525,10 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { */ DroolsPdpEntity droolsPdpEntity = em.find(DroolsPdpEntity.class, pdpId); if (droolsPdpEntity != null) { - if (logger.isDebugEnabled()) { - logger.debug("deletePdp: Removing PDP"); - } + logger.debug("deletePdp: Removing PDP"); em.remove(droolsPdpEntity); } else { - if (logger.isDebugEnabled()) { - logger.debug("deletePdp: PDP with ID={} not currently in DB", pdpId); - } + logger.debug("deletePdp: PDP with ID={} not currently in DB", pdpId); } /* @@ -600,9 +538,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { } finally { cleanup(em, "deletePdp"); } - if (logger.isDebugEnabled()) { - logger.debug("deletePdp: Exiting"); - } + logger.debug("deletePdp: Exiting"); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java index 9da5d42e..bdd9a958 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.java @@ -7,9 +7,9 @@ * 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. @@ -20,23 +20,23 @@ package org.onap.policy.drools.activestandby; -/* +/* * Per MultiSite_v1-10.ppt: - * - * Extends the StateChangeNotifier class and overwrites the abstract handleStateChange() method to get state changes - * and do the following: - * - * When the Standby Status changes (from providingservice) to hotstandby or coldstandby, - * the Active/Standby selection algorithm must stand down if the PDP-D is currently the lead/active node + * + * Extends the StateChangeNotifier class and overwrites the abstract handleStateChange() method to get state changes + * and do the following: + * + * When the Standby Status changes (from providingservice) to hotstandby or coldstandby, + * the Active/Standby selection algorithm must stand down if the PDP-D is currently the lead/active node * and allow another PDP-D to take over. It must also call lock on all engines in the engine management. - * - * When the Standby Status changes from (hotstandby) to coldstandby, the Active/Standby algorithm must NOT assume + * + * When the Standby Status changes from (hotstandby) to coldstandby, the Active/Standby algorithm must NOT assume * the active/lead role. - * - * When the Standby Status changes (from coldstandby or providingservice) to hotstandby, + * + * When the Standby Status changes (from coldstandby or providingservice) to hotstandby, * the Active/Standby algorithm may assume the active/lead role if the active/lead fails. - * - * When the Standby Status changes to providingservice (from hotstandby or coldstandby) call unlock on all + * + * When the Standby Status changes to providingservice (from hotstandby or coldstandby) call unlock on all * engines in the engine management layer. */ import java.util.Date; @@ -52,27 +52,27 @@ import org.slf4j.LoggerFactory; /* * Some background: * - * Originally, there was a "StandbyStateChangeNotifier" that belonged to policy-core, and this class's - * handleStateChange() method used to take care of invoking conn.standDownPdp(). - * - * But testing revealed that when a state change to hot standby - * occurred from a demote() operation, first the PMStandbyStateChangeNotifier.handleStateChange() method - * would be invoked and then the StandbyStateChangeNotifier.handleStateChange() method would be invoked, + * Originally, there was a "StandbyStateChangeNotifier" that belonged to policy-core, and this class's + * handleStateChange() method used to take care of invoking conn.standDownPdp(). + * + * But testing revealed that when a state change to hot standby + * occurred from a demote() operation, first the PMStandbyStateChangeNotifier.handleStateChange() method + * would be invoked and then the StandbyStateChangeNotifier.handleStateChange() method would be invoked, * and this ordering was creating the following problem: * - * When PMStandbyStateChangeNotifier.handleStateChange() was invoked it would take a long time to finish, - * because it would result in SingleThreadedUebTopicSource.stop() being invoked, which can potentially do a + * When PMStandbyStateChangeNotifier.handleStateChange() was invoked it would take a long time to finish, + * because it would result in SingleThreadedUebTopicSource.stop() being invoked, which can potentially do a * 5 second sleep for each controller being stopped. - * - * Meanwhile, as these controller stoppages and their associated sleeps were occurring, the election handler - * would discover the demoted PDP in hotstandby (but still designated!) and promote it, resulting in the - * standbyStatus going from hotstandby to providingservice. So then, by the time that + * + * Meanwhile, as these controller stoppages and their associated sleeps were occurring, the election handler + * would discover the demoted PDP in hotstandby (but still designated!) and promote it, resulting in the + * standbyStatus going from hotstandby to providingservice. So then, by the time that * PMStandbyStateChangeNotifier.handleStateChange() finished its work and - * StandbyStateChangeNotifier.handleStateChange() started executing, the standbyStatus was no longer hotstandby - * (as effected by the demote), but providingservice (as reset by the election handling logic) and + * StandbyStateChangeNotifier.handleStateChange() started executing, the standbyStatus was no longer hotstandby + * (as effected by the demote), but providingservice (as reset by the election handling logic) and * conn.standDownPdp() would not get called! * - * To fix this bug, we consolidated StandbyStateChangeNotifier and PMStandbyStateChangeNotifier, + * To fix this bug, we consolidated StandbyStateChangeNotifier and PMStandbyStateChangeNotifier, * with the standDownPdp() always * being invoked prior to the TopicEndpoint.manager.lock(). In this way, when the election handling logic is invoked * during the controller stoppages, the PDP is in hotstandby and the standdown occurs. @@ -94,7 +94,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { /** * Constructor. - * + * */ public PmStandbyStateChangeNotifier() { pdpUpdateInterval = @@ -114,47 +114,29 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { * stateManagememt, has synchronize all of its methods. Only one stateManagement operation * can occur at a time. Thus, only one handleStateChange() call will ever be made at a time. */ - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: Entering, message={}, standbyStatus={}", super.getMessage(), - super.getStateManagement().getStandbyStatus()); - } + logger.debug("handleStateChange: Entering, message={}, standbyStatus={}", super.getMessage(), + super.getStateManagement().getStandbyStatus()); String standbyStatus = super.getStateManagement().getStandbyStatus(); String pdpId = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: previousStandbyStatus = {}; standbyStatus = {}", - previousStandbyStatus, standbyStatus); - } + logger.debug("handleStateChange: previousStandbyStatus = {}; standbyStatus = {}", + previousStandbyStatus, standbyStatus); if (standbyStatus == null || standbyStatus.equals(StateManagement.NULL_VALUE)) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: standbyStatus is null; standing down PDP={}", pdpId); - } + logger.debug("handleStateChange: standbyStatus is null; standing down PDP={}", pdpId); if (previousStandbyStatus.equals(StateManagement.NULL_VALUE)) { // We were just here and did this successfully - if (logger.isDebugEnabled()) { - logger.debug( - "handleStateChange: " - + "Is returning because standbyStatus is null and was previously 'null'; PDP={}", - pdpId); - } + logger.debug("handleStateChange: " + + "Is returning because standbyStatus is null and was previously 'null'; PDP={}", + pdpId); return; } isWaitingForActivation = false; try { - try { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: null: cancelling delayActivationTimer."); - } - delayActivateTimer.cancel(); - } catch (Exception e) { - if (logger.isInfoEnabled()) { - logger.info("handleStateChange: null no delayActivationTimer existed.", e); - } - // If you end of here, there was no active timer - } + logger.debug("handleStateChange: null: cancelling delayActivationTimer."); + cancelTimer(); // Only want to lock the endpoints, not the controllers. - PolicyEngine.manager.deactivate(); + getPolicyEngineManager().deactivate(); // The operation was fully successful, but you cannot assign it a real null value // because later we might try to execute previousStandbyStatus.equals() and get // a null pointer exception. @@ -164,34 +146,19 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { } } else if (standbyStatus.equals(StateManagement.HOT_STANDBY) || standbyStatus.equals(StateManagement.COLD_STANDBY)) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: standbyStatus={}; standing down PDP={}", standbyStatus, pdpId); - } + logger.debug("handleStateChange: standbyStatus={}; standing down PDP={}", standbyStatus, pdpId); if (previousStandbyStatus.equals(PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)) { // We were just here and did this successfully - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: Is returning because standbyStatus is {}" - + " and was previously {}; PDP= {}", standbyStatus, previousStandbyStatus, pdpId); - } + logger.debug("handleStateChange: Is returning because standbyStatus is {}" + + " and was previously {}; PDP= {}", standbyStatus, previousStandbyStatus, pdpId); return; } isWaitingForActivation = false; try { - try { - if (logger.isDebugEnabled()) { - logger.debug( - "handleStateChange: HOT_STNDBY || COLD_STANDBY: cancelling delayActivationTimer."); - } - delayActivateTimer.cancel(); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: HOT_STANDBY || COLD_STANDBY no delayActivationTimer existed.", - e); - } - // If you end of here, there was no active timer - } + logger.debug("handleStateChange: HOT_STNDBY || COLD_STANDBY: cancelling delayActivationTimer."); + cancelTimer(); // Only want to lock the endpoints, not the controllers. - PolicyEngine.manager.deactivate(); + getPolicyEngineManager().deactivate(); // The operation was fully successful previousStandbyStatus = PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY; } catch (Exception e) { @@ -200,33 +167,25 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { } } else if (standbyStatus.equals(StateManagement.PROVIDING_SERVICE)) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: standbyStatus= {} scheduling activation of PDP={}", standbyStatus, - pdpId); - } + logger.debug("handleStateChange: standbyStatus= {} scheduling activation of PDP={}", standbyStatus, + pdpId); if (previousStandbyStatus.equals(StateManagement.PROVIDING_SERVICE)) { // We were just here and did this successfully - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: Is returning because standbyStatus is {}" - + "and was previously {}; PDP={}", standbyStatus, previousStandbyStatus, pdpId); - } + logger.debug("handleStateChange: Is returning because standbyStatus is {}" + + "and was previously {}; PDP={}", standbyStatus, previousStandbyStatus, pdpId); return; } try { // UnLock all the endpoints - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: standbyStatus={}; controllers must be unlocked.", standbyStatus); - } + logger.debug("handleStateChange: standbyStatus={}; controllers must be unlocked.", standbyStatus); /* * Only endpoints should be unlocked. Controllers have not been locked. Because, * sometimes, it is possible for more than one PDP-D to become active (race * conditions) we need to delay the activation of the topic endpoint interfaces to * give the election algorithm time to resolve the conflict. */ - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: PROVIDING_SERVICE isWaitingForActivation= {}", - isWaitingForActivation); - } + logger.debug("handleStateChange: PROVIDING_SERVICE isWaitingForActivation= {}", + isWaitingForActivation); // Delay activation for 2*pdpUpdateInterval+2000 ms in case of an election handler // conflict. @@ -234,26 +193,19 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { // First let's check that the timer has not died if (isWaitingForActivation) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: PROVIDING_SERVICE isWaitingForActivation = {}", - isWaitingForActivation); - } + logger.debug("handleStateChange: PROVIDING_SERVICE isWaitingForActivation = {}", + isWaitingForActivation); long now = new Date().getTime(); long waitTimeMs = now - startTimeWaitingForActivationMs; if (waitTimeMs > 3 * waitInterval) { - if (logger.isDebugEnabled()) { - logger.debug( - "handleStateChange: PROVIDING_SERVICE looks like the activation wait timer may be hung," - + " waitTimeMs = {} and allowable waitInterval = {}" - + " Checking whether it is currently in activation. isNowActivating = {}", - waitTimeMs, waitInterval, isNowActivating); - } + logger.debug("handleStateChange: PROVIDING_SERVICE looks like the activation wait timer " + + "may be hung, waitTimeMs = {} and allowable waitInterval = {}" + + " Checking whether it is currently in activation. isNowActivating = {}", + waitTimeMs, waitInterval, isNowActivating); // Now check that it is not currently executing an activation if (!isNowActivating) { - if (logger.isDebugEnabled()) { - logger.debug( - "handleStateChange: PROVIDING_SERVICE looks like the activation wait timer died"); - } + logger.debug("handleStateChange: PROVIDING_SERVICE looks like the activation " + + "wait timer died"); // This will assure the timer is cancelled and rescheduled. isWaitingForActivation = false; } @@ -262,32 +214,19 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { } if (!isWaitingForActivation) { - try { - // Just in case there is an old timer hanging around - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: PROVIDING_SERVICE cancelling delayActivationTimer."); - } - delayActivateTimer.cancel(); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: PROVIDING_SERVICE no delayActivationTimer existed.", e); - } - // If you end of here, there was no active timer - } - delayActivateTimer = new Timer(); + // Just in case there is an old timer hanging around + logger.debug("handleStateChange: PROVIDING_SERVICE cancelling delayActivationTimer."); + cancelTimer(); + delayActivateTimer = makeTimer(); // delay the activate so the DesignatedWaiter can run twice delayActivateTimer.schedule(new DelayActivateClass(), waitInterval); isWaitingForActivation = true; startTimeWaitingForActivationMs = new Date().getTime(); - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: PROVIDING_SERVICE scheduling delayActivationTimer in {} ms", - waitInterval); - } + logger.debug("handleStateChange: PROVIDING_SERVICE scheduling delayActivationTimer in {} ms", + waitInterval); } else { - if (logger.isDebugEnabled()) { - logger.debug( - "handleStateChange: PROVIDING_SERVICE delayActivationTimer is waiting for activation."); - } + logger.debug("handleStateChange: PROVIDING_SERVICE delayActivationTimer is " + + "waiting for activation."); } } catch (Exception e) { @@ -299,28 +238,16 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { logger.error("handleStateChange: Unsupported standbyStatus={}; standing down PDP={}", standbyStatus, pdpId); if (previousStandbyStatus.equals(PmStandbyStateChangeNotifier.UNSUPPORTED)) { // We were just here and did this successfully - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: Is returning because standbyStatus is " - + "UNSUPPORTED and was previously {}; PDP={}", previousStandbyStatus, pdpId); - } + logger.debug("handleStateChange: Is returning because standbyStatus is " + + "UNSUPPORTED and was previously {}; PDP={}", previousStandbyStatus, pdpId); return; } // Only want to lock the endpoints, not the controllers. isWaitingForActivation = false; try { - try { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: unsupported standbystatus: cancelling delayActivationTimer."); - } - delayActivateTimer.cancel(); - } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: unsupported standbystatus: no delayActivationTimer existed.", - e); - } - // If you end of here, there was no active timer - } - PolicyEngine.manager.deactivate(); + logger.debug("handleStateChange: unsupported standbystatus: cancelling delayActivationTimer."); + cancelTimer(); + getPolicyEngineManager().deactivate(); // We know the standbystatus is unsupported previousStandbyStatus = PmStandbyStateChangeNotifier.UNSUPPORTED; } catch (Exception e) { @@ -328,8 +255,12 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { standbyStatus, e.getMessage(), e); } } - if (logger.isDebugEnabled()) { - logger.debug("handleStateChange: Exiting"); + logger.debug("handleStateChange: Exiting"); + } + + private void cancelTimer() { + if (delayActivateTimer != null) { + delayActivateTimer.cancel(); } } @@ -342,20 +273,16 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { public void run() { isNowActivating = true; try { - if (logger.isDebugEnabled()) { - logger.debug("DelayActivateClass.run: entry"); - } + logger.debug("DelayActivateClass.run: entry"); synchronized (delayActivateLock) { - PolicyEngine.manager.activate(); + getPolicyEngineManager().activate(); // The state change fully succeeded previousStandbyStatus = StateManagement.PROVIDING_SERVICE; // We want to set this to false here because the activate call can take a while isWaitingForActivation = false; isNowActivating = false; } - if (logger.isDebugEnabled()) { - logger.debug("DelayActivateClass.run.exit"); - } + logger.debug("DelayActivateClass.run.exit"); } catch (Exception e) { isWaitingForActivation = false; isNowActivating = false; @@ -368,4 +295,14 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier { public String getPreviousStandbyStatus() { return previousStandbyStatus; } + + // these may be overridden by junit tests + + protected PolicyEngine getPolicyEngineManager() { + return PolicyEngine.manager; + } + + protected Timer makeTimer() { + return new Timer(); + } } diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/ActiveStandbyPropertiesTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/ActiveStandbyPropertiesTest.java new file mode 100644 index 00000000..058aa5e8 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/ActiveStandbyPropertiesTest.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.drools.activestandby; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; + +import java.util.Properties; +import org.junit.Before; +import org.junit.Test; + +public class ActiveStandbyPropertiesTest { + + private Properties props; + + /** + * Initializes objects. + */ + @Before + public void setUp() { + props = new Properties(); + props.setProperty("abc", "hello"); + props.setProperty("def", "world"); + } + + @Test + public void testInitProperties_testGetProperty_testGetProperties() { + ActiveStandbyProperties.initProperties(props); + + assertSame(props, ActiveStandbyProperties.getProperties()); + + assertEquals("hello", ActiveStandbyProperties.getProperty("abc")); + assertEquals("world", ActiveStandbyProperties.getProperty("def")); + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java new file mode 100644 index 00000000..310f9110 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/DroolsPdpObjectTest.java @@ -0,0 +1,153 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.drools.activestandby; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import lombok.Getter; +import lombok.Setter; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.drools.activestandby.DroolsPdp; +import org.onap.policy.drools.activestandby.DroolsPdpObject; + +public class DroolsPdpObjectTest { + private static final String PDP_ID = "my-id"; + private static final String PDP_ID2 = "my-id2"; + private static final String SITE = "my-site"; + private static final String SITE2 = "my-site2"; + private static final int PRIORITY = 11; + private static final int PRIORITY2 = 12; + + private MyPdp pdp; + + @Before + public void setUp() { + pdp = makePdp(PDP_ID, SITE, PRIORITY); + } + + @Test + public void testEqualsObject() { + // self + assertTrue(pdp.equals(pdp)); + + // same id + MyPdp pdp2 = new MyPdp(); + pdp2.setPdpId(PDP_ID); + assertTrue(pdp.equals(pdp2)); + + // different id + pdp2.setPdpId(PDP_ID2); + assertFalse(pdp.equals(pdp2)); + + // different type of object + assertFalse(pdp.equals("")); + } + + @Test + public void testNullSafeCompare() { + // self, when null + pdp.setSiteName(null); + assertEquals(0, pdp.comparePriority(pdp)); + + // both null + MyPdp pdp2 = makePdp(PDP_ID, null, PRIORITY); + assertEquals(0, pdp.comparePriority(pdp2)); + + // left null + pdp2 = makePdp(PDP_ID, SITE, PRIORITY); + assertEquals(-1, pdp.comparePriority(pdp2)); + + // right null - note: args are reversed + pdp2 = makePdp(PDP_ID, SITE, PRIORITY); + assertEquals(1, pdp2.comparePriority(pdp)); + } + + @Test + public void testComparePriorityDroolsPdp() { + // self + assertEquals(0, pdp.comparePriority(pdp)); + + // same + MyPdp pdp2 = makePdp(PDP_ID, SITE, PRIORITY); + assertEquals(0, pdp.comparePriority(pdp2)); + + // different site + pdp2 = makePdp(PDP_ID, SITE2, PRIORITY); + assertEquals(SITE.compareTo(SITE2), pdp.comparePriority(pdp2)); + + // different priority + pdp2 = makePdp(PDP_ID, SITE, PRIORITY2); + assertEquals(PRIORITY - PRIORITY2, pdp.comparePriority(pdp2)); + + // different id + pdp2 = makePdp(PDP_ID2, SITE, PRIORITY); + assertEquals(PDP_ID.compareTo(PDP_ID2), pdp.comparePriority(pdp2)); + } + + @Test + public void testComparePriorityDroolsPdpString() { + final int result = 1000; + + // override other comparison method so we know if it's called + MyPdp pdp2 = new MyPdp() { + @Override + public int comparePriority(DroolsPdp other) { + return result; + } + }; + + pdp2.setPdpId(PDP_ID); + pdp2.setSiteName(SITE2); + pdp2.setPriority(PRIORITY); + + // should use overridden comparison method + assertEquals(result, pdp2.comparePriority(pdp, null)); + assertEquals(result, pdp2.comparePriority(pdp, "")); + + // should use normal comparison method + assertEquals(SITE2.compareTo(SITE), pdp2.comparePriority(pdp, SITE)); + } + + private MyPdp makePdp(String id, String site, int priority) { + MyPdp pdp2 = new MyPdp(); + + pdp2.setSiteName(site); + pdp2.setPdpId(id); + pdp2.setPriority(priority); + + return pdp2; + } + + @Getter + @Setter + private class MyPdp extends DroolsPdpObject { + private String pdpId; + private boolean designated; + private int priority; + private Date updatedDate; + private String siteName; + private Date designatedDate; + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java new file mode 100644 index 00000000..28d3b439 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java @@ -0,0 +1,284 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.drools.activestandby; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.drools.system.PolicyEngine; + +public class PmStandbyStateChangeNotifierTest { + private static final String UNSUPPORTED_STATUS = "unsupported status"; + private static final String PDP_ID = "my-pdp"; + private static final long UPDATE_INTERVAL = 100; + private static final long WAIT_INTERVAL = 2 * UPDATE_INTERVAL + 2000; + + @Mock + private PolicyEngine engmgr; + + @Mock + private Timer timer; + + @Mock + private StateManagement mgmt; + + private PmStandbyStateChangeNotifier notifier; + + /** + * Initializes the properties. + */ + @BeforeClass + public static void setUpBeforeClass() { + Properties props = new Properties(); + props.setProperty(ActiveStandbyProperties.NODE_NAME, PDP_ID); + props.setProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL, String.valueOf(UPDATE_INTERVAL)); + + ActiveStandbyProperties.initProperties(props); + } + + /** + * Initializes objects, including the notifier. + */ + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + notifier = new MyNotifier(); + } + + @Test + public void testHandleStateChange_Null() { + notifier.update(mgmt, null); + verify(engmgr).deactivate(); + assertEquals(StateManagement.NULL_VALUE, notifier.getPreviousStandbyStatus()); + + // repeat - nothing else should be done + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.NULL_VALUE); + notifier.update(mgmt, null); + verify(engmgr, times(1)).deactivate(); + assertEquals(StateManagement.NULL_VALUE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_Null_Ex() { + doThrow(new MyException()).when(engmgr).deactivate(); + + // should not throw an exception + notifier.update(mgmt, null); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_HotOrCold() { + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.HOT_STANDBY); + notifier.update(mgmt, null); + verify(engmgr).deactivate(); + assertEquals(PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY, notifier.getPreviousStandbyStatus()); + + // repeat - nothing else should be done + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.COLD_STANDBY); + notifier.update(mgmt, null); + verify(engmgr, times(1)).deactivate(); + assertEquals(PmStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_HotOrCold_Ex() { + doThrow(new MyException()).when(engmgr).deactivate(); + + // should not throw an exception + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.HOT_STANDBY); + notifier.update(mgmt, null); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_ProvidingService() { + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); + notifier.update(mgmt, null); + verify(engmgr, never()).activate(); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(TimerTask.class); + verify(timer).schedule(captor.capture(), eq(WAIT_INTERVAL)); + + // execute the timer task + captor.getValue().run(); + + verify(engmgr).activate(); + assertEquals(StateManagement.PROVIDING_SERVICE, notifier.getPreviousStandbyStatus()); + + // repeat - nothing else should be done + notifier.update(mgmt, null); + verify(engmgr, never()).deactivate(); + verify(engmgr, times(1)).activate(); + verify(timer, times(1)).schedule(captor.capture(), eq(WAIT_INTERVAL)); + assertEquals(StateManagement.PROVIDING_SERVICE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_ProvidingService_BeforeActivation() { + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); + notifier.update(mgmt, null); + + // repeat - nothing else should be done + notifier.update(mgmt, null); + verify(engmgr, never()).deactivate(); + verify(engmgr, never()).activate(); + + verify(timer, times(1)).schedule(any(), eq(WAIT_INTERVAL)); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_ProvidingService_Ex() { + notifier = new MyNotifier() { + @Override + protected Timer makeTimer() { + throw new MyException(); + } + }; + + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); + notifier.update(mgmt, null); + + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_Unsupported() { + when(mgmt.getStandbyStatus()).thenReturn(UNSUPPORTED_STATUS); + notifier.update(mgmt, null); + + verify(engmgr).deactivate(); + assertEquals(PmStandbyStateChangeNotifier.UNSUPPORTED, notifier.getPreviousStandbyStatus()); + + // repeat - nothing else should be done + notifier.update(mgmt, null); + verify(engmgr, times(1)).deactivate(); + assertEquals(PmStandbyStateChangeNotifier.UNSUPPORTED, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testHandleStateChange_Unsupported_Ex() { + doThrow(new MyException()).when(engmgr).deactivate(); + + // should not throw an exception + when(mgmt.getStandbyStatus()).thenReturn(UNSUPPORTED_STATUS); + notifier.update(mgmt, null); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testCancelTimer() { + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); + notifier.update(mgmt, null); + + when(mgmt.getStandbyStatus()).thenReturn(null); + notifier.update(mgmt, null); + + verify(timer).cancel(); + } + + @Test + public void testDelayActivateClass() { + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); + notifier.update(mgmt, null); + verify(engmgr, never()).activate(); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(TimerTask.class); + verify(timer).schedule(captor.capture(), eq(WAIT_INTERVAL)); + + // execute the timer task + captor.getValue().run(); + + verify(engmgr).activate(); + assertEquals(StateManagement.PROVIDING_SERVICE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testDelayActivateClass_Ex() { + when(mgmt.getStandbyStatus()).thenReturn(StateManagement.PROVIDING_SERVICE); + notifier.update(mgmt, null); + verify(engmgr, never()).activate(); + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(TimerTask.class); + verify(timer).schedule(captor.capture(), eq(WAIT_INTERVAL)); + + doThrow(new MyException()).when(engmgr).activate(); + + // execute the timer task + captor.getValue().run(); + + assertEquals(PmStandbyStateChangeNotifier.NONE, notifier.getPreviousStandbyStatus()); + } + + @Test + public void testGetPolicyEngineManager() { + // use real object with real method - no exception expected + new PmStandbyStateChangeNotifier().getPolicyEngineManager(); + } + + @Test + public void testMakeTimer() { + // use real object with real method + new PmStandbyStateChangeNotifier().makeTimer().cancel(); + } + + private class MyNotifier extends PmStandbyStateChangeNotifier { + @Override + protected PolicyEngine getPolicyEngineManager() { + return engmgr; + } + + @Override + protected Timer makeTimer() { + return timer; + } + } + + private static class MyException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public MyException() { + super("expected exception"); + } + } +} diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java index 719fb62f..b5b89941 100644 --- a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/AllSeemsWellTest.java @@ -235,7 +235,7 @@ public class AllSeemsWellTest { // discovered by the ActiveStandbyFeature when the election handler initializes. StateManagementFeatureApi stateManagementFeatureApi = null; - for (StateManagementFeatureApi feature : stateManagementFeatureApi.impl.getList()) { + for (StateManagementFeatureApi feature : StateManagementFeatureApi.impl.getList()) { ((PolicySessionFeatureApi) feature).globalInit(null, configDir); stateManagementFeatureApi = feature; logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", -- cgit 1.2.3-korg