diff options
86 files changed, 7242 insertions, 344 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..30e60521 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +.DS_Store +.project +.settings +.classpath +.jupiter +.pydevproject +*.swp +*.log +*.out +.metadata/ +target/ +*/logs/ +*/sql/ +*/testingLogs/ +*/config/ diff --git a/api-active-standby-management/pom.xml b/api-active-standby-management/pom.xml new file mode 100644 index 00000000..581acae0 --- /dev/null +++ b/api-active-standby-management/pom.xml @@ -0,0 +1,49 @@ +<!-- + ============LICENSE_START======================================================= + ECOMP Policy Engine - Drools PDP + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>drools-pdp</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>api-active-standby-management</artifactId> + + <name>api-active-standby-management</name> + <description>API for Active Standby Management feature</description> + + <properties> + <maven.compiler.source>1.8</maven.compiler.source> + <maven.compiler.target>1.8</maven.compiler.target> + </properties> + + <dependencies> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>policy-management</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + </dependencies> +</project> diff --git a/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureAPI.java b/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureAPI.java new file mode 100644 index 00000000..ef02c617 --- /dev/null +++ b/api-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeatureAPI.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * api-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import org.onap.policy.drools.utils.OrderedService; +import org.onap.policy.drools.utils.OrderedServiceImpl; + +/** + * This interface provides a way to invoke optional features at various + * points in the code. At appropriate points in the + * application, the code iterates through this list, invoking these optional + * methods. + */ +public interface ActiveStandbyFeatureAPI extends OrderedService +{ + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects + * implementing the 'FeatureAPI' interface. + */ + public static OrderedServiceImpl<ActiveStandbyFeatureAPI> impl = + new OrderedServiceImpl<>(ActiveStandbyFeatureAPI.class); + + /** + * This method returns the resourceName (PDP ID) for the Drools-PDP that is + * currently designated as active. + * + * @return String (resourceName) + */ + public String getPdpdNowActive(); + + /** + * This method returns the resourceName (PDP ID) for the Drools-PDP that was + * previously designated as active. + * + * @return String (resourceName) + */ + public String getPdpdLastActive(); + + /** + * This method returns the resourceName associated with this instance of the feature + * @return String (resourceName) + */ + public String getResourceName(); + +} diff --git a/feature-active-standby-management/pom.xml b/feature-active-standby-management/pom.xml new file mode 100644 index 00000000..824b38ed --- /dev/null +++ b/feature-active-standby-management/pom.xml @@ -0,0 +1,136 @@ +<!-- + ============LICENSE_START======================================================= + feature-active-standby-management + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>drools-pdp</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> + + <artifactId>feature-active-standby-management</artifactId> + + <name>feature-active-standby-management</name> + <description>Separately loadable module for managing active-standby behavior</description> + + <build> + <plugins> + <plugin> + <artifactId>maven-assembly-plugin</artifactId> + <version>2.6</version> + <executions> + <execution> + <id>zipfile</id> + <goals> + <goal>single</goal> + </goals> + <phase>package</phase> + <configuration> + <attach>true</attach> + <finalName>${project.artifactId}-${project.version}</finalName> + <descriptors> + <descriptor>src/assembly/assemble_zip.xml</descriptor> + </descriptors> + <appendAssemblyId>false</appendAssemblyId> + </configuration> + </execution> + </executions> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-dependency-plugin</artifactId> + <version>2.8</version> + <executions> + <execution> + <id>copy-dependencies</id> + <goals> + <goal>copy-dependencies</goal> + </goals> + <phase>prepare-package</phase> + <configuration> + <transitive>false</transitive> + <outputDirectory>${project.build.directory}/assembly/lib</outputDirectory> + <overWriteReleases>false</overWriteReleases> + <overWriteSnapshots>true</overWriteSnapshots> + <overWriteIfNewer>true</overWriteIfNewer> + <useRepositoryLayout>false</useRepositoryLayout> + <addParentPoms>false</addParentPoms> + <copyPom>false</copyPom> + <includeScope>runtime</includeScope> + <excludeTransitive>true</excludeTransitive> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + + <dependencies> + <dependency> + <groupId>io.swagger</groupId> + <artifactId>swagger-jersey2-jaxrs</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>policy-core</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>policy-management</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.eclipse.persistence</groupId> + <artifactId>eclipselink</artifactId> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>api-active-standby-management</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>api-state-management</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>feature-state-management</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <version>[1.4.186,)</version> + <scope>test</scope> + </dependency> + </dependencies> + +</project> diff --git a/feature-active-standby-management/src/assembly/assemble_zip.xml b/feature-active-standby-management/src/assembly/assemble_zip.xml new file mode 100644 index 00000000..97b82ac2 --- /dev/null +++ b/feature-active-standby-management/src/assembly/assemble_zip.xml @@ -0,0 +1,76 @@ +<!-- + ============LICENSE_START======================================================= + feature-active-standby- management + ================================================================================ + 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========================================================= + --> + +<!-- Defines how we build the .zip file which is our distribution. --> + +<assembly + xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd"> + <id>feature-active-standby-management</id> + <formats> + <format>zip</format> + </formats> + + <!-- we want "system" and related files right at the root level as this + file is suppose to be unzip on top of a karaf distro. --> + <includeBaseDirectory>false</includeBaseDirectory> + + <fileSets> + <fileSet> + <directory>target</directory> + <outputDirectory>lib/feature</outputDirectory> + <includes> + <include>feature-active-standby-management-${project.version}.jar</include> + </includes> + </fileSet> + <fileSet> + <directory>target/assembly/lib</directory> + <outputDirectory>lib/dependencies</outputDirectory> + <includes> + <include>*.jar</include> + </includes> + </fileSet> + <fileSet> + <directory>src/main/feature/config</directory> + <outputDirectory>config</outputDirectory> + <fileMode>0644</fileMode> + <excludes/> + </fileSet> + <fileSet> + <directory>src/main/feature/bin</directory> + <outputDirectory>bin</outputDirectory> + <fileMode>0744</fileMode> + <excludes/> + </fileSet> + <fileSet> + <directory>src/main/feature/db</directory> + <outputDirectory>db</outputDirectory> + <fileMode>0744</fileMode> + <excludes/> + </fileSet> + <fileSet> + <directory>src/main/feature/install</directory> + <outputDirectory>install</outputDirectory> + <fileMode>0744</fileMode> + <excludes/> + </fileSet> + </fileSets> +</assembly> diff --git a/feature-active-standby-management/src/main/feature/config/feature-active-standby-management.properties b/feature-active-standby-management/src/main/feature/config/feature-active-standby-management.properties new file mode 100644 index 00000000..d9fd6ca3 --- /dev/null +++ b/feature-active-standby-management/src/main/feature/config/feature-active-standby-management.properties @@ -0,0 +1,39 @@ +### +# ============LICENSE_START======================================================= +# feature-active-standby-management +# ================================================================================ +# 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========================================================= +### + +# DB properties +javax.persistence.jdbc.driver=org.mariadb.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mariadb://${{SQL_HOST}}:3306/activestandbymanagement +javax.persistence.jdbc.user=${{SQL_USER}} +javax.persistence.jdbc.password=${{SQL_PASSWORD}} + +# Must be unique across the system +resource.name=pdp1 +# Name of the site in which this node is hosted +site_name=site1 + +# Needed by DroolsPdpsElectionHandler +pdp.checkInterval=1500 +pdp.updateInterval=1000 +#pdp.timeout=3000 +# Need long timeout, because testTransaction is only run every 10 seconds. +pdp.timeout=15000 +#how long do we wait for the pdp table to populate on initial startup +pdp.initialWait=20000
\ No newline at end of file diff --git a/feature-active-standby-management/src/main/feature/db/activestandbymanagement/sql/18020-activestandbymanagement.upgrade.sql b/feature-active-standby-management/src/main/feature/db/activestandbymanagement/sql/18020-activestandbymanagement.upgrade.sql new file mode 100644 index 00000000..4b3375ad --- /dev/null +++ b/feature-active-standby-management/src/main/feature/db/activestandbymanagement/sql/18020-activestandbymanagement.upgrade.sql @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * 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========================================================= + */ + +set foreign_key_checks=0; + +CREATE TABLE if not exists activestandbymanagement.DROOLSPDPENTITY +( +pdpId VARCHAR(255) NOT NULL, +designated TINYINT(1) default 0 NOT NULL, +priority INTEGER NOT NULL, +site VARCHAR(50), +updatedDate TIMESTAMP NOT NULL, +designatedDate TIMESTAMP NOT NULL, +PRIMARY KEY (pdpId) +); + +set foreign_key_checks=1;
\ No newline at end of file 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 new file mode 100644 index 00000000..d40a9e0f --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.policy.drools.core.PolicySessionFeatureAPI; +import org.onap.policy.drools.features.PolicyEngineFeatureAPI; +import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.PropertyUtil; + +/** + * If this feature is supported, there is a single instance of it. + * It adds persistence to Drools sessions, but it is also intertwined with + * active/standby state management and IntegrityMonitor. For now, they are + * all treated as a single feature, but it would be nice to separate them. + * + * The bulk of the code here was once in other classes, such as + * 'PolicyContainer' and 'Main'. It was moved here as part of making this + * a separate optional feature. + */ +public class ActiveStandbyFeature implements ActiveStandbyFeatureAPI, + PolicySessionFeatureAPI, PolicyEngineFeatureAPI +{ + // get an instance of logger + private static final Logger logger = + LoggerFactory.getLogger(ActiveStandbyFeature.class); + + private static DroolsPdp myPdp; + private static Object myPdpSync = new Object(); + private static DroolsPdpsElectionHandler electionHandler; + + private StateManagementFeatureAPI stateManagementFeature; + + public static final int SEQ_NUM = 1; + + + /**************************/ + /* 'FeatureAPI' interface */ + /**************************/ + + /** + * {@inheritDoc} + */ + @Override + public int getSequenceNumber() + { + return(SEQ_NUM); + } + + /** + * {@inheritDoc} + */ + @Override + public void globalInit(String args[], String configDir) + { + // This must come first since it initializes myPdp + initializePersistence(configDir); + + 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()); + } + 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.error("ActiveStandbyFeature failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", myPdp.getPdpId()); + } + + + + //Create an instance of the Observer + PMStandbyStateChangeNotifier pmNotifier = new PMStandbyStateChangeNotifier(); + + //Register the PMStandbyStateChangeNotifier Observer + stateManagementFeature.addObserver(pmNotifier); + if(logger.isDebugEnabled()){ + logger.debug("ActiveStandbyFeature.globalInit() exit"); + } + } + + + /** + * {@inheritDoc} + */ + @Override + public boolean afterStart(PolicyEngine engine) + { + // ASSERTION: engine == PolicyEngine.manager + PolicyEngine.manager.lock(); + return false; + } + + /** + * Read in the persistence properties, determine whether persistence is + * enabled or disabled, and initialize persistence if enabled. + */ + private static void initializePersistence(String configDir) + { + //Get the Active Standby properties + try { + Properties activeStandbyProperties = + PropertyUtil.getProperties(configDir + "/feature-active-standby-management.properties"); + ActiveStandbyProperties.initProperties(activeStandbyProperties); + logger.info("initializePersistence: ActiveStandbyProperties success"); + } catch (IOException e) { + logger.error("ActiveStandbyFeature: initializePersistence ActiveStandbyProperties", e); + } + + DroolsPdpsConnector conn = getDroolsPdpsConnector("activeStandbyPU"); + String resourceName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); + if(resourceName == null){ + throw new NullPointerException(); + } + + /* + * In a JUnit test environment, one or more PDPs may already have been + * inserted in the DB, so we need to check for this. + */ + DroolsPdp existingPdp = conn.getPdp(resourceName); + if (existingPdp != null) { + System.out.println("Found existing PDP record, pdpId=" + + existingPdp.getPdpId() + ", isDesignated=" + + existingPdp.isDesignated() + ", updatedDate=" + + existingPdp.getUpdatedDate()); + myPdp = existingPdp; + } + + synchronized(myPdpSync){ + if(myPdp == null){ + + myPdp = new DroolsPdpImpl(resourceName,false,4,new Date()); + } + if(myPdp != null){ + String site_name = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.SITE_NAME); + if (site_name == null) { + site_name = ""; + }else{ + site_name = site_name.trim(); + } + myPdp.setSiteName(site_name); + } + if(electionHandler == null){ + electionHandler = new DroolsPdpsElectionHandler(conn,myPdp); + } + } + System.out.println("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n"); + logger.info("\n\nThis controller is a standby, waiting to be chosen as primary...\n\n"); + } + + + /* + * Moved code to instantiate a JpaDroolsPdpsConnector object from main() to + * this method, so it can also be accessed from StandbyStateChangeNotifier + * class. + */ + public static DroolsPdpsConnector getDroolsPdpsConnector(String pu) { + + Map<String, Object> propMap = new HashMap<String, Object>(); + propMap.put("javax.persistence.jdbc.driver", ActiveStandbyProperties + .getProperty(ActiveStandbyProperties.DB_DRIVER)); + propMap.put("javax.persistence.jdbc.url", + ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_URL)); + propMap.put("javax.persistence.jdbc.user", ActiveStandbyProperties + .getProperty(ActiveStandbyProperties.DB_USER)); + propMap.put("javax.persistence.jdbc.password", + ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_PWD)); + + EntityManagerFactory emf = Persistence.createEntityManagerFactory( + pu, propMap); + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emf); + + return conn; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPdpdNowActive(){ + return electionHandler.getPdpdNowActive(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getPdpdLastActive(){ + return electionHandler.getPdpdLastActive(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getResourceName() { + return myPdp.getPdpId(); + } +} 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 new file mode 100644 index 00000000..6e26334b --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyProperties.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ActiveStandbyProperties { + // get an instance of logger + private static final Logger logger = LoggerFactory.getLogger(ActiveStandbyProperties.class); + + public static final String PDP_CHECK_INVERVAL = "pdp.checkInterval"; + public static final String PDP_UPDATE_INTERVAL = "pdp.updateInterval"; + public static final String PDP_TIMEOUT = "pdp.timeout"; + public static final String PDP_INITIAL_WAIT_PERIOD = "pdp.initialWait"; + + public static final String NODE_NAME = "resource.name"; + public static final String SITE_NAME = "site_name"; + + /* + * feature-active-standby-management.properties parameter key values + */ + public static final String DB_DRIVER = "javax.persistence.jdbc.driver"; + public static final String DB_URL = "javax.persistence.jdbc.url"; + public static final String DB_USER = "javax.persistence.jdbc.user"; + public static final String DB_PWD = "javax.persistence.jdbc.password"; + + private static Properties properties = null; + /* + * 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). + * + */ + public static void initProperties (Properties prop){ + logger.info("ActiveStandbyProperties.initProperties(Properties): entry"); + logger.info("\n\nActiveStandbyProperties.initProperties: Properties = \n{}\n\n", prop); + + properties = prop; + } + + public static String getProperty(String key){ + return properties.getProperty(key); + } + + public static Properties getProperties() { + return properties; + } +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java new file mode 100644 index 00000000..a440a7e1 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdp.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.Date; + +public interface DroolsPdp { + + public String getPdpId(); + public boolean isDesignated(); + public int getPriority(); + public Date getUpdatedDate(); + public void setDesignated(boolean isDesignated); + public void setUpdatedDate(Date updatedDate); + public int comparePriority(DroolsPdp other); + public int comparePriority(DroolsPdp other,String previousSite); + public String getSiteName(); + public void setSiteName(String siteName); + public Date getDesignatedDate(); + public void setDesignatedDate(Date designatedDate); +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java new file mode 100644 index 00000000..ec1ce579 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpEntity.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.onap.policy.drools.activestandby.DroolsPdpObject; + +@Entity +//@Table(name="DroolsPdpEntity") + +@NamedQueries({ + @NamedQuery(name="DroolsPdpEntity.findAll", query="SELECT e FROM DroolsPdpEntity e "), + @NamedQuery(name="DroolsPdpEntity.deleteAll", query="DELETE FROM DroolsPdpEntity WHERE 1=1") +}) +public class DroolsPdpEntity extends DroolsPdpObject implements Serializable{ + + private static final long serialVersionUID = 1L; + + @Id + @Column(name="pdpId", nullable=false) + private String pdpId="-1"; + + @Column(name="designated", nullable=false) + private boolean designated=false; + + @Column(name="priority", nullable=false) + private int priority=0; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="updatedDate", nullable=false) + private Date updatedDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="designatedDate",nullable=false) + private Date designatedDate; + + @Column(name="site", nullable=true, length = 50) + private String site; + + + public DroolsPdpEntity(){ + updatedDate = new Date(); + //When this is translated to a TimeStamp in MySQL, it assumes the date is relative + //to the local timezone. So, a value of Date(0) is actually Dec 31 18:00:00 CST 1969 + //which is an invalid value for the MySql TimeStamp + designatedDate = new Date(864000000); + } + + @Override + public String getPdpId() { + return this.pdpId; + } + + public void setPdpId(String pdpId) { + this.pdpId = pdpId; + } + + @Override + public boolean isDesignated() { + return this.designated; + } + + @Override + public int getPriority() { + return this.priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + @Override + public Date getUpdatedDate() { + return this.updatedDate; + } + + @Override + public void setDesignated(boolean isDesignated) { + this.designated=isDesignated; + } + + @Override + public void setUpdatedDate(Date updatedDate) { + this.updatedDate=updatedDate; + } + + + @Override + public String getSiteName() { + return site; + } + + @Override + public void setSiteName(String siteName) { + site = siteName; + + } + + @Override + public Date getDesignatedDate() { + return designatedDate; + } + + @Override + public void setDesignatedDate(Date designatedDate) { + this.designatedDate = designatedDate; + } + +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java new file mode 100644 index 00000000..141d5857 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.Date; + +public class DroolsPdpImpl extends DroolsPdpObject { + + private boolean designated; + private int priority; + private Date updatedDate; + private Date designatedDate; + private String pdpId; + private String site; + + public DroolsPdpImpl(String pdpId, boolean designated, int priority, Date updatedDate){ + this.pdpId = pdpId; + this.designated = designated; + this.priority = priority; + this.updatedDate = updatedDate; + //When this is translated to a TimeStamp in MySQL, it assumes the date is relative + //to the local timezone. So, a value of Date(0) is actually Dec 31 18:00:00 CST 1969 + //which is an invalid value for the MySql TimeStamp + this.designatedDate = new Date(864000000); + + } + @Override + public boolean isDesignated() { + + return designated; + } + + @Override + public int getPriority() { + return priority; + } + @Override + public void setUpdatedDate(Date date){ + this.updatedDate = date; + } + @Override + public Date getUpdatedDate() { + return updatedDate; + } + + @Override + public String getPdpId() { + return pdpId; + } + @Override + public void setDesignated(boolean isDesignated) { + this.designated = isDesignated; + + } + + @Override + public String getSiteName() { + return site; + } + @Override + public void setSiteName(String siteName) { + this.site = siteName; + + } + @Override + public Date getDesignatedDate() { + return designatedDate; + } + @Override + public void setDesignatedDate(Date designatedDate) { + this.designatedDate = designatedDate; + + } +} 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 new file mode 100644 index 00000000..e434c834 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + + +public abstract class DroolsPdpObject implements DroolsPdp{ + + @Override + public boolean equals(Object other){ + if(other instanceof DroolsPdp){ + return this.getPdpId().equals(((DroolsPdp)other).getPdpId()); + }else{ + return false; + } + } + private int nullSafeCompare(String one, String two){ + if(one != null && two != null){ + return one.compareTo(two); + } + if(one == null && two != null){ + return -1; + } + 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()); + } + } + @Override + public int comparePriority(DroolsPdp other, String previousSite){ + if(previousSite == null || previousSite.equals("")){ + return comparePriority(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()); + } + } +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsConnector.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsConnector.java new file mode 100644 index 00000000..d0d33f0f --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsConnector.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.Collection; + +public interface DroolsPdpsConnector { + + + //return a list of PDPs, NOT including this PDP + public Collection<DroolsPdp> getDroolsPdps(); + + public void update(DroolsPdp pdp); + + //determines if the DroolsPdp parameter is considered "current" or expired (has it been too long since the Pdp sent an update) + public boolean isPdpCurrent(DroolsPdp pdp); + + // Updates DESIGNATED boolean in PDP record. + public void setDesignated(DroolsPdp pdp, boolean designated); + + // Marks droolspdpentity.DESIGNATED=false, so another PDP-D will go active. + public void standDownPdp(String pdpId); + + // This is used in a JUnit test environment to manually + // insert a PDP + public void insertPdp(DroolsPdp pdp); + + // This is used in a JUnit test environment to manually + // delete a PDP + public void deletePdp(String pdpId); + + // This is used in a JUnit test environment to manually + // clear the droolspdpentity table. + public void deleteAllPdps(); + + // This is used in a JUnit test environment to manually + // get a PDP + public DroolsPdpEntity getPdp(String pdpId); + + // Used by DroolsPdpsElectionHandler to determine if the currently designated + // PDP has failed. + public boolean hasDesignatedPdpFailed(Collection<DroolsPdp> pdps); + + +} 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 new file mode 100644 index 00000000..6edf11f8 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java @@ -0,0 +1,1076 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.Timer; +import java.util.TimerTask; + +import org.onap.policy.common.im.StateManagement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI; + +public class DroolsPdpsElectionHandler implements ThreadRunningChecker { + // get an instance of logger + private final static Logger logger = LoggerFactory.getLogger(DroolsPdpsElectionHandler.class); + private DroolsPdpsConnector pdpsConnector; + private Object pdpsConnectorLock = new Object(); + private Object checkUpdateWorkerLock = new Object(); + private Object checkWaitTimerLock = new Object(); + private Object designationWaiterLock = new Object(); + + /* + * Must be static, so it can be referenced by JpaDroolsPdpsConnector, + * without requiring a reference to the election handler instantiation. + */ + private static DroolsPdp myPdp; + + private DesignationWaiter designationWaiter; + private Timer updateWorker; + private Timer waitTimer; + private Date updateWorkerLastRunDate; + private Date waitTimerLastRunDate; + private int pdpCheckInterval; + private int pdpUpdateInterval; + private volatile boolean isDesignated; + + private String pdpdNowActive; + private String pdpdLastActive; + + private StateManagementFeatureAPI stateManagementFeature; + + public DroolsPdpsElectionHandler(DroolsPdpsConnector pdps, DroolsPdp myPdp){ + pdpdNowActive = null; + pdpdLastActive = null; + this.pdpsConnector = pdps; + DroolsPdpsElectionHandler.myPdp = myPdp; + this.isDesignated = false; + pdpCheckInterval = 3000; + try{ + pdpCheckInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_CHECK_INVERVAL)); + }catch(Exception e){ + logger.error + ("Could not get pdpCheckInterval property. Using default", e); + } + pdpUpdateInterval = 2000; + try{ + pdpUpdateInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL)); + }catch(Exception e){ + logger.error + ("Could not get pdpUpdateInterval property. Using default", e); + } + + Date now = new Date(); + + // Retrieve the ms since the epoch + long nowMs = now.getTime(); + + // Create the timer which will update the updateDate in DroolsPdpEntity table. + // This is the heartbeat + updateWorker = new Timer(); + + // Schedule the heartbeat to start in 100 ms and run at pdpCheckInterval ms thereafter + // NOTE: The first run of the TimerUpdateClass results in myPdp being added to the + // drools droolsPdpEntity table. + updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval); + updateWorkerLastRunDate = new Date(nowMs + 100); + + // Create the timer which will run the election algorithm + waitTimer = new Timer(); + + // Schedule it to start in startMs ms (so it will run after the updateWorker and run at pdpUpdateInterval ms thereafter + long startMs = getDWaiterStartMs(); + designationWaiter = new DesignationWaiter(); + waitTimer.scheduleAtFixedRate(designationWaiter, startMs, pdpUpdateInterval); + waitTimerLastRunDate = new Date(nowMs + startMs); + + //Get the StateManagementFeature instance + + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + if (feature.getResourceName().equals(myPdp.getPdpId())) + { + if(logger.isDebugEnabled()){ + logger.debug("DroolsPdpsElectionHandler: Found StateManagementFeature" + + " with resourceName: {}", myPdp.getPdpId()); + } + stateManagementFeature = feature; + break; + } + } + if(stateManagementFeature == null){ + logger.error("DroolsPdpsElectionHandler failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", myPdp.getPdpId()); + } + } + + /* + * When the JpaDroolsPdpsConnector.standDown() method is invoked, it needs + * access to myPdp, so it can keep its designation status in sync with the + * DB. + */ + public static void setMyPdpDesignated(boolean designated) { + if(logger.isDebugEnabled()){ + logger.debug + ("setMyPdpDesignated: designated= {}", designated); + } + myPdp.setDesignated(designated); + } + + private class DesignationWaiter extends TimerTask { + // get an instance of logger + private final Logger logger = LoggerFactory.getLogger(DesignationWaiter.class); + + @Override + public void run() { + try{ + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run: Entering"); + } + + // just here initially so code still works + if (pdpsConnector == null) { + waitTimerLastRunDate = new Date(); + if(logger.isDebugEnabled()){ + logger.debug("DesignatedWaiter.run (pdpsConnector==null) waitTimerLastRunDate = {}", waitTimerLastRunDate); + } + + return; + } + + synchronized (designationWaiterLock) { + + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run: Entering synchronized block"); + } + + checkUpdateWorkerTimer(); + + //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. + ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>(); + + Collection<DroolsPdp> pdps = pdpsConnector.getDroolsPdps(); + DroolsPdp designatedPdp = null; + + if(logger.isDebugEnabled()){ + 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); + } + for (DroolsPdp pdp : pdps) { + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run: evaluating pdp ID: {}", pdp.getPdpId()); + } + + /* + * Note: side effect of isPdpCurrent is that any stale but + * designated PDPs will be marked as un-designated. + */ + boolean isCurrent = pdpsConnector.isPdpCurrent(pdp); + + /* + * We can't use stateManagement.getStandbyStatus() here, because + * we need the standbyStatus, not for this PDP, but for the PDP + * being processed by this loop iteration. + */ + String standbyStatus = stateManagementFeature.getStandbyStatus(pdp.getPdpId()); + if(standbyStatus==null){ + // Treat this case as a cold standby -- if we + // abort here, no sessions will be created in a + // single-node test environment. + standbyStatus = StateManagement.COLD_STANDBY; + } + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run: PDP= {}, isCurrent= {}", pdp.getPdpId(), isCurrent); + } + + /* + * There are 4 combinations of isDesignated and isCurrent. We will examine each one in-turn + * and evaluate the each pdp in the list of pdps against each combination. + * + * This is the first combination of isDesignated and isCurrent + */ + if (pdp.isDesignated() && isCurrent) { + //It is current, but it could have a standbystatus=coldstandby / hotstandby + //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()); + } + // So, we must demote it + try { + //Keep the order like this. StateManagement is last since it triggers controller shutdown + //This will change isDesignated and it can enter another if(combination) below + pdpsConnector.standDownPdp(pdp.getPdpId()); + myPdp.setDesignated(false); + isDesignated = false; + if(!(standbyStatus.equals(StateManagement.HOT_STANDBY) || + standbyStatus.equals(StateManagement.COLD_STANDBY))){ + /* + * Only demote it if it appears it has not already been demoted. Don't worry + * about synching with the topic endpoint states. That is done by the + * refreshStateAudit + */ + stateManagementFeature.demote(); + } + //update the standbystatus to check in a later combination of isDesignated and isCurrent + standbyStatus=stateManagementFeature.getStandbyStatus(pdp.getPdpId()); + } catch (Exception e) { + logger.error + ("DesignatedWaiter.run: myPdp: {} " + + "Caught Exception attempting to demote myPdp," + + "message= {}", myPdp.getPdpId(), e.getMessage()); + } + }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()); + } + } + + }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); + } + listOfDesignated.add(pdp); + } + + + } + + + /* + * The second combination of isDesignated and isCurrent + * + * PDP is designated but not current; it has failed. So we stand it down (it doesn't matter what + * 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); + } + /* + * Changes designated to 0 but it is still potentially providing service + * Will affect isDesignated, so, it can enter an if(combination) below + */ + pdpsConnector.standDownPdp(pdp.getPdpId()); + + //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()); + } + // We found that myPdp is designated but not current + // So, we must cause it to disableFail + try { + myPdp.setDesignated(false); + pdpsConnector.setDesignated(myPdp, false); + isDesignated = false; + stateManagementFeature.disableFailed(); + } catch (Exception e) { + logger.error + ("DesignatedWaiter.run: myPdp: {} Caught Exception " + + "attempting to disableFail myPdp {}, message= {}", + myPdp.getPdpId(), myPdp.getPdpId(), e.getMessage()); + } + } 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() ); + } + // 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 + // should equal coldstandby + try { + stateManagementFeature.disableFailed(pdp.getPdpId()); + } catch (Exception e) { + logger.error + ("DesignatedWaiter.run: for PDP {} Caught Exception attempting to " + + "disableFail({}), message= {}", + pdp.getPdpId(), pdp.getPdpId(), e.getMessage()); + } + + } + continue; //we are not going to do anything else with this pdp + } + + /* + * The third combination of isDesignated and isCurrent + * /* + * If a PDP is not currently designated but is providing service (erroneous, but recoverable) or hot standby + * we can add it to the list of possible designated if all the designated have failed + */ + 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); + } + // 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()); + } + try { + //Keep the order like this. StateManagement is last since it triggers controller shutdown + pdpsConnector.setDesignated(myPdp, false); + myPdp.setDesignated(false); + isDesignated = false; + //This is definitely not a redundant call. It is attempting to correct a problem + stateManagementFeature.demote(); + //recheck the standbystatus + standbyStatus = stateManagementFeature.getStandbyStatus(pdp.getPdpId()); + } catch (Exception e) { + logger.error + ("DesignatedWaiter.run: myPdp: {} Caught Exception " + + "attempting to demote myPdp {}, message = {}", myPdp.getPdpId(), + myPdp.getPdpId(), e.getMessage()); + } + + } + } + 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); + } + listOfDesignated.add(pdp); + } + continue; //done with this one + } + + /* + * The fourth combination of isDesignated and isCurrent + * + * We are not going to put any of these on the list since it appears they have failed. + + * + */ + if(!pdp.isDesignated() && !isCurrent) { + if(logger.isDebugEnabled()){ + 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. + */ + if(logger.isDebugEnabled()){ + 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. StateManagement is last since it triggers controller shutdown + pdpsConnector.setDesignated(myPdp, false); + myPdp.setDesignated(false); + isDesignated = false; + stateManagementFeature.disableFailed(); + } catch (Exception e) { + logger.error + ("DesignatedWaiter.run: myPdp: {} Caught Exception attempting to " + + "disableFail myPdp {}, message= {}", + myPdp.getPdpId(), myPdp.getPdpId(), e.getMessage()); + } + }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()); + } + // 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 + try { + stateManagementFeature.disableFailed(pdp.getPdpId()); + } catch (Exception e) { + logger.error + ("DesignatedWaiter.run: for PDP {}" + + " Caught Exception attempting to disableFail({})" + + ", message=", pdp.getPdpId(), pdp.getPdpId(), e.getMessage()); + } + } + } + } + + + } // end pdps loop + + /* + * We have checked the four combinations of isDesignated and isCurrent. Where appropriate, + * we added the PDPs to the potential list of designated pdps + * + * We need to give priority to pdps on the same site that is currently being used + * First, however, we must sanitize the list of designated to make sure their are + * only designated members or non-designated members. There should not be both in + * the list. Because there are real time delays, it is possible that both types could + * be on the list. + */ + + listOfDesignated = santizeDesignatedList(listOfDesignated); + + /* + * We need to figure out the last pdp that was the primary so we can get the last site + * name and the last session numbers. We need to create a "dummy" droolspdp since + * it will be used in later comparisons and cannot be null. + */ + + DroolsPdp mostRecentPrimary = computeMostRecentPrimary(pdps, listOfDesignated); + + if(mostRecentPrimary != null){ + pdpdLastActive = mostRecentPrimary.getPdpId(); + } + + + /* + * It is possible to get here with more than one pdp designated and providingservice. This normally + * occurs when there is a race condition with multiple nodes coming up at the same time. If that is + * the case we must determine which one is the one that should be designated and which one should + * be demoted. + * + * It is possible to have 0, 1, 2 or more but not all, or all designated. + * If we have one designated and current, we chose it and are done + * If we have 2 or more, but not all, we must determine which one is in the same site as + * the previously designated pdp. + */ + + designatedPdp = computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + if(designatedPdp != null){ + pdpdNowActive = designatedPdp.getPdpId(); + } + + if (designatedPdp == null) { + logger.warn + ("WARNING: DesignatedWaiter.run: No viable PDP found to be Designated. designatedPdp still null."); + // Just to be sure the parameters are correctly set + myPdp.setDesignated(false); + pdpsConnector.setDesignated(myPdp,false); + isDesignated = false; + + waitTimerLastRunDate = new Date(); + if(logger.isDebugEnabled()){ + logger.debug("DesignatedWaiter.run (designatedPdp == null) waitTimerLastRunDate = {}", waitTimerLastRunDate); + } + + return; + + } else if (designatedPdp.getPdpId().equals(myPdp.getPdpId())) { + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run: designatedPdp is PDP={}", myPdp.getPdpId()); + } + /* + * update function expects myPdp.isDesignated to be true. + */ + try { + //Keep the order like this. StateManagement is last since it triggers controller init + myPdp.setDesignated(true); + myPdp.setDesignatedDate(new Date()); + pdpsConnector.setDesignated(myPdp, true); + isDesignated = true; + String standbyStatus = stateManagementFeature.getStandbyStatus(); + if(!standbyStatus.equals(StateManagement.PROVIDING_SERVICE)){ + /* + * Only call promote if it is not already in the right state. Don't worry about + * synching the lower level topic endpoint states. That is done by the + * refreshStateAudit. + * Note that we need to fetch the session list from 'mostRecentPrimary' + * at this point -- soon, 'mostRecentPrimary' will be set to this host. + */ + //this.sessions = mostRecentPrimary.getSessions(); + stateManagementFeature.promote(); + } + } catch (Exception e) { + logger.error + ("ERROR: DesignatedWaiter.run: Caught Exception attempting to promote PDP={}" + + ", message=", myPdp.getPdpId(), e.getMessage()); + myPdp.setDesignated(false); + pdpsConnector.setDesignated(myPdp,false); + isDesignated = false; + //If you can't promote it, demote it + try { + String standbyStatus = stateManagementFeature.getStandbyStatus(); + if(!(standbyStatus.equals(StateManagement.HOT_STANDBY) || + standbyStatus.equals(StateManagement.COLD_STANDBY))){ + /* + * Only call demote if it is not already in the right state. Don't worry about + * synching the lower level topic endpoint states. That is done by the + * refreshStateAudit. + */ + stateManagementFeature.demote(); + } + } catch (Exception e1) { + logger.error + ("ERROR: DesignatedWaiter.run: Caught StandbyStatusException " + + "attempting to promote then demote PDP={}, message=", + myPdp.getPdpId(), e1.getMessage()); + } + + } + waitTimerLastRunDate = new Date(); + if(logger.isDebugEnabled()){ + logger.debug("DesignatedWaiter.run (designatedPdp.getPdpId().equals(myPdp.getPdpId())) " + + "waitTimerLastRunDate = " + waitTimerLastRunDate); + } + + return; + } + isDesignated = false; + + } // end synchronized + if(logger.isDebugEnabled()){ + 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); + } + + waitTimerLastRunDate = tmpDate; + + }catch(Exception e){ + logger.error("DesignatedWaiter.run caught an unexpected exception: ", e); + } + } // end run + } + + public ArrayList<DroolsPdp> santizeDesignatedList(ArrayList<DroolsPdp> listOfDesignated){ + + boolean containsDesignated = false; + boolean containsHotStandby = false; + ArrayList<DroolsPdp> listForRemoval = new ArrayList<DroolsPdp>(); + for(DroolsPdp pdp : listOfDesignated){ + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run sanitizing: pdp = {}" + + " isDesignated = {}",pdp.getPdpId(), pdp.isDesignated()); + } + if(pdp.isDesignated()){ + containsDesignated = true; + }else { + containsHotStandby = true; + listForRemoval.add(pdp); + } + } + if(containsDesignated && containsHotStandby){ + //remove the hot standby from the list + listOfDesignated.removeAll(listForRemoval); + containsHotStandby = false; + } + return listOfDesignated; + } + + public DroolsPdp computeMostRecentPrimary(Collection<DroolsPdp> pdps, ArrayList<DroolsPdp> listOfDesignated){ + boolean containsDesignated = false; + for(DroolsPdp pdp : listOfDesignated){ + if(pdp.isDesignated()){ + containsDesignated = true; + } + } + DroolsPdp mostRecentPrimary = new DroolsPdpImpl(null, true, 1, new Date(0)); + mostRecentPrimary.setSiteName(null); + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run listOfDesignated.size() = {}", listOfDesignated.size()); + } + if(listOfDesignated.size() <=1){ + if(logger.isDebugEnabled()){ + 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()); + } + if(pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0){ + mostRecentPrimary = pdp; + if(logger.isDebugEnabled()){ + 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()); + } + //They are all designated or all hot standby. + mostRecentPrimary = null; + for(DroolsPdp pdp : pdps){ + if(mostRecentPrimary == null){ + mostRecentPrimary = pdp; + continue; + } + 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()); + } + } + }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()); + } + } + } + } + }else{ + if(logger.isDebugEnabled()){ + 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); + } + /* + * 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 + * site with the latest designated date for the pdp not included on the designated list. + * This should be the site that had the last designation before this race condition + * occurred. + */ + for(DroolsPdp pdp : pdps){ + if(listOfDesignated.contains(pdp)){ + continue; //Don't consider this entry + } + if(pdp.getDesignatedDate().compareTo(mostRecentPrimary.getDesignatedDate()) > 0){ + mostRecentPrimary = pdp; + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run mostRecentPrimary = {}", mostRecentPrimary.getPdpId()); + } + } + } + }else{ + if(logger.isDebugEnabled()){ + 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()); + } + } + } + } + } + return mostRecentPrimary; + } + + public DroolsPdp computeDesignatedPdp(ArrayList<DroolsPdp> listOfDesignated, DroolsPdp mostRecentPrimary){ + DroolsPdp designatedPdp = null; + DroolsPdp lowestPriorityPdp = null; + if(listOfDesignated.size() > 1){ + if(logger.isDebugEnabled()){ + logger.debug + ("DesignatedWaiter.run: myPdp: {} listOfDesignated.size(): {}", myPdp.getPdpId(), listOfDesignated.size()); + } + DroolsPdp rejectedPdp = null; + DroolsPdp lowestPrioritySameSite = null; + DroolsPdp lowestPriorityDifferentSite = null; + for(DroolsPdp pdp : listOfDesignated){ + // We need to determine if another PDP is the lowest priority + if(nullSafeEquals(pdp.getSiteName(),mostRecentPrimary.getSiteName())){ + if(lowestPrioritySameSite == null){ + if(lowestPriorityDifferentSite != null){ + rejectedPdp = lowestPriorityDifferentSite; + } + lowestPrioritySameSite = pdp; + }else{ + if(pdp.getPdpId().equals((lowestPrioritySameSite.getPdpId()))){ + 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()); + } + //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()); + } + rejectedPdp = pdp; + } + } + } else{ + if(lowestPrioritySameSite != null){ + //if we already have a candidate for same site, we don't want to bother with different sites + rejectedPdp = pdp; + } else{ + if(lowestPriorityDifferentSite == null){ + lowestPriorityDifferentSite = pdp; + continue; + } + if(pdp.getPdpId().equals((lowestPriorityDifferentSite.getPdpId()))){ + 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()); + } + //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()); + } + rejectedPdp = pdp; + } + } + } + // 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()); + } + // We found that myPdp is on the listOfDesignated and it is not the lowest priority + // So, we must demote it + try { + //Keep the order like this. StateManagement is last since it triggers controller shutdown + myPdp.setDesignated(false); + pdpsConnector.setDesignated(myPdp, false); + isDesignated = false; + String standbyStatus = stateManagementFeature.getStandbyStatus(); + if(!(standbyStatus.equals(StateManagement.HOT_STANDBY) || + standbyStatus.equals(StateManagement.COLD_STANDBY))){ + /* + * Only call demote if it is not already in the right state. Don't worry about + * synching the lower level topic endpoint states. That is done by the + * refreshStateAudit. + */ + stateManagementFeature.demote(); + } + } catch (Exception e) { + myPdp.setDesignated(false); + pdpsConnector.setDesignated(myPdp, false); + isDesignated = false; + logger.error + ("DesignatedWaiter.run: myPdp: {} Caught Exception attempting to " + + "demote myPdp {} myPdp.getPdpId(), message= {}", myPdp.getPdpId(), + e.getMessage()); + } + } + } //end: for(DroolsPdp pdp : listOfDesignated) + if(lowestPrioritySameSite != null){ + lowestPriorityPdp = lowestPrioritySameSite; + } else { + 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); + } + designatedPdp = lowestPriorityPdp; + + } else if(listOfDesignated.isEmpty()){ + if(logger.isDebugEnabled()){ + 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()); + } + designatedPdp = listOfDesignated.get(0); + } + return designatedPdp; + + } + + private class TimerUpdateClass extends TimerTask{ + + @Override + public void run() { + try{ + if(logger.isDebugEnabled()){ + logger.debug("TimerUpdateClass.run: entry"); + } + checkWaitTimer(); + synchronized(pdpsConnectorLock){ + + myPdp.setUpdatedDate(new Date()); + /* + Redundant with DesignationWaiter and this updates the date every + cycle instead of just when the state changes. + if(myPdp.isDesignated()){ + myPdp.setDesignatedDate(new Date()); + } + */ + pdpsConnector.update(myPdp); + + Date tmpDate = new Date(); + if(logger.isDebugEnabled()){ + logger.debug("TimerUpdateClass.run: updateWorkerLastRunDate = {}", tmpDate); + } + + updateWorkerLastRunDate = tmpDate; + } + if(logger.isDebugEnabled()){ + logger.debug("TimerUpdateClass.run.exit"); + } + }catch(Exception e){ + logger.error("TimerUpdateClass.run caught an unexpected exception: ", e); + } + } + } + @Override + public void checkThreadStatus() { + checkUpdateWorkerTimer(); + checkWaitTimer(); + } + + private void checkUpdateWorkerTimer(){ + synchronized(checkUpdateWorkerLock){ + try{ + if(logger.isDebugEnabled()){ + logger.debug("checkUpdateWorkerTimer: entry"); + } + Date now = new Date(); + long nowMs = now.getTime(); + long updateWorkerMs = updateWorkerLastRunDate.getTime(); + //give it 2 second cushion + if((nowMs - updateWorkerMs) > pdpCheckInterval + 2000){ + logger.error("checkUpdateWorkerTimer: nowMs - updateWorkerMs = {} " + + ", exceeds pdpCheckInterval + 2000 = {} " + + "Will reschedule updateWorker timer",(nowMs - updateWorkerMs), (pdpCheckInterval + 2000)); + + try{ + updateWorker.cancel(); + // Recalculate the time because this is a synchronized section and the thread could have + // been blocked. + now = new Date(); + nowMs = now.getTime(); + updateWorker = new Timer(); + // reset the updateWorkerLastRunDate + updateWorkerLastRunDate = new Date(nowMs + 100); + //execute the first time in 100 ms + updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval); + if(logger.isDebugEnabled()){ + logger.debug("checkUpdateWorkerTimer: Scheduling updateWorker timer to start in 100 ms "); + } + }catch(Exception e){ + logger.error("checkUpdateWorkerTimer: Caught unexpected Exception: ", e); + // Recalculate the time because this is a synchronized section and the thread could have + // been blocked. + now = new Date(); + nowMs = now.getTime(); + updateWorker = new Timer(); + updateWorkerLastRunDate = new Date(nowMs + 100); + updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval); + if(logger.isDebugEnabled()){ + logger.debug("checkUpdateWorkerTimer: Attempting to schedule updateWorker timer in 100 ms"); + } + } + + } + if(logger.isDebugEnabled()){ + logger.debug("checkUpdateWorkerTimer: exit"); + } + }catch(Exception e){ + logger.error("checkUpdateWorkerTimer: caught unexpected exception: ", e); + } + } + } + + private void checkWaitTimer(){ + synchronized(checkWaitTimerLock){ + try{ + if(logger.isDebugEnabled()){ + logger.debug("checkWaitTimer: entry"); + } + Date now = new Date(); + long nowMs = now.getTime(); + long waitTimerMs = waitTimerLastRunDate.getTime(); + + //give it 2 times leeway + if((nowMs - waitTimerMs) > 2*pdpUpdateInterval){ + logger.error("checkWaitTimer: nowMs - waitTimerMs = {}" + + ", exceeds pdpUpdateInterval + 2000 = {}" + + "Will reschedule waitTimer timer", (nowMs - waitTimerMs), (2*pdpUpdateInterval)); + + try{ + // Recalculate since the thread could have been stalled on the synchronize() + nowMs = (new Date()).getTime(); + // Time to the start of the next pdpUpdateInterval multiple + long startMs = getDWaiterStartMs(); + waitTimer.cancel(); + designationWaiter = new DesignationWaiter(); + waitTimer = new Timer(); + waitTimerLastRunDate = new Date(nowMs + startMs); + waitTimer.scheduleAtFixedRate(designationWaiter, startMs, pdpUpdateInterval); + if(logger.isDebugEnabled()){ + logger.debug("checkWaitTimer: Scheduling waitTimer timer to start in {} ms", startMs); + } + }catch(Exception e){ + logger.error("checkWaitTimer: Caught unexpected Exception: ", e); + // Recalculate since the thread could have been stalled on the synchronize() + nowMs = (new Date()).getTime(); + // Time to the start of the next pdpUpdateInterval multiple + long startMs = getDWaiterStartMs(); + designationWaiter = new DesignationWaiter(); + waitTimer = new Timer(); + waitTimerLastRunDate = new Date(nowMs + startMs); + waitTimer.scheduleAtFixedRate(designationWaiter, startMs, pdpUpdateInterval); + if(logger.isDebugEnabled()){ + logger.debug("checkWaitTimer: Scheduling waitTimer timer in {} ms", startMs); + } + } + + } + if(logger.isDebugEnabled()){ + logger.debug("checkWaitTimer: exit"); + } + }catch(Exception e){ + logger.error("checkWaitTimer: caught unexpected exception: ", e); + } + } + } + + private long getDWaiterStartMs(){ + Date now = new Date(); + + // Retrieve the ms since the epoch + long nowMs = now.getTime(); + + // Time since the end of the last pdpUpdateInterval multiple + long nowModMs = nowMs % pdpUpdateInterval; + + // Time to the start of the next pdpUpdateInterval multiple + long startMs = 2*pdpUpdateInterval - nowModMs; + + // Give the start time a minimum of a 5 second cushion + if(startMs < 5000){ + // Start at the beginning of following interval + startMs = pdpUpdateInterval + startMs; + } + return startMs; + } + + private boolean nullSafeEquals(Object one, Object two){ + if(one == null && two == null){ + return true; + } + if(one != null && two != null){ + return one.equals(two); + } + return false; + } + + public String getPdpdNowActive(){ + return pdpdNowActive; + } + + public String getPdpdLastActive(){ + return pdpdLastActive; + } +} 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 new file mode 100644 index 00000000..0d931acc --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java @@ -0,0 +1,636 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +import java.util.Collection; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Query; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JpaDroolsPdpsConnector implements DroolsPdpsConnector { + + // 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 for drools session and pass it in here, or create a new one + public JpaDroolsPdpsConnector(EntityManagerFactory emf){ + this.emf = emf; + } + @Override + public Collection<DroolsPdp> getDroolsPdps() { + //return a list of all the DroolsPdps in the database + EntityManager em = emf.createEntityManager(); + try { + em.getTransaction().begin(); + Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p"); + List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + LinkedList<DroolsPdp> droolsPdpsReturnList = new LinkedList<DroolsPdp>(); + for(Object o : droolsPdpsList){ + if(o instanceof DroolsPdp){ + //Make sure it is not a cached version + em.refresh((DroolsPdpEntity)o); + droolsPdpsReturnList.add((DroolsPdp)o); + if (logger.isDebugEnabled()) { + DroolsPdp droolsPdp = (DroolsPdp)o; + logger.debug("getDroolsPdps: PDP= {}" + + ", isDesignated= {}" + + ", updatedDate= {}" + + ", priority= {}", droolsPdp.getPdpId(), droolsPdp.isDesignated(), + droolsPdp.getUpdatedDate(), droolsPdp.getPriority()); + } + } + } + try{ + em.getTransaction().commit(); + }catch(Exception e){ + logger.error + ("Cannot commit getDroolsPdps() transaction", e); + } + return droolsPdpsReturnList; + } finally { + cleanup(em, "getDroolsPdps"); + } + } + + private boolean nullSafeEquals(Object one, Object two){ + if(one == null && two == null){ + return true; + } + if(one != null && two != null){ + return one.equals(two); + } + return false; + } + + @Override + public void update(DroolsPdp pdp) { + + if (logger.isDebugEnabled()) { + logger.debug("update: Entering, pdpId={}", pdp.getPdpId()); + } + + //this is to update our own pdp in the database + EntityManager em = emf.createEntityManager(); + try { + em.getTransaction().begin(); + Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); + droolsPdpsListQuery.setParameter("pdpId", pdp.getPdpId()); + List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + DroolsPdpEntity droolsPdpEntity; + if(droolsPdpsList.size() == 1 && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)){ + droolsPdpEntity = (DroolsPdpEntity)droolsPdpsList.get(0); + em.refresh(droolsPdpEntity); //Make sure we have current values + Date currentDate = new Date(); + long difference = currentDate.getTime()-droolsPdpEntity.getUpdatedDate().getTime(); + //just set some kind of default here + long pdpTimeout = 15000; + try{ + pdpTimeout = Long.parseLong(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_TIMEOUT)); + }catch(Exception e){ + 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()); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("update: For PDP={}" + + ", instantiating new DroolsPdpEntity", pdp.getPdpId()); + } + droolsPdpEntity = new DroolsPdpEntity(); + em.persist(droolsPdpEntity); + droolsPdpEntity.setPdpId(pdp.getPdpId()); + } + if(droolsPdpEntity.getPriority() != pdp.getPriority()){ + droolsPdpEntity.setPriority(pdp.getPriority()); + } + if(!droolsPdpEntity.getUpdatedDate().equals(pdp.getUpdatedDate())){ + droolsPdpEntity.setUpdatedDate(pdp.getUpdatedDate()); + } + /*if(!droolsPdpEntity.getDesignatedDate().equals(pdp.getDesignatedDate())){ + droolsPdpEntity.setDesignatedDate(pdp.getDesignatedDate()); + } The designated date is only set below when this first becomes designated*/ + if(!nullSafeEquals(droolsPdpEntity.getSiteName(),pdp.getSiteName())){ + droolsPdpEntity.setSiteName(pdp.getSiteName()); + } + + 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()); + } + droolsPdpEntity.setDesignated(pdp.isDesignated()); + //The isDesignated value is not the same and the new one == true + if(pdp.isDesignated()){ + droolsPdpEntity.setDesignatedDate(new Date()); + } + } + em.getTransaction().commit(); + } finally { + cleanup(em, "update"); + } + + if (logger.isDebugEnabled()) { + logger.debug("update: Exiting"); + } + + } + + /* + * 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) + */ + @Override + public boolean isPdpCurrent(DroolsPdp pdp) { + + boolean isCurrent = isCurrent(pdp); + + EntityManager em = emf.createEntityManager(); + try{ + if(!isCurrent && pdp.isDesignated()){ + em.getTransaction().begin(); + Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); + droolsPdpsListQuery.setParameter("pdpId", pdp.getPdpId()); + 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()); + } + 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!", pdp.getPdpId()); + } + } else { + if (logger.isDebugEnabled()) { + 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); + } finally { + cleanup(em, "isPdpCurrent"); + } + return isCurrent; + + } + + @Override + public void setDesignated(DroolsPdp pdp, boolean designated) { + + if (logger.isDebugEnabled()) { + logger.debug("setDesignated: Entering, pdpId={}" + + ", designated={}", pdp.getPdpId(), designated); + } + + EntityManager em = null; + try { + em = emf.createEntityManager(); + em.getTransaction().begin(); + Query droolsPdpsListQuery = em + .createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); + droolsPdpsListQuery.setParameter("pdpId", pdp.getPdpId()); + List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode( + LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + if (droolsPdpsList.size() == 1 + && droolsPdpsList.get(0) instanceof DroolsPdpEntity) { + DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList + .get(0); + + if (logger.isDebugEnabled()) { + 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()){ + droolsPdpEntity.setDesignatedDate(new Date()); + } + + } + em.getTransaction().commit(); + } else { + logger.error("setDesignated: PDP={}" + + " not in DB; cannot update designation", pdp.getPdpId()); + } + } catch (Exception e) { + logger.error("setDesignated: Caught Exception", e); + } finally { + cleanup(em, "setDesignated"); + } + + if (logger.isDebugEnabled()) { + logger.debug("setDesignated: Exiting"); + } + + } + + + @Override + public void standDownPdp(String pdpId) { + if(logger.isDebugEnabled()){ + logger.debug("standDownPdp: Entering, pdpId={}", pdpId); + } + + EntityManager em = null; + try { + /* + * Start transaction. + */ + em = emf.createEntityManager(); + em.getTransaction().begin(); + + /* + * Get droolspdpentity record for this PDP and mark DESIGNATED as + * false. + */ + Query droolsPdpsListQuery = em + .createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); + droolsPdpsListQuery.setParameter("pdpId", pdpId); + List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode( + LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + DroolsPdpEntity droolsPdpEntity; + if (droolsPdpsList.size() == 1 + && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) { + droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0); + droolsPdpEntity.setDesignated(false); + em.persist(droolsPdpEntity); + if(logger.isDebugEnabled()){ + logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId ); + } + } else { + logger.error("standDownPdp: Missing record in droolspdpentity for pdpId={}" + + "; cannot stand down PDP", pdpId); + } + + /* + * End transaction. + */ + em.getTransaction().commit(); + cleanup(em, "standDownPdp"); + em = null; + + // Keep the election handler in sync with the DB + DroolsPdpsElectionHandler.setMyPdpDesignated(false); + + } catch (Exception e) { + logger.error("standDownPdp: Unexpected Exception attempting to mark " + + "DESIGNATED as false for droolspdpentity, pdpId={}" + + ". Cannot stand down PDP; message={}", pdpId, e.getMessage(), e); + } finally { + cleanup(em, "standDownPdp"); + } + if(logger.isDebugEnabled()){ + 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<DroolsPdp> pdps) { + + if (logger.isDebugEnabled()) { + logger.debug("hasDesignatedPdpFailed: Entering, pdps.size()={}", pdps.size()); + } + + boolean failed = true; + boolean foundDesignatedPdp = false; + + for (DroolsPdp pdp : pdps) { + + /* + * 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()); + } + 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()); + } + } + } + + if (logger.isDebugEnabled()) { + 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()); + } + + boolean current = false; + + // Return if the current PDP is considered "current" based on whatever + // time box that may be. + // If the the PDP is not current, we should mark it as not primary in + // the database + Date currentDate = new Date(); + long difference = currentDate.getTime() + - pdp.getUpdatedDate().getTime(); + // just set some kind of default here + long pdpTimeout = 15000; + try { + pdpTimeout = Long.parseLong(ActiveStandbyProperties + .getProperty(ActiveStandbyProperties.PDP_TIMEOUT)); + if (logger.isDebugEnabled()) { + 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); + } + + return current; + } + + + /* + * Currently this method is only used in a JUnit test environment. Gets a + * PDP record from droolspdpentity table. + */ + @Override + public DroolsPdpEntity getPdp(String pdpId) { + + if (logger.isDebugEnabled()) { + logger.debug("getPdp: Entering and getting PDP with pdpId={}", pdpId); + } + + DroolsPdpEntity droolsPdpEntity = null; + + EntityManager em = null; + try { + em = emf.createEntityManager(); + em.getTransaction().begin(); + Query droolsPdpsListQuery = em + .createQuery("SELECT p FROM DroolsPdpEntity p WHERE p.pdpId=:pdpId"); + droolsPdpsListQuery.setParameter("pdpId", pdpId); + List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode( + LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + 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()); + } + + // Make sure the droolsPdpEntity is not a cached version + em.refresh(droolsPdpEntity); + + em.getTransaction().commit(); + } else { + logger.error("getPdp: PDP={} not found!?", pdpId); + } + } catch (Exception e) { + logger.error + ("getPdp: Caught Exception attempting to get PDP", e); + } finally { + cleanup(em, "getPdp"); + } + + if (logger.isDebugEnabled()) { + logger.debug("getPdp: Returning droolsPdpEntity={}", droolsPdpEntity); + } + return droolsPdpEntity; + + } + + /* + * Normally this method should only be used in a JUnit test environment. + * Manually inserts a PDP record in droolspdpentity table. + */ + @Override + public void insertPdp(DroolsPdp pdp) { + if(logger.isDebugEnabled()){ + logger.debug("insertPdp: Entering and manually inserting PDP"); + } + + /* + * Start transaction + */ + EntityManager em = emf.createEntityManager(); + try { + em.getTransaction().begin(); + + /* + * Insert record. + */ + DroolsPdpEntity droolsPdpEntity = new DroolsPdpEntity(); + em.persist(droolsPdpEntity); + droolsPdpEntity.setPdpId(pdp.getPdpId()); + droolsPdpEntity.setDesignated(pdp.isDesignated()); + droolsPdpEntity.setPriority(pdp.getPriority()); + droolsPdpEntity.setUpdatedDate(pdp.getUpdatedDate()); + droolsPdpEntity.setSiteName(pdp.getSiteName()); + + /* + * End transaction. + */ + em.getTransaction().commit(); + } finally { + cleanup(em, "insertPdp"); + } + if(logger.isDebugEnabled()){ + logger.debug("insertPdp: Exiting"); + } + + } + + /* + * Normally this method should only be used in a JUnit test environment. + * Manually deletes all PDP records in droolspdpentity table. + */ + @Override + public void deleteAllPdps() { + + if(logger.isDebugEnabled()){ + logger.debug("deleteAllPdps: Entering"); + } + + /* + * Start transaction + */ + EntityManager em = emf.createEntityManager(); + try { + em.getTransaction().begin(); + + Query droolsPdpsListQuery = em + .createQuery("SELECT p FROM DroolsPdpEntity p"); + @SuppressWarnings("unchecked") + List<DroolsPdp> droolsPdpsList = droolsPdpsListQuery.setLockMode( + LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList(); + if(logger.isDebugEnabled()){ + logger.debug("deleteAllPdps: Deleting {} PDPs", droolsPdpsList.size()); + } + for (DroolsPdp droolsPdp : droolsPdpsList) { + String pdpId = droolsPdp.getPdpId(); + deletePdp(pdpId); + } + + /* + * End transaction. + */ + em.getTransaction().commit(); + } finally { + cleanup(em, "deleteAllPdps"); + } + if(logger.isDebugEnabled()){ + logger.debug("deleteAllPdps: Exiting"); + } + + } + + /* + * Normally this method should only be used in a JUnit test environment. + * Manually deletes a PDP record in droolspdpentity table. + */ + @Override + public void deletePdp(String pdpId) { + if(logger.isDebugEnabled()){ + logger.debug("deletePdp: Entering and manually deleting pdpId={}", pdpId); + } + + /* + * Start transaction + */ + EntityManager em = emf.createEntityManager(); + try { + em.getTransaction().begin(); + + /* + * Delete record. + */ + DroolsPdpEntity droolsPdpEntity = em.find(DroolsPdpEntity.class, pdpId); + if (droolsPdpEntity != null) { + if(logger.isDebugEnabled()){ + logger.debug("deletePdp: Removing PDP"); + } + em.remove(droolsPdpEntity); + } else { + if(logger.isDebugEnabled()){ + logger.debug("deletePdp: PDP with ID={} not currently in DB", pdpId); + } + } + + /* + * End transaction. + */ + em.getTransaction().commit(); + } finally { + cleanup(em, "deletePdp"); + } + if(logger.isDebugEnabled()){ + logger.debug("deletePdp: Exiting"); + } + + } + + /* + * Close the specified EntityManager, rolling back any pending transaction + * + * @param em the EntityManager to close ('null' is OK) + * @param method the invoking Java method (used for log messages) + */ + private static void cleanup(EntityManager em, String method) + { + if (em != null) { + if (em.isOpen()) { + if (em.getTransaction().isActive()) { + // there is an active EntityTransaction -- roll it back + try { + em.getTransaction().rollback(); + } catch (Exception e) { + logger.error(method + ": Caught Exception attempting to rollback EntityTransaction,", e); + } + } + + // now, close the EntityManager + try { + em.close(); + } catch (Exception e) { + logger.error(method + ": Caught Exception attempting to close EntityManager, ", e); + } + } + } + } +} 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 new file mode 100644 index 00000000..ce62bf89 --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PMStandbyStateChangeNotifier.java @@ -0,0 +1,345 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.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 + * 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 + * the active/lead role. + * + * 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 + * engines in the engine management layer. + */ +import java.util.Date; +import java.util.Timer; +import java.util.TimerTask; + +import org.onap.policy.common.im.StateChangeNotifier; +import org.onap.policy.common.im.StateManagement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.policy.drools.system.PolicyEngine; + +/* + * 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, 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 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 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 conn.standDownPdp() would not get called! + * + * 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. + * + */ +public class PMStandbyStateChangeNotifier extends StateChangeNotifier { + // get an instance of logger + private static final Logger logger = LoggerFactory.getLogger(PMStandbyStateChangeNotifier.class); + private Timer delayActivateTimer; + private int pdpUpdateInterval; + private boolean isWaitingForActivation; + private long startTimeWaitingForActivationMs; + private long waitInterval; + private boolean isNowActivating; + private String previousStandbyStatus; + public static String NONE = "none"; + public static String UNSUPPORTED = "unsupported"; + public static String HOTSTANDBY_OR_COLDSTANDBY = "hotstandby_or_coldstandby"; + + public PMStandbyStateChangeNotifier(){ + pdpUpdateInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL)); + isWaitingForActivation = false; + startTimeWaitingForActivationMs = new Date().getTime(); + //delay the activate so the DesignatedWaiter can run twice - give it an extra 2 seconds + waitInterval = 2*pdpUpdateInterval + 2000; + isNowActivating=false; + previousStandbyStatus = PMStandbyStateChangeNotifier.NONE; + } + + @Override + public void handleStateChange() { + /* + * A note on synchronization: This method is not synchronized because the caller, 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.isInfoEnabled()){ + if(logger.isDebugEnabled()){ + 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); + } + + if (standbyStatus == null || standbyStatus.equals(StateManagement.NULL_VALUE)) { + if(logger.isDebugEnabled()){ + 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); + } + 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 + } + //Only want to lock the endpoints, not the controllers. + PolicyEngine.manager.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. + previousStandbyStatus = StateManagement.NULL_VALUE; + }catch(Exception e){ + logger.warn("handleStateChange: standbyStatus == null caught exception: ", e); + } + } else if (standbyStatus.equals(StateManagement.HOT_STANDBY) || standbyStatus.equals(StateManagement.COLD_STANDBY)) { + if(logger.isDebugEnabled()){ + 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); + } + 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 + } + //Only want to lock the endpoints, not the controllers. + PolicyEngine.manager.deactivate(); + //The operation was fully successful + previousStandbyStatus = PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY; + }catch(Exception e){ + logger.warn("handleStateChange: standbyStatus = {} caught exception: {}", standbyStatus, e.getMessage(), e); + } + + } else if (standbyStatus.equals(StateManagement.PROVIDING_SERVICE)) { + if(logger.isDebugEnabled()){ + 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); + } + return; + } + try{ + //UnLock all the endpoints + if(logger.isDebugEnabled()){ + 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); + } + + //Delay activation for 2*pdpUpdateInterval+2000 ms in case of an election handler conflict. + //You could have multiple election handlers thinking they can take over. + + // First let's check that the timer has not died + if(isWaitingForActivation){ + if(logger.isDebugEnabled()){ + 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); + } + //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"); + } + // This will assure the timer is cancelled and rescheduled. + isWaitingForActivation = false; + } + } + + } + + 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."); + } + //If you end of here, there was no active timer + } + delayActivateTimer = new Timer(); + //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); + } + }else{ + if(logger.isDebugEnabled()){ + logger.debug("handleStateChange: PROVIDING_SERVICE delayActivationTimer is waiting for activation."); + } + } + + }catch(Exception e){ + logger.warn("handleStateChange: PROVIDING_SERVICE standbyStatus == providingservice caught exception: ", e); + } + + } else { + 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); + } + 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(); + //We know the standbystatus is unsupported + previousStandbyStatus = PMStandbyStateChangeNotifier.UNSUPPORTED; + }catch(Exception e){ + logger.warn("handleStateChange: Unsupported standbyStatus = {} " + + "caught exception: {} ",standbyStatus, e.getMessage(), e); + } + } + if(logger.isDebugEnabled()){ + logger.debug("handleStateChange: Exiting"); + } + } + + private class DelayActivateClass extends TimerTask{ + + private Object delayActivateLock = new Object(); + + + @Override + public void run() { + isNowActivating = true; + try{ + if(logger.isDebugEnabled()){ + logger.debug("DelayActivateClass.run: entry"); + } + synchronized(delayActivateLock){ + PolicyEngine.manager.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"); + } + }catch(Exception e){ + isWaitingForActivation = false; + isNowActivating = false; + logger.warn("DelayActivateClass.run: caught an unexpected exception " + + "calling PolicyEngine.manager.activate: ", e); + } + } + } + + public String getPreviousStandbyStatus(){ + return previousStandbyStatus; + } +} diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ThreadRunningChecker.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ThreadRunningChecker.java new file mode 100644 index 00000000..db848ebb --- /dev/null +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ThreadRunningChecker.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.activestandby; + +public interface ThreadRunningChecker { + public void checkThreadStatus(); + +} diff --git a/feature-active-standby-management/src/main/resources/META-INF/persistence.xml b/feature-active-standby-management/src/main/resources/META-INF/persistence.xml new file mode 100644 index 00000000..4a625b55 --- /dev/null +++ b/feature-active-standby-management/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,33 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + feature-active-standby-management + ================================================================================ + 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========================================================= + --> + +<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="activeStandbyPU" transaction-type="RESOURCE_LOCAL"> + <!-- This is for database access by non-drools methods --> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.onap.policy.drools.activestandby.DroolsPdpEntity</class> + <properties> + <!-- Properties are passed in --> + </properties> + </persistence-unit> +</persistence> diff --git a/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.activestandby.ActiveStandbyFeatureAPI b/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.activestandby.ActiveStandbyFeatureAPI new file mode 100644 index 00000000..5296f8b7 --- /dev/null +++ b/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.activestandby.ActiveStandbyFeatureAPI @@ -0,0 +1 @@ +org.onap.policy.drools.activestandby.ActiveStandbyFeature diff --git a/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI b/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI new file mode 100644 index 00000000..5296f8b7 --- /dev/null +++ b/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI @@ -0,0 +1 @@ +org.onap.policy.drools.activestandby.ActiveStandbyFeature diff --git a/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureAPI b/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureAPI new file mode 100644 index 00000000..5296f8b7 --- /dev/null +++ b/feature-active-standby-management/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureAPI @@ -0,0 +1 @@ +org.onap.policy.drools.activestandby.ActiveStandbyFeature diff --git a/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java new file mode 100644 index 00000000..a4a97968 --- /dev/null +++ b/feature-active-standby-management/src/test/java/org/onap/policy/drools/controller/test/StandbyStateManagementTest.java @@ -0,0 +1,1551 @@ +/* + * ============LICENSE_START======================================================= + * feature-active-standby-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.controller.test; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.util.ArrayList; +import java.util.Date; +import java.util.Properties; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; + +import org.apache.commons.lang3.time.DateUtils; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.onap.policy.common.im.AdministrativeStateException; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.im.StateManagement; +import org.onap.policy.drools.activestandby.ActiveStandbyFeatureAPI; +import org.onap.policy.drools.activestandby.ActiveStandbyProperties; +import org.onap.policy.drools.activestandby.DroolsPdp; +import org.onap.policy.drools.activestandby.DroolsPdpEntity; +import org.onap.policy.drools.activestandby.DroolsPdpImpl; +import org.onap.policy.drools.activestandby.DroolsPdpsConnector; +import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler; +import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector; +import org.onap.policy.drools.activestandby.PMStandbyStateChangeNotifier; +import org.onap.policy.drools.core.PolicySessionFeatureAPI; +import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI; + +/* + * All JUnits are designed to run in the local development environment + * where they have write privileges and can execute time-sensitive + * tasks. + * + * These tests can be run as JUnits, but there is some issue with running them + * as part of a "mvn install" build. Also, they take a very long time to run + * due to many real time breaks. Consequently, they are marked as @Ignore and + * only run from the desktop. + */ + +public class StandbyStateManagementTest { + private static final Logger logger = LoggerFactory.getLogger(StandbyStateManagementTest.class); + /* + * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every ten seconds, starting + * at ten seconds after the minute boundary (e.g. 13:05:10). So, an 80 second sleep should be + * sufficient to ensure that we wait for the DesignationWaiter to do its job, before + * checking the results. + */ + + long sleepTime = 80000; + + /* + * DroolsPdpsElectionHandler runs every ten seconds, so a 15 second sleep should be + * plenty to ensure it has time to re-promote this PDP. + */ + + long electionWaitSleepTime = 15000; + + /* + * Sleep 5 seconds after each test to allow interrupt (shutdown) recovery. + */ + + long interruptRecoveryTime = 5000; + + private static EntityManagerFactory emfx; + private static EntityManagerFactory emfd; + private static EntityManager emx; + private static EntityManager emd; + private static EntityTransaction et; + + private final String configDir = "src/test/resources"; + + /* + * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing. + */ + + @BeforeClass + public static void setUpClass() throws Exception { + + String userDir = System.getProperty("user.dir"); + logger.debug("setUpClass: userDir={}", userDir); + System.setProperty("com.sun.management.jmxremote.port", "9980"); + System.setProperty("com.sun.management.jmxremote.authenticate","false"); + + } + + @AfterClass + public static void tearDownClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + //Create teh data access for xaml db + Properties stateManagementProperties = new Properties(); + stateManagementProperties.load(new FileInputStream(new File( + "src/test/resources/feature-state-management.properties"))); + + emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties); + + // Create an entity manager to use the DB + emx = emfx.createEntityManager(); + + //Create the data access for drools db + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + "src/test/resources/feature-active-standby-management.properties"))); + + emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties); + + // Create an entity manager to use the DB + emd = emfd.createEntityManager(); + } + + @After + public void tearDown() throws Exception { + + } + + public void cleanXacmlDb(){ + et = emx.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate(); + emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate(); + emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate(); + emx.flush(); + et.commit(); + } + + public void cleanDroolsDb(){ + et = emd.getTransaction(); + + et.begin(); + // Make sure we leave the DB clean + emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate(); + emd.flush(); + et.commit(); + } + + /* + * These JUnit tests must be run one at a time in an eclipse environment + * by right-clicking StandbyStateManagementTest and selecting + * "Run As" -> "JUnit Test". + * + * They will run successfully when you run all of them under runAllTests(), + * however, you will get all sorts of non-fatal errors in the log and on the + * console that result from overlapping threads that are not terminated at the + * end of each test. The problem is that the JUnit environment does not terminate + * all the test threads between tests. This is true even if you break each JUnit + * into a separate file. Consequently, all the tests would have to be refactored + * so all test object initializations are coordinated. In other words, you + * retrieve the ActiveStandbyFeature instance and other class instances only once + * at the beginning of the JUnits and then reuse them throughout the tests. + * Initialization of the state of the objects is pretty straight forward as it + * just amounts to manipulating the entries in StateManagementEntity and + * DroolsPdpEntity tables. However, some thought needs to be given to how to + * "pause" the processing in ActiveStandbyFeature class. I think we could "pause" + * it by calling globalInit() which will, I think, restart it. So long as it + * does not create a new instance, it will force it to go through an initialization + * cycle which includes a "pause" at the beginning of proecessing. We just must + * be sure it does not create another instance - which may mean we need to add + * a factory interface instead of calling the constructor directly. + */ + + + //@Ignore + @Test + public void runAllTests() throws Exception { + testColdStandby(); + testHotStandby1(); + testHotStandby2(); + testLocking1(); + testLocking2(); + testPMStandbyStateChangeNotifier(); + testSanitizeDesignatedList(); + testComputeMostRecentPrimary(); + testComputeDesignatedPdp(); + } + + //@Ignore + //@Test + public void testPMStandbyStateChangeNotifier() throws Exception { + logger.debug("\n\ntestPMStandbyStateChangeNotifier: Entering\n\n"); + cleanXacmlDb(); + + logger.debug("testPMStandbyStateChangeNotifier: Reading activeStandbyProperties"); + + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + ActiveStandbyProperties.initProperties(activeStandbyProperties); + String thisPdpId = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testPMStandbyStateChangeNotifier: Getting StateManagementFeatureAPI"); + + StateManagementFeatureAPI sm = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + sm = feature; + logger.debug("testPMStandbyStateChangeNotifier stateManagementFeature.getResourceName(): {}", sm.getResourceName()); + break; + } + if(sm == null){ + logger.error("testPMStandbyStateChangeNotifier failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testPMStandbyStateChangeNotifier failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + //Create an instance of the Observer + PMStandbyStateChangeNotifier pmNotifier = new PMStandbyStateChangeNotifier(); + + //Register the PMStandbyStateChangeNotifier Observer + sm.addObserver(pmNotifier); + + //At this point the standbystatus = 'null' + sm.lock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE)); + + sm.unlock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.NULL_VALUE)); + + //Adding standbystatus=hotstandby + sm.demote(); + System.out.println(pmNotifier.getPreviousStandbyStatus()); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //Now making standbystatus=coldstandby + sm.lock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = hotstandby + sm.unlock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = providingservice + sm.promote(); + //The previousStandbyStatus is not updated until after the delay activation expires + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //Sleep long enough for the delayActivationTimer to run + Thread.sleep(5000); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + //standbystatus = providingservice + sm.promote(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(StateManagement.PROVIDING_SERVICE)); + + //standbystatus = coldstandby + sm.lock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = hotstandby + sm.unlock(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + + //standbystatus = hotstandby + sm.demote(); + assertTrue(pmNotifier.getPreviousStandbyStatus().equals(PMStandbyStateChangeNotifier.HOTSTANDBY_OR_COLDSTANDBY)); + } + + //@Ignore + //@Test + public void testSanitizeDesignatedList() throws Exception { + + logger.debug("\n\ntestSanitizeDesignatedList: Entering\n\n"); + + // Get a DroolsPdpsConnector + + logger.debug("testSanitizeDesignatedList: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testSanitizeDesignatedList: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); + + // Create 4 pdpd all not designated + + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); + + ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>(); + listOfDesignated.add(pdp1); + listOfDesignated.add(pdp2); + listOfDesignated.add(pdp3); + listOfDesignated.add(pdp4); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI stateManagementFeature = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + stateManagementFeature = feature; + logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", stateManagementFeature.getResourceName()); + break; + } + if(stateManagementFeature == null){ + logger.error("testColdStandby failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testColdStandby failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + + DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); + + listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); + + logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size = {}\n\n",listOfDesignated.size()); + + assertTrue(listOfDesignated.size()==4); + + // Now make 2 designated + + pdp1.setDesignated(true); + pdp2.setDesignated(true); + + listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); + + logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after 2 designated = {}\n\n", listOfDesignated.size()); + + assertTrue(listOfDesignated.size()==2); + assertTrue(listOfDesignated.contains(pdp1)); + assertTrue(listOfDesignated.contains(pdp2)); + + + // Now all are designated. But, we have to add back the previously non-designated nodes + + pdp3.setDesignated(true); + pdp4.setDesignated(true); + listOfDesignated.add(pdp3); + listOfDesignated.add(pdp4); + + listOfDesignated = droolsPdpsElectionHandler.santizeDesignatedList(listOfDesignated); + + logger.debug("\n\ntestSanitizeDesignatedList: listOfDesignated.size after all designated = {}\n\n", listOfDesignated.size()); + + assertTrue(listOfDesignated.size()==4); + + } + + + //@Ignore + //@Test + public void testComputeMostRecentPrimary() throws Exception { + + logger.debug("\n\ntestComputeMostRecentPrimary: Entering\n\n"); + + logger.debug("testComputeMostRecentPrimary: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testComputeMostRecentPrimary: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); + + + // Create 4 pdpd all not designated + + + long designatedDateMS = new Date().getTime(); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); + pdp1.setDesignatedDate(new Date(designatedDateMS - 2)); + + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); + //oldest + pdp2.setDesignatedDate(new Date(designatedDateMS - 3)); + + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); + pdp3.setDesignatedDate(new Date(designatedDateMS - 1)); + + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); + //most recent + pdp4.setDesignatedDate(new Date(designatedDateMS)); + + ArrayList<DroolsPdp> listOfAllPdps = new ArrayList<DroolsPdp>(); + listOfAllPdps.add(pdp1); + listOfAllPdps.add(pdp2); + listOfAllPdps.add(pdp3); + listOfAllPdps.add(pdp4); + + + ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>(); + listOfDesignated.add(pdp1); + listOfDesignated.add(pdp2); + listOfDesignated.add(pdp3); + listOfDesignated.add(pdp4); + + // Because the way we sanitize the listOfDesignated, it will always contain all hot standby + // or all designated members. + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI stateManagementFeature = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + stateManagementFeature = feature; + logger.debug("testComputeMostRecentPrimary stateManagementFeature.getResourceName(): {}", stateManagementFeature.getResourceName()); + break; + } + if(stateManagementFeature == null){ + logger.error("testComputeMostRecentPrimary failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testComputeMostRecentPrimary failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); + + DroolsPdp mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = {}\n\n", mostRecentPrimary.getPdpId()); + + + // If all of the pdps are included in the listOfDesignated and none are designated, it will choose + // the one which has the most recent designated date. + + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + // Now let's designate all of those on the listOfDesignated. It will choose the first one designated + + + pdp1.setDesignated(true); + pdp2.setDesignated(true); + pdp3.setDesignated(true); + pdp4.setDesignated(true); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: All designated all on list, mostRecentPrimary.getPdpId() = {}\n\n", mostRecentPrimary.getPdpId()); + + + // If all of the pdps are included in the listOfDesignated and all are designated, it will choose + // the one which was designated first + + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp2")); + + + // Now we will designate only 2 and put just them in the listOfDesignated. The algorithm will now + // look for the most recently designated pdp which is not currently designated. + + + pdp3.setDesignated(false); + pdp4.setDesignated(false); + + listOfDesignated.remove(pdp3); + listOfDesignated.remove(pdp4); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: mostRecentPrimary.getPdpId() = {}\n\n", mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + + // Now we will have none designated and put two of them in the listOfDesignated. The algorithm will now + // look for the most recently designated pdp regardless of whether it is currently marked as designated. + + + pdp1.setDesignated(false); + pdp2.setDesignated(false); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: 2 on list mostRecentPrimary.getPdpId() = {}\n\n", mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + // If we have only one pdp on in the listOfDesignated, the most recently designated pdp will be chosen, regardless + // of its designation status + + + listOfDesignated.remove(pdp1); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: 1 on list mostRecentPrimary.getPdpId() = {}\n\n", mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + + // Finally, if none are on the listOfDesignated, it will again choose the most recently designated pdp. + + + listOfDesignated.remove(pdp2); + + mostRecentPrimary = droolsPdpsElectionHandler.computeMostRecentPrimary(listOfAllPdps, listOfDesignated); + + logger.debug("\n\ntestComputeMostRecentPrimary: 0 on list mostRecentPrimary.getPdpId() = {}\n\n", mostRecentPrimary.getPdpId()); + + assertTrue(mostRecentPrimary.getPdpId().equals("pdp4")); + + } + + //@Ignore + //@Test + public void testComputeDesignatedPdp() throws Exception{ + + logger.debug("\n\ntestComputeDesignatedPdp: Entering\n\n"); + + logger.debug("testComputeDesignatedPdp: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + + logger.debug("testComputeDesignatedPdp: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector droolsPdpsConnector = new JpaDroolsPdpsConnector(emfDrools); + + + // Create 4 pdpd all not designated. Two on site1. Two on site2 + + + long designatedDateMS = new Date().getTime(); + DroolsPdp pdp1 = new DroolsPdpImpl("pdp1", false, 4, new Date()); + pdp1.setDesignatedDate(new Date(designatedDateMS - 2)); + pdp1.setSiteName("site1"); + + DroolsPdp pdp2 = new DroolsPdpImpl("pdp2", false, 4, new Date()); + pdp2.setDesignatedDate(new Date(designatedDateMS - 3)); + pdp2.setSiteName("site1"); + + //oldest + DroolsPdp pdp3 = new DroolsPdpImpl("pdp3", false, 4, new Date()); + pdp3.setDesignatedDate(new Date(designatedDateMS - 4)); + pdp3.setSiteName("site2"); + + DroolsPdp pdp4 = new DroolsPdpImpl("pdp4", false, 4, new Date()); + //most recent + pdp4.setDesignatedDate(new Date(designatedDateMS)); + pdp4.setSiteName("site2"); + + ArrayList<DroolsPdp> listOfAllPdps = new ArrayList<DroolsPdp>(); + listOfAllPdps.add(pdp1); + listOfAllPdps.add(pdp2); + listOfAllPdps.add(pdp3); + listOfAllPdps.add(pdp4); + + + ArrayList<DroolsPdp> listOfDesignated = new ArrayList<DroolsPdp>(); + + + // We will first test an empty listOfDesignated. As we know from the previous JUnit, + // the pdp with the most designated date will be chosen for mostRecentPrimary + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI stateManagementFeature = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + stateManagementFeature = feature; + logger.debug("testComputeDesignatedPdp stateManagementFeature.getResourceName(): {}", stateManagementFeature.getResourceName()); + break; + } + if(stateManagementFeature == null){ + logger.error("testComputeDesignatedPdp failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testComputeDesignatedPdp failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + + DroolsPdpsElectionHandler droolsPdpsElectionHandler = new DroolsPdpsElectionHandler(droolsPdpsConnector, pdp1); + + DroolsPdp mostRecentPrimary = pdp4; + + DroolsPdp designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // The designatedPdp should be null + + assertTrue(designatedPdp==null); + + + // Now let's try having only one pdp in listOfDesignated, but not in the same site as the most recent primary + + listOfDesignated.add(pdp2); + + designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // Now the designatedPdp should be the one and only selection in the listOfDesignated + + + assertTrue(designatedPdp.getPdpId().equals(pdp2.getPdpId())); + + + // Now let's put 2 pdps in the listOfDesignated, neither in the same site as the mostRecentPrimary + + + listOfDesignated.add(pdp1); + + designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // The designatedPdp should now be the one with the lowest lexiographic score - pdp1 + + + assertTrue(designatedPdp.getPdpId().equals(pdp1.getPdpId())); + + + // Finally, we will have 2 pdps in the listOfDesignated, one in the same site with the mostRecentPrimary + + + listOfDesignated.remove(pdp1); + listOfDesignated.add(pdp3); + + designatedPdp = droolsPdpsElectionHandler.computeDesignatedPdp(listOfDesignated, mostRecentPrimary); + + + // The designatedPdp should now be the one on the same site as the mostRecentPrimary + + + assertTrue(designatedPdp.getPdpId().equals(pdp3.getPdpId())); + } + + //@Ignore + //@Test + public void testColdStandby() throws Exception { + + logger.debug("\n\ntestColdStandby: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + logger.debug("testColdStandby: Reading stateManagementProperties"); + Properties stateManagementProperties = new Properties(); + stateManagementProperties.load(new FileInputStream(new File( + configDir + "/feature-state-management.properties"))); + + logger.debug("testColdStandby: Creating emfXacml"); + EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + logger.debug("testColdStandby: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testColdStandby: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testColdStandby: Cleaning up tables"); + conn.deleteAllPdps(); + + logger.debug("testColdStandby: Inserting PDP={} as designated", thisPdpId); + DroolsPdp pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date()); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testColdStandby: After insertion, DESIGNATED= {} " + + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + + /* + * When the Standby Status changes (from providingservice) to hotstandby + * or coldstandby,the Active/Standby selection algorithm must stand down + * if thePDP-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. + */ + + + /* + * Yes, this is kludgy, but we have a chicken and egg problem here: we + * need a StateManagement object to invoke the + * deleteAllStateManagementEntities method. + */ + logger.debug("testColdStandby: Instantiating stateManagement object"); + + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI smf = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + smf = feature; + logger.debug("testColdStandby stateManagementFeature.getResourceName(): {}", smf.getResourceName()); + break; + } + if(smf == null){ + logger.error("testColdStandby failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testColdStandby failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureAPI activeStandbyFeature = null; + for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + activeStandbyFeature = feature; + logger.debug("testColdStandby activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); + break; + } + if(activeStandbyFeature == null){ + logger.error("testColdStandby failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID:{}", thisPdpId); + logger.debug("testColdStandby failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID:{}", thisPdpId); + } + + // Artificially putting a PDP into service is really a two step process, 1) + // inserting it as designated and 2) promoting it so that its standbyStatus + // is providing service. + + logger.debug("testColdStandby: Runner started; Sleeping " + + interruptRecoveryTime + "ms before promoting PDP= {}", + thisPdpId); + Thread.sleep(interruptRecoveryTime); + + logger.debug("testColdStandby: Promoting PDP={}", thisPdpId); + smf.promote(); + + String standbyStatus = sm.getStandbyStatus(thisPdpId); + logger.debug("testColdStandby: Before locking, PDP= {} has standbyStatus= {}", + thisPdpId, standbyStatus); + + logger.debug("testColdStandby: Locking smf"); + smf.lock(); + + Thread.sleep(interruptRecoveryTime); + + // Verify that the PDP is no longer designated. + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testColdStandby: After lock sm.lock() invoked, " + + "DESIGNATED= {} for PDP={}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("\n\ntestColdStandby: Exiting\n\n"); + Thread.sleep(interruptRecoveryTime); + + } + + // Tests hot standby when there is only one PDP. + + //@Ignore + //@Test + public void testHotStandby1() throws Exception { + + logger.debug("\n\ntestHotStandby1: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + logger.debug("testHotStandby1: Reading stateManagementProperties"); + Properties stateManagementProperties = new Properties(); + stateManagementProperties.load(new FileInputStream(new File( + configDir + "/feature-state-management.properties"))); + + logger.debug("testHotStandby1: Creating emfXacml"); + EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + logger.debug("testHotStandby1: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testHotStandby1: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testHotStandby1: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + logger.debug("testHotStandby1: Inserting PDP={} as not designated", thisPdpId); + Date yesterday = DateUtils.addDays(new Date(), -1); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testHotStandby1: After insertion, PDP={} has DESIGNATED={}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("testHotStandby1: Instantiating stateManagement object"); + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI smf = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + smf = feature; + logger.debug("testHotStandby1 stateManagementFeature.getResourceName(): {}", smf.getResourceName()); + break; + } + if(smf == null){ + logger.error("testHotStandby1 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testHotStandby1 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureAPI activeStandbyFeature = null; + for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + activeStandbyFeature = feature; + logger.debug("testHotStandby1 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); + break; + } + if(activeStandbyFeature == null){ + logger.error("testHotStandby1 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testHotStandby1 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + + logger.debug("testHotStandby1: Demoting PDP={}", thisPdpId); + // demoting should cause state to transit to hotstandby + smf.demote(); + + + logger.debug("testHotStandby1: Sleeping {} ms, to allow JpaDroolsPdpsConnector " + + "time to check droolspdpentity table", sleepTime); + Thread.sleep(sleepTime); + + + // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service. + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testHotStandby1: After sm.demote() invoked, DESIGNATED= {} " + + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + String standbyStatus = smf.getStandbyStatus(thisPdpId); + logger.debug("testHotStandby1: After demotion, PDP= {} " + + "has standbyStatus= {}", thisPdpId, standbyStatus); + assertTrue(standbyStatus != null && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); + + logger.debug("testHotStandby1: Stopping policyManagementRunner"); + //policyManagementRunner.stopRunner(); + + logger.debug("\n\ntestHotStandby1: Exiting\n\n"); + Thread.sleep(interruptRecoveryTime); + + } + + /* + * Tests hot standby when two PDPs are involved. + */ + + //@Ignore + //@Test + public void testHotStandby2() throws Exception { + + logger.info("\n\ntestHotStandby2: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + logger.info("testHotStandby2: Reading stateManagementProperties"); + Properties stateManagementProperties = new Properties(); + stateManagementProperties.load(new FileInputStream(new File( + configDir + "/feature-state-management.properties"))); + + logger.info("testHotStandby2: Creating emfXacml"); + EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + logger.info("testHotStandby2: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.info("testHotStandby2: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.info("testHotStandby2: Cleaning up tables"); + conn.deleteAllPdps(); + + + // Insert a PDP that's designated but not current. + + String activePdpId = "pdp2"; + logger.info("testHotStandby2: Inserting PDP={} as stale, designated PDP", activePdpId); + Date yesterday = DateUtils.addDays(new Date(), -1); + DroolsPdp pdp = new DroolsPdpImpl(activePdpId, true, 4, yesterday); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(activePdpId); + logger.info("testHotStandby2: After insertion, PDP= {}, which is " + + "not current, has DESIGNATED= {}", activePdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == true); + + /* + * Promote the designated PDP. + * + * We have a chicken and egg problem here: we need a StateManagement + * object to invoke the deleteAllStateManagementEntities method. + */ + + + logger.info("testHotStandby2: Promoting PDP={}", activePdpId); + StateManagement sm = new StateManagement(emfXacml, "dummy"); + sm.deleteAllStateManagementEntities(); + + + sm = new StateManagement(emfXacml, activePdpId);//pdp2 + + // Artificially putting a PDP into service is really a two step process, 1) + // inserting it as designated and 2) promoting it so that its standbyStatus + // is providing service. + + /* + * Insert this PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + + logger.info("testHotStandby2: Inserting PDP= {} as not designated", thisPdpId); + pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.info("testHotStandby2: After insertion, PDP={} " + + "has DESIGNATED= {}", thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI sm2 = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + sm2 = feature; + logger.debug("testHotStandby2 stateManagementFeature.getResourceName(): {}", sm2.getResourceName()); + break; + } + if(sm2 == null){ + logger.error("testHotStandby2 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testHotStandby2 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureAPI activeStandbyFeature = null; + for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + activeStandbyFeature = feature; + logger.debug("testHotStandby2 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); + break; + } + if(activeStandbyFeature == null){ + logger.error("testHotStandby2 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testHotStandby2 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + logger.info("testHotStandby2: Runner started; Sleeping {} " + + "ms before promoting/demoting", interruptRecoveryTime); + Thread.sleep(interruptRecoveryTime); + + logger.info("testHotStandby2: Runner started; promoting PDP={}", activePdpId); + //At this point, the newly created pdp will have set the state to disabled/failed/cold standby + //because it is stale. So, it cannot be promoted. We need to call sm.enableNotFailed() so we + //can promote it and demote the other pdp - else the other pdp will just spring back to providingservice + sm.enableNotFailed();//pdp2 + sm.promote(); + String standbyStatus = sm.getStandbyStatus(activePdpId); + logger.info("testHotStandby2: After promoting, PDP= {} has standbyStatus= {}", activePdpId, standbyStatus); + + // demoting PDP should ensure that state transits to hotstandby + logger.info("testHotStandby2: Runner started; demoting PDP= {}", thisPdpId); + sm2.demote();//pdp1 + standbyStatus = sm.getStandbyStatus(thisPdpId); + logger.info("testHotStandby2: After demoting, PDP={} has standbyStatus= {}",thisPdpId , standbyStatus); + + logger.info("testHotStandby2: Sleeping {} ms, to allow JpaDroolsPdpsConnector " + + "time to check droolspdpentity table", sleepTime); + Thread.sleep(sleepTime); + + /* + * Verify that this PDP, demoted to HOT_STANDBY, is now + * re-designated and providing service. + */ + + droolsPdpEntity = conn.getPdp(thisPdpId); + logger.info("testHotStandby2: After demoting PDP={}" + + ", DESIGNATED= {}" + + " for PDP= {}", activePdpId, droolsPdpEntity.isDesignated(), thisPdpId); + assertTrue(droolsPdpEntity.isDesignated() == true); + standbyStatus = sm2.getStandbyStatus(thisPdpId); + logger.info("testHotStandby2: After demoting PDP={}" + + ", PDP={} has standbyStatus= {}", + activePdpId, thisPdpId, standbyStatus); + assertTrue(standbyStatus != null + && standbyStatus.equals(StateManagement.PROVIDING_SERVICE)); + + logger.info("testHotStandby2: Stopping policyManagementRunner"); + //policyManagementRunner.stopRunner(); + + logger.info("\n\ntestHotStandby2: Exiting\n\n"); + Thread.sleep(interruptRecoveryTime); + + } + + /* + * 1) Inserts and designates this PDP, then verifies that startTransaction + * is successful. + * + * 2) Demotes PDP, and verifies that because there is only one PDP, it will + * be immediately re-promoted, thus allowing startTransaction to be + * successful. + * + * 3) Locks PDP and verifies that startTransaction results in + * AdministrativeStateException. + * + * 4) Unlocks PDP and verifies that startTransaction results in + * StandbyStatusException. + * + * 5) Promotes PDP and verifies that startTransaction is once again + * successful. + */ + + //@Ignore + //@Test + public void testLocking1() throws Exception { + logger.debug("testLocking1: Entry"); + cleanXacmlDb(); + cleanDroolsDb(); + + logger.debug("testLocking1: Reading stateManagementProperties"); + Properties stateManagementProperties = new Properties(); + stateManagementProperties.load(new FileInputStream(new File( + configDir + "/feature-state-management.properties"))); + + logger.debug("testLocking1: Creating emfXacml"); + EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + logger.debug("testLocking1: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testLocking1: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testLocking1: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as designated. Initial standby state will be + * either null or cold standby. + */ + + logger.debug("testLocking1: Inserting PDP= {} as designated", thisPdpId); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 4, new Date()); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testLocking1: After insertion, PDP= {} has DESIGNATED= {}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == true); + + logger.debug("testLocking1: Instantiating stateManagement object"); + StateManagement smDummy = new StateManagement(emfXacml, "dummy"); + smDummy.deleteAllStateManagementEntities(); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI sm = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + sm = feature; + logger.debug("testLocking1 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); + break; + } + if(sm == null){ + logger.error("testLocking1 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testLocking1 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureAPI activeStandbyFeature = null; + for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + activeStandbyFeature = feature; + logger.debug("testLocking1 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); + break; + } + if(activeStandbyFeature == null){ + logger.error("testLocking1 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testLocking1 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + logger.debug("testLocking1: Runner started; Sleeping " + + interruptRecoveryTime + "ms before promoting PDP={}", + thisPdpId); + Thread.sleep(interruptRecoveryTime); + + logger.debug("testLocking1: Promoting PDP={}", thisPdpId); + sm.promote(); + + logger.debug("testLocking1: Sleeping {} ms, to allow time for " + + "policy-management.Main class to come up, designated= {}", + sleepTime, conn.getPdp(thisPdpId).isDesignated()); + Thread.sleep(sleepTime); + + logger.debug("testLocking1: Waking up and invoking startTransaction on active PDP={}" + + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + + + IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance(); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking1: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + // demoting should cause state to transit to hotstandby, followed by re-promotion, + // since there is only one PDP. + logger.debug("testLocking1: demoting PDP={}", thisPdpId); + sm.demote(); + + logger.debug("testLocking1: sleeping" + electionWaitSleepTime + + " to allow election handler to re-promote PDP={}", thisPdpId); + Thread.sleep(electionWaitSleepTime); + + logger.debug("testLocking1: Invoking startTransaction on re-promoted PDP={}" + + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking1: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + // locking should cause state to transit to cold standby + logger.debug("testLocking1: locking PDP={}", thisPdpId); + sm.lock(); + + // Just to avoid any race conditions, sleep a little after locking + logger.debug("testLocking1: Sleeping a few millis after locking, to avoid race condition"); + Thread.sleep(100); + + logger.debug("testLocking1: Invoking startTransaction on locked PDP= {}" + + ", designated= {}",thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + logger.error("testLocking1: startTransaction unexpectedly successful"); + assertTrue(false); + } catch (AdministrativeStateException e) { + logger.debug("testLocking1: As expected, caught AdministrativeStateException, ", e); + } catch (StandbyStatusException e) { + logger.error("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } finally { + droolsPdpIntegrityMonitor.endTransaction(); + } + + // unlocking should cause state to transit to hot standby and then providing service + logger.debug("testLocking1: unlocking PDP={}", thisPdpId); + sm.unlock(); + + // Just to avoid any race conditions, sleep a little after locking + logger.debug("testLocking1: Sleeping a few millis after unlocking, to avoid race condition"); + Thread.sleep(electionWaitSleepTime); + + logger.debug("testLocking1: Invoking startTransaction on unlocked PDP=" + + thisPdpId + + ", designated=" + + conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + logger.error("testLocking1: startTransaction successful as expected"); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.debug("testLocking1: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } finally { + droolsPdpIntegrityMonitor.endTransaction(); + } + + // demoting should cause state to transit to hot standby + logger.debug("testLocking1: demoting PDP={}", thisPdpId); + sm.demote(); + + // Just to avoid any race conditions, sleep a little after promoting + logger.debug("testLocking1: Sleeping a few millis after demoting, to avoid race condition"); + Thread.sleep(100); + + logger.debug("testLocking1: Invoking startTransaction on demoted PDP={}" + + ", designated={}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking1: Unexpectedly, transaction successful"); + assertTrue(false); + } catch (AdministrativeStateException e) { + logger.error("testLocking1: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking1: As expected caught StandbyStatusException, ", e); + } catch (Exception e) { + logger.error("testLocking1: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + logger.debug("\n\ntestLocking1: Exiting\n\n"); + Thread.sleep(interruptRecoveryTime); + + } + + + /* + * 1) Inserts and designates this PDP, then verifies that startTransaction + * is successful. + * + * 2) Inserts another PDP in hotstandby. + * + * 3) Demotes this PDP, and verifies 1) that other PDP is not promoted (because one + * PDP cannot promote another PDP) and 2) that this PDP is re-promoted. + */ + + //@Ignore + //@Test + public void testLocking2() throws Exception { + + logger.debug("\n\ntestLocking2: Entering\n\n"); + cleanXacmlDb(); + cleanDroolsDb(); + + logger.debug("testLocking2: Reading stateManagementProperties"); + Properties stateManagementProperties = new Properties(); + stateManagementProperties.load(new FileInputStream(new File( + configDir + "/feature-state-management.properties"))); + + logger.debug("testLocking2: Creating emfXacml"); + EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory( + "junitXacmlPU", stateManagementProperties); + + logger.debug("testLocking2: Reading activeStandbyProperties"); + Properties activeStandbyProperties = new Properties(); + activeStandbyProperties.load(new FileInputStream(new File( + configDir + "/feature-active-standby-management.properties"))); + String thisPdpId = activeStandbyProperties + .getProperty(ActiveStandbyProperties.NODE_NAME); + + logger.debug("testLocking2: Creating emfDrools"); + EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory( + "junitDroolsPU", activeStandbyProperties); + + DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools); + + logger.debug("testLocking2: Cleaning up tables"); + conn.deleteAllPdps(); + + /* + * Insert this PDP as designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + logger.debug("testLocking2: Inserting PDP= {} as designated", thisPdpId); + DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, true, 3, new Date()); + conn.insertPdp(pdp); + DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId); + logger.debug("testLocking2: After insertion, PDP= {} has DESIGNATED= {}", + thisPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == true); + + logger.debug("testLocking2: Instantiating stateManagement object and promoting PDP={}", thisPdpId); + StateManagement smDummy = new StateManagement(emfXacml, "dummy"); + smDummy.deleteAllStateManagementEntities(); + + // Now we want to create a StateManagementFeature and initialize it. It will be + // discovered by the ActiveStandbyFeature when the election handler initializes. + + StateManagementFeatureAPI sm = null; + for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + sm = feature; + logger.debug("testLocking2 stateManagementFeature.getResourceName(): {}", sm.getResourceName()); + break; + } + if(sm == null){ + logger.error("testLocking2 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testLocking2 failed to initialize. " + + "Unable to get instance of StateManagementFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature + // that has been created. + ActiveStandbyFeatureAPI activeStandbyFeature = null; + for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList()) + { + ((PolicySessionFeatureAPI) feature).globalInit(null, configDir); + activeStandbyFeature = feature; + logger.debug("testLocking2 activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName()); + break; + } + if(activeStandbyFeature == null){ + logger.error("testLocking2 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + logger.debug("testLocking2 failed to initialize. " + + "Unable to get instance of ActiveStandbyFeatureAPI " + + "with resourceID: {}", thisPdpId); + } + + /* + * Insert another PDP as not designated. Initial standby state will be + * either null or cold standby. Demoting should transit state to + * hot standby. + */ + + String standbyPdpId = "pdp2"; + logger.debug("testLocking2: Inserting PDP= {} as not designated", standbyPdpId); + Date yesterday = DateUtils.addDays(new Date(), -1); + pdp = new DroolsPdpImpl(standbyPdpId, false, 4, yesterday); + conn.insertPdp(pdp); + droolsPdpEntity = conn.getPdp(standbyPdpId); + logger.debug("testLocking2: After insertion, PDP={} has DESIGNATED= {}", + standbyPdpId, droolsPdpEntity.isDesignated()); + assertTrue(droolsPdpEntity.isDesignated() == false); + + logger.debug("testLocking2: Demoting PDP= {}", standbyPdpId); + StateManagement sm2 = new StateManagement(emfXacml, standbyPdpId); + + logger.debug("testLocking2: Runner started; Sleeping {} ms " + + "before promoting/demoting", interruptRecoveryTime); + Thread.sleep(interruptRecoveryTime); + + logger.debug("testLocking2: Promoting PDP= {}", thisPdpId); + sm.promote(); + + // demoting PDP should ensure that state transits to hotstandby + logger.debug("testLocking2: Demoting PDP={}", standbyPdpId); + sm2.demote(); + + logger.debug("testLocking2: Sleeping {} ms, to allow time for to come up", sleepTime); + Thread.sleep(sleepTime); + + logger.debug("testLocking2: Waking up and invoking startTransaction on active PDP={}" + + ", designated= {}", thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + + IntegrityMonitor droolsPdpIntegrityMonitor = IntegrityMonitor.getInstance(); + + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking2: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking2: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking2: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + // demoting should cause state to transit to hotstandby followed by re-promotion. + logger.debug("testLocking2: demoting PDP={}", thisPdpId); + sm.demote(); + + logger.debug("testLocking2: sleeping {}" + + " to allow election handler to re-promote PDP={}", electionWaitSleepTime, thisPdpId); + Thread.sleep(electionWaitSleepTime); + + logger.debug("testLocking2: Waking up and invoking startTransaction " + + "on re-promoted PDP= {}, designated= {}", + thisPdpId, conn.getPdp(thisPdpId).isDesignated()); + try { + droolsPdpIntegrityMonitor.startTransaction(); + droolsPdpIntegrityMonitor.endTransaction(); + logger.debug("testLocking2: As expected, transaction successful"); + } catch (AdministrativeStateException e) { + logger.error("testLocking2: Unexpectedly caught AdministrativeStateException, ", e); + assertTrue(false); + } catch (StandbyStatusException e) { + logger.error("testLocking2: Unexpectedly caught StandbyStatusException, ", e); + assertTrue(false); + } catch (Exception e) { + logger.error("testLocking2: Unexpectedly caught Exception, ", e); + assertTrue(false); + } + + logger.debug("testLocking2: Verifying designated status for PDP= {}", standbyPdpId); + boolean standbyPdpDesignated = conn.getPdp(standbyPdpId).isDesignated(); + assertTrue(standbyPdpDesignated == false); + + logger.debug("\n\ntestLocking2: Exiting\n\n"); + Thread.sleep(interruptRecoveryTime); + } +} diff --git a/feature-active-standby-management/src/test/resources/META-INF/persistence.xml b/feature-active-standby-management/src/test/resources/META-INF/persistence.xml new file mode 100644 index 00000000..ff6ac58a --- /dev/null +++ b/feature-active-standby-management/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,47 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + feature-active-standby-management + ================================================================================ + 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========================================================= + --> + +<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="junitDroolsPU" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.onap.policy.drools.activestandby.DroolsPdpEntity</class> + <properties> + <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> + <property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/> + <property name="javax.persistence.schema-generation.scripts.create-target" value="./sql/generatedCreateDrools.ddl"/> + <property name="javax.persistence.schema-generation.scripts.drop-target" value="./sql/generatedDropDrools.ddl"/> + </properties> + </persistence-unit> + <persistence-unit name="junitXacmlPU" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <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> + <properties> + <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> + <property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/> + <property name="javax.persistence.schema-generation.scripts.create-target" value="./sql/generatedCreateXacml.ddl"/> + <property name="javax.persistence.schema-generation.scripts.drop-target" value="./sql/generatedDropXacml.ddl"/> + </properties> + </persistence-unit> +</persistence> diff --git a/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties b/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties new file mode 100644 index 00000000..bbae5d98 --- /dev/null +++ b/feature-active-standby-management/src/test/resources/feature-active-standby-management.properties @@ -0,0 +1,39 @@ +### +# ============LICENSE_START======================================================= +# feature-active-standby-management +# ================================================================================ +# 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========================================================= +### + +# DB properties +javax.persistence.jdbc.driver = org.h2.Driver +javax.persistence.jdbc.url = jdbc:h2:file:./sql/activestandbymanagement +javax.persistence.jdbc.user = sa +javax.persistence.jdbc.password = + +# Must be unique across the system +resource.name=pdp1 +# Name of the site in which this node is hosted +site_name=pdp_1 + +# Needed by DroolsPdpsElectionHandler +pdp.checkInterval=1500 +pdp.updateInterval=1000 +#pdp.timeout=3000 +# Need long timeout, because testTransaction is only run every 10 seconds. +pdp.timeout=15000 +#how long do we wait for the pdp table to populate on initial startup +pdp.initialWait=20000
\ No newline at end of file diff --git a/feature-active-standby-management/src/test/resources/feature-state-management.properties b/feature-active-standby-management/src/test/resources/feature-state-management.properties new file mode 100644 index 00000000..3d767a17 --- /dev/null +++ b/feature-active-standby-management/src/test/resources/feature-state-management.properties @@ -0,0 +1,74 @@ +### +# ============LICENSE_START======================================================= +# feature-active-standby-management +# ================================================================================ +# 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========================================================= +### + +# DB properties +javax.persistence.jdbc.driver = org.h2.Driver +javax.persistence.jdbc.url = jdbc:h2:file:./sql/statemanagement +javax.persistence.jdbc.user = sa +javax.persistence.jdbc.password = + +# DroolsPDPIntegrityMonitor Properties +hostPort = 0.0.0.0:57692 + +#IntegrityMonitor Properties + +# Must be unique across the system +resource.name=pdp1 +# Name of the site in which this node is hosted +site_name = pdp_1 +# Forward Progress Monitor update interval seconds +fp_monitor_interval = 30 +# Failed counter threshold before failover +failed_counter_threshold = 3 +# Interval between test transactions when no traffic seconds +test_trans_interval = 10 +# Interval between writes of the FPC to the DB seconds +write_fpc_interval = 5 +# Node type Note: Make sure you don't leave any trailing spaces, or you'll get an 'invalid node type' error! +node_type = pdp_drools +# Dependency groups are groups of resources upon which a node operational state is dependent upon. +# Each group is a comma-separated list of resource names and groups are separated by a semicolon. For example: +# dependency_groups=site_1.astra_1,site_1.astra_2;site_1.brms_1,site_1.brms_2;site_1.logparser_1;site_1.pypdp_1 +dependency_groups= +# When set to true, dependent health checks are performed by using JMX to invoke test() on the dependent. +# The default false is to use state checks for health. +test_via_jmx=true +# This is the max number of seconds beyond which a non incrementing FPC is considered a failure +max_fpc_update_interval=120 +# Run the state audit every 60 seconds (60000 ms). The state audit finds stale DB entries in the +# forwardprogressentity table and marks the node as disabled/failed in the statemanagemententity +# table. NOTE! It will only run on nodes that have a standbystatus = providingservice. +# A value of <= 0 will turn off the state audit. +state_audit_interval_ms=60000 +# The refresh state audit is run every (default) 10 minutes (600000 ms) to clean up any state corruption in the +# DB statemanagemententity table. It only refreshes the DB state entry for the local node. That is, it does not +# refresh the state of any other nodes. A value <= 0 will turn the audit off. Any other value will override +# the default of 600000 ms. +refresh_state_audit_interval_ms=600000 + + +# Repository audit properties +# Flag to control the execution of the subsystemTest for the Nexus Maven repository +repository.audit.is.active=false +repository.audit.ignore.errors=true + +# DB Audit Properties +# Flag to control the execution of the subsystemTest for the Database +db.audit.is.active=false diff --git a/feature-active-standby-management/src/test/resources/logback-test.xml b/feature-active-standby-management/src/test/resources/logback-test.xml new file mode 100644 index 00000000..a36bdb16 --- /dev/null +++ b/feature-active-standby-management/src/test/resources/logback-test.xml @@ -0,0 +1,46 @@ +<!-- + ============LICENSE_START======================================================= + feature-state-management + ================================================================================ + 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========================================================= + --> + +<!-- Controls the output of logs for JUnit tests --> + +<configuration> + + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> + <Pattern> + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n + </Pattern> + </encoder> + </appender> + <appender name="FILE" class="ch.qos.logback.core.FileAppender"> + <file>logs/debug.log</file> + <encoder> + <Pattern> + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n + </Pattern> + </encoder> + </appender> + + <root level="debug"> + <appender-ref ref="STDOUT" /> + <appender-ref ref="FILE" /> + </root> + +</configuration> diff --git a/feature-healthcheck/.gitignore b/feature-healthcheck/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/feature-healthcheck/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java index 5cbcf555..cc6f02e0 100644 --- a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java @@ -144,6 +144,7 @@ class HealthCheckMonitor implements HealthCheck { /** * {@inheritDoc} */ + @Override public Reports healthCheck() { Reports reports = new Reports(); reports.healthy = PolicyEngine.manager.isAlive(); @@ -152,8 +153,8 @@ class HealthCheckMonitor implements HealthCheck { engineReport.healthy = PolicyEngine.manager.isAlive(); engineReport.name = "PDP-D"; engineReport.url = "self"; - engineReport.code = (PolicyEngine.manager.isAlive()) ? 200 : 500; - engineReport.message = (PolicyEngine.manager.isAlive()) ? "alive" : "not alive"; + engineReport.code = PolicyEngine.manager.isAlive() ? 200 : 500; + engineReport.message = PolicyEngine.manager.isAlive() ? "alive" : "not alive"; reports.details.add(engineReport); for (HttpClient client : clients) { diff --git a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java index a618f033..1c0b45fb 100644 --- a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java +++ b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java @@ -22,28 +22,20 @@ package org.onap.policy.drools.healthcheck; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; -import java.io.FileOutputStream; import java.io.FileWriter; -import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; import java.util.Properties; import org.junit.AfterClass; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.onap.policy.drools.healthcheck.HealthCheck.Report; import org.onap.policy.drools.healthcheck.HealthCheck.Reports; -import org.onap.policy.drools.http.client.HttpClient; -import org.onap.policy.drools.http.server.HttpServletServer; import org.onap.policy.drools.persistence.SystemPersistence; import org.onap.policy.drools.properties.PolicyProperties; import org.onap.policy.drools.system.PolicyEngine; diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java index fabcbc03..1c935b0c 100644 --- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java +++ b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsPersistenceProperties.java @@ -21,6 +21,8 @@ package org.onap.policy.drools.persistence; public class DroolsPersistenceProperties { + private DroolsPersistenceProperties() { + } /* * feature-session-persistence.properties parameter key values */ diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java index 71f5ec9a..e9c5b33b 100644 --- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java +++ b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/DroolsSessionEntity.java @@ -91,22 +91,23 @@ public class DroolsSessionEntity implements Serializable, DroolsSession { public void setSessionId(long sessionId) { this.sessionId = sessionId; } - + + @Override public Date getCreatedDate() { return createdDate; } - + @Override public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } - + @Override public Date getUpdatedDate() { return updatedDate; } - + @Override public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } diff --git a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java index b48690b0..db33d05a 100644 --- a/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java +++ b/feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java @@ -143,7 +143,7 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine policyContainer.setAdjunct(this, rval); } - return ((ContainerAdjunct) rval); + return (ContainerAdjunct) rval; } /** @@ -151,7 +151,7 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine */ @Override public int getSequenceNumber() { - return (1); + return 1; } /** @@ -201,9 +201,9 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine public PolicySession.ThreadModel selectThreadModel(PolicySession session) { PolicyContainer policyContainer = session.getPolicyContainer(); if (isPersistenceEnabled(policyContainer, session.getName())) { - return (new PersistentThreadModel(session, getProperties(policyContainer))); + return new PersistentThreadModel(session, getProperties(policyContainer)); } - return (null); + return null; } /** @@ -372,8 +372,8 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine KieSessionConfiguration kConf = kieSvcFact.newKieSessionConfiguration(); - KieSession kieSession = (desiredSessionId >= 0 ? loadKieSession(kieBaseName, desiredSessionId, env, kConf) - : null); + KieSession kieSession = desiredSessionId >= 0 ? loadKieSession(kieBaseName, desiredSessionId, env, kConf) + : null; if (kieSession == null) { // loadKieSession() returned null or desiredSessionId < 0 @@ -609,7 +609,7 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine */ private long getSessionId(DroolsSessionConnector conn, String sessnm) { DroolsSession sess = conn.get(sessnm); - return (sess != null ? sess.getSessionId() : -1); + return sess != null ? sess.getSessionId() : -1; } /** @@ -650,10 +650,10 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine if (properties != null) { // fetch the 'type' property String type = getProperty(properties, sessionName, "type"); - rval = ("auto".equals(type) || "native".equals(type)); + rval = "auto".equals(type) || "native".equals(type); } - return (rval); + return rval; } /** @@ -665,10 +665,10 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine */ private Properties getProperties(PolicyContainer container) { try { - return (fact.getPolicyContainer(container).getProperties()); + return fact.getPolicyContainer(container).getProperties(); } catch (IllegalArgumentException e) { logger.error("getProperties exception: ", e); - return (null); + return null; } } @@ -694,7 +694,7 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine value = properties.getProperty("persistence." + property); } - return (value); + return value; } /* ============================================================ */ @@ -790,7 +790,7 @@ public class PersistenceFeature implements PolicySessionFeatureAPI, PolicyEngine * @return the String to use as the thread name */ private String getThreadName() { - return ("Session " + session.getFullName() + " (persistent)"); + return "Session " + session.getFullName() + " (persistent)"; } /***************************/ diff --git a/feature-session-persistence/src/test/resources/logback-test.xml b/feature-session-persistence/src/test/resources/logback-test.xml index 5aeaf90f..6e919eb9 100644 --- a/feature-session-persistence/src/test/resources/logback-test.xml +++ b/feature-session-persistence/src/test/resources/logback-test.xml @@ -22,18 +22,25 @@ <configuration> - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> - <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> - <Pattern> - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n - </Pattern> - </encoder> - </appender> - - <logger name="org.onap.policy.drools.persistence" level="INFO"/> - - <root level="warn"> - <appender-ref ref="STDOUT"/> - </root> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> + <Pattern> + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n + </Pattern> + </encoder> + </appender> + <appender name="FILE" class="ch.qos.logback.core.FileAppender"> + <file>logs/debug.log</file> + <encoder> + <Pattern> + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n + </Pattern> + </encoder> + </appender> + + <root level="debug"> + <appender-ref ref="STDOUT" /> + <appender-ref ref="FILE" /> + </root> </configuration> diff --git a/feature-state-management/.gitignore b/feature-state-management/.gitignore new file mode 100644 index 00000000..b83d2226 --- /dev/null +++ b/feature-state-management/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/feature-state-management/pom.xml b/feature-state-management/pom.xml index 5265cdbb..033d36d6 100644 --- a/feature-state-management/pom.xml +++ b/feature-state-management/pom.xml @@ -133,5 +133,10 @@ <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DbAudit.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DbAudit.java index 8de170c7..cde6e4e4 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DbAudit.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DbAudit.java @@ -46,6 +46,9 @@ public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase static public boolean isJunit = false; + synchronized private static void setCreateTableNeeded(boolean b) { + DbAudit.createTableNeeded = b; + } /** * @return the single 'DbAudit' instance */ @@ -103,26 +106,17 @@ public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase String user = properties.getProperty(StateManagementProperties.DB_USER); String password = properties.getProperty(StateManagementProperties.DB_PWD); - // connection to DB - Connection connection = null; - - // supports SQL operations - PreparedStatement statement = null; - ResultSet rs = null; - // operation phase currently running -- used to construct an error // message, if needed String phase = null; - try + // create connection to DB + phase = "creating connection"; + if(logger.isDebugEnabled()){ + logger.debug("DbAudit: Creating connection to {}", url); + } + try (Connection connection = DriverManager.getConnection(url, user, password)) { - // create connection to DB - phase = "creating connection"; - if(logger.isDebugEnabled()){ - logger.debug("DbAudit: Creating connection to {}", url); - } - - connection = DriverManager.getConnection(url, user, password); // create audit table, if needed if (createTableNeeded) @@ -131,93 +125,68 @@ public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase if(logger.isDebugEnabled()){ logger.info("DbAudit: Creating 'Audit' table, if needed"); } - statement = connection.prepareStatement + try (PreparedStatement statement = connection.prepareStatement ("CREATE TABLE IF NOT EXISTS Audit (\n" + " name varchar(64) DEFAULT NULL,\n" + " UNIQUE KEY name (name)\n" - + ") DEFAULT CHARSET=latin1;"); - statement.execute(); - statement.close(); - createTableNeeded = false; + + ") DEFAULT CHARSET=latin1;")) { + statement.execute(); + DbAudit.setCreateTableNeeded(false); + } catch (Exception e) { + throw e; + } } // insert an entry into the table phase = "insert entry"; String key = UUID.randomUUID().toString(); - statement = connection.prepareStatement - ("INSERT INTO Audit (name) VALUES (?)"); - statement.setString(1, key); - statement.executeUpdate(); - statement.close(); - + try (PreparedStatement statement = connection.prepareStatement + ("INSERT INTO Audit (name) VALUES (?)")) { + statement.setString(1, key); + statement.executeUpdate(); + } catch (Exception e) { + throw e; + } + // fetch the entry from the table phase = "fetch entry"; - statement = connection.prepareStatement - ("SELECT name FROM Audit WHERE name = ?"); - statement.setString(1, key); - rs = statement.executeQuery(); - if (rs.first()) - { - // found entry - if(logger.isDebugEnabled()){ - logger.debug("DbAudit: Found key {}", rs.getString(1)); + try (PreparedStatement statement = connection.prepareStatement + ("SELECT name FROM Audit WHERE name = ?")) { + statement.setString(1, key); + try (ResultSet rs = statement.executeQuery()) { + if (rs.first()) + { + // found entry + if(logger.isDebugEnabled()){ + logger.debug("DbAudit: Found key {}", rs.getString(1)); + } + } + else + { + logger.error + ("DbAudit: can't find newly-created entry with key {}", key); + setResponse("Can't find newly-created entry"); + } + } catch (Exception e) { + throw e; } - } - else - { - logger.error - ("DbAudit: can't find newly-created entry with key {}", key); - setResponse("Can't find newly-created entry"); - } - statement.close(); - + } // delete entries from table phase = "delete entry"; - statement = connection.prepareStatement - ("DELETE FROM Audit WHERE name = ?"); - statement.setString(1, key); - statement.executeUpdate(); - statement.close(); - statement = null; - } + try (PreparedStatement statement = connection.prepareStatement + ("DELETE FROM Audit WHERE name = ?")) { + statement.setString(1, key); + statement.executeUpdate(); + } catch (Exception e) { + throw e; + } + } catch (Exception e) { String message = "DbAudit: Exception during audit, phase = " + phase; logger.error(message, e); setResponse(message); } - finally - { - if (rs != null) - { - try - { - rs.close(); - } - catch (Exception e) - { - } - } - if (statement != null) - { - try - { - statement.close(); - } - catch (Exception e) - { - } - } - if (connection != null) - { - try - { - connection.close(); - } - catch (Exception e) - { - } - } - } } + } diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java index 73f6f738..3b7410fa 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java @@ -20,20 +20,17 @@ package org.onap.policy.drools.statemanagement; -import java.io.File; -import java.io.FileInputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Properties; import org.onap.policy.common.im.IntegrityMonitor; import org.onap.policy.common.im.IntegrityMonitorException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.http.server.HttpServletServer; import org.onap.policy.drools.properties.Startable; import org.onap.policy.drools.utils.PropertyUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class extends 'IntegrityMonitor' for use in the 'Drools PDP' @@ -90,62 +87,62 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor if (resourceName == null) { logger.error("init: Missing IntegrityMonitor property: 'resource.name'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'resource.name'")); + throw new Exception + ("Missing IntegrityMonitor property: 'resource.name'"); } if (hostPort == null) { logger.error("init: Missing IntegrityMonitor property: 'hostPort'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'hostPort'")); + throw new Exception + ("Missing IntegrityMonitor property: 'hostPort'"); } if (fpMonitorInterval == null) { logger.error("init: Missing IntegrityMonitor property: 'fp_monitor_interval'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'fp_monitor_interval'")); + throw new Exception + ("Missing IntegrityMonitor property: 'fp_monitor_interval'"); } if (failedCounterThreshold == null) { logger.error("init: Missing IntegrityMonitor property: 'failed_counter_threshold'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'failed_counter_threshold'")); + throw new Exception + ("Missing IntegrityMonitor property: 'failed_counter_threshold'"); } if (testTransInterval == null) { logger.error("init: Missing IntegrityMonitor property: 'test_trans_interval'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'test_trans_interval'")); + throw new Exception + ("Missing IntegrityMonitor property: 'test_trans_interval'"); } if (writeFpcInterval == null) { logger.error("init: Missing IntegrityMonitor property: 'write_fpc_interval'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'write_fpc_interval'")); + throw new Exception + ("Missing IntegrityMonitor property: 'write_fpc_interval'"); } if (siteName == null) { logger.error("init: Missing IntegrityMonitor property: 'site_name'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'site_name'")); + throw new Exception + ("Missing IntegrityMonitor property: 'site_name'"); } if (nodeType == null) { logger.error("init: Missing IntegrityMonitor property: 'node_type'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'node_type'")); + throw new Exception + ("Missing IntegrityMonitor property: 'node_type'"); } if (dependencyGroups == null) { logger.error("init: Missing IntegrityMonitor property: 'dependency_groups'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'dependency_groups'")); + throw new Exception + ("Missing IntegrityMonitor property: 'dependency_groups'"); } if (javaxPersistenceJdbcDriver == null) { logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for xacml DB'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for xacml DB'")); + throw new Exception + ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.driver for xacml DB'"); } if (javaxPersistenceJdbcUrl == null) { @@ -156,14 +153,14 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor if (javaxPersistenceJdbcUser == null) { logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for xacml DB'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for xacml DB'")); + throw new Exception + ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.user for xacml DB'"); } if (javaxPersistenceJdbcPassword == null) { logger.error("init: Missing IntegrityMonitor property: 'javax.persistence.jbdc.password for xacml DB'"); - throw(new Exception - ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.password' for xacml DB'")); + throw new Exception + ("Missing IntegrityMonitor property: 'javax.persistence.jbdc.password' for xacml DB'"); } // Now that we've validated the properties, create Drools Integrity Monitor @@ -303,7 +300,7 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor */ public String getName() { - return(name); + return name; } /** @@ -311,7 +308,7 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor */ public String getResponse() { - return(response); + return response; } /** @@ -351,10 +348,11 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor try { server.waitedStart(5); } catch (Exception e) { - e.printStackTrace(); + logger.error("Exception waiting for servers to start: ", e); } } } catch (Exception e) { + logger.error("Exception building servers", e); return false; } @@ -366,7 +364,7 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor try { server.stop(); } catch (Exception e) { - e.printStackTrace(); + logger.error("Exception during stop", e); } return true; diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/IntegrityMonitorRestManager.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/IntegrityMonitorRestManager.java index f5024299..ed522fce 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/IntegrityMonitorRestManager.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/IntegrityMonitorRestManager.java @@ -77,8 +77,6 @@ public class IntegrityMonitorRestManager { im = DroolsPDPIntegrityMonitor.getInstance(); } catch (Exception e) { logger.error("IntegrityMonitorRestManager: test() interface caught an exception", e); - e.printStackTrace(); - body.append("\nException: " + e + "\n"); responseValue = 500; } diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/RepositoryAudit.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/RepositoryAudit.java index 94464cd4..b36c1657 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/RepositoryAudit.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/RepositoryAudit.java @@ -53,7 +53,7 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase */ public static DroolsPDPIntegrityMonitor.AuditBase getInstance() { - return(instance); + return instance; } /** @@ -123,8 +123,8 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase String repositoryPassword = StateManagementProperties.getProperty("repository.audit.password"); boolean upload = - (repositoryId != null && repositoryUrl != null - && repositoryUsername != null && repositoryPassword != null); + repositoryId != null && repositoryUrl != null + && repositoryUsername != null && repositoryPassword != null; // used to incrementally construct response as problems occur // (empty = no problems) @@ -335,11 +335,17 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase // place output in 'fileContents' (replacing the Return characters // with Newline) byte[] outputData = new byte[(int)output.length()]; - FileInputStream fis = new FileInputStream(output); - fis.read(outputData); - String fileContents = new String(outputData).replace('\r','\n'); - fis.close(); - + String fileContents; + try (FileInputStream fis = new FileInputStream(output)) { + // + // Ideally this should be in a loop or even better use + // Java 8 nio functionality. + // + int bytesRead = fis.read(outputData); + logger.info("fileContents read {} bytes", bytesRead); + fileContents = new String(outputData).replace('\r','\n'); + } + // generate log messages from 'Downloading' and 'Downloaded' // messages within the 'mvn' output int index = 0; @@ -404,8 +410,8 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase "curl", "--request", "DELETE", "--user", repositoryUsername + ":" + repositoryPassword, - (repositoryUrl + "/" + groupId.replace('.', '/') + "/" + - artifactId + "/" + version)) + repositoryUrl + "/" + groupId.replace('.', '/') + "/" + + artifactId + "/" + version) != 0) { logger.error @@ -431,13 +437,15 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase (dir, new SimpleFileVisitor<Path>() { + @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { // logger.info("RepositoryAudit: Delete " + file); file.toFile().delete(); - return(FileVisitResult.CONTINUE); + return FileVisitResult.CONTINUE; } + @Override public FileVisitResult postVisitDirectory(Path file, IOException e) throws IOException { @@ -445,11 +453,11 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase { // logger.info("RepositoryAudit: Delete " + file); file.toFile().delete(); - return(FileVisitResult.CONTINUE); + return FileVisitResult.CONTINUE; } else { - throw(e); + throw e; } } }); @@ -486,12 +494,12 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase if (process.waitFor(timeoutInSeconds, TimeUnit.SECONDS)) { // process terminated before the timeout - return(process.exitValue()); + return process.exitValue(); } // process timed out -- kill it, and return -1 process.destroyForcibly(); - return(-1); + return -1; } /* ============================================================ */ @@ -532,21 +540,22 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase String[] segments = artifact.split("/"); if (segments.length != 4 && segments.length != 3) { - throw(new IllegalArgumentException("groupId/artifactId/version/type")); + throw new IllegalArgumentException("groupId/artifactId/version/type"); } groupId = segments[0]; artifactId = segments[1]; version = segments[2]; - type = (segments.length == 4 ? segments[3] : "jar"); + type = segments.length == 4 ? segments[3] : "jar"; } /** * @return the artifact id in the form: * "<groupId>/<artifactId>/<version>/<type>" */ + @Override public String toString() { - return(groupId + "/" + artifactId + "/" + version + "/" + type); + return groupId + "/" + artifactId + "/" + version + "/" + type; } } } diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java index 6d47039e..0143c58b 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java @@ -24,14 +24,13 @@ import java.io.IOException; import java.util.Observer; import java.util.Properties; -import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI; import org.onap.policy.common.im.StandbyStatusException; import org.onap.policy.common.im.StateManagement; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.onap.policy.drools.core.PolicySessionFeatureAPI; import org.onap.policy.drools.features.PolicyEngineFeatureAPI; import org.onap.policy.drools.utils.PropertyUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * If this feature is supported, there is a single instance of it. @@ -100,14 +99,12 @@ public class StateManagementFeature implements StateManagementFeatureAPI, } } } catch (Exception e1) { - String msg = " \n"; if(logger.isDebugEnabled()){ logger.debug("StateManagementFeature.globalInit(): DroolsPDPIntegrityMonitor" + " initialization failed with exception:", e1); } logger.error("DroolsPDPIntegrityMonitor.init(): StateManagementFeature startup failed " + "to get DroolsPDPIntegrityMonitor instance:", e1); - e1.printStackTrace(); } } diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java index c8e17ea9..f90f7482 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java @@ -38,6 +38,9 @@ public class StateManagementProperties { public static final String DB_PWD = "javax.persistence.jdbc.password"; private static Properties properties = null; + + private StateManagementProperties(){ + } /* * Initialize the parameter values from the feature-state-management.properties file values * diff --git a/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java b/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java index 8adb9462..ba7ce3ea 100644 --- a/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java +++ b/feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java @@ -38,8 +38,6 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.onap.policy.common.im.StateManagement; import org.onap.policy.drools.core.PolicySessionFeatureAPI; import org.onap.policy.drools.statemanagement.DbAudit; @@ -47,6 +45,8 @@ import org.onap.policy.drools.statemanagement.IntegrityMonitorRestManager; import org.onap.policy.drools.statemanagement.RepositoryAudit; import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI; import org.onap.policy.drools.statemanagement.StateManagementProperties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class StateManagementTest { diff --git a/packages/install/pom.xml b/packages/install/pom.xml index 7a765c3a..f1bde432 100644 --- a/packages/install/pom.xml +++ b/packages/install/pom.xml @@ -101,6 +101,12 @@ <version>${project.version}</version> <type>zip</type> </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>feature-active-standby-management</artifactId> + <version>${project.version}</version> + <type>zip</type> + </dependency> </dependencies> </project> diff --git a/policy-core/drools-artifact-1.1/pom.xml b/policy-core/drools-artifact-1.1/pom.xml new file mode 100644 index 00000000..24a6d37d --- /dev/null +++ b/policy-core/drools-artifact-1.1/pom.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + ONAP Policy Engine - Drools PDP + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>drools-artifact1</artifactId> + <version>17.1.0-SNAPSHOT</version> + <description>supports Junit tests in policy-core</description> + + <parent> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>drools-pdp</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> +</project> diff --git a/policy-core/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml b/policy-core/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml new file mode 100644 index 00000000..22319689 --- /dev/null +++ b/policy-core/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> + <kbase name="rules"> + <ksession name="session1"/> + </kbase> +</kmodule> diff --git a/policy-core/drools-artifact-1.1/src/main/resources/rules.drl b/policy-core/drools-artifact-1.1/src/main/resources/rules.drl new file mode 100644 index 00000000..9dac208b --- /dev/null +++ b/policy-core/drools-artifact-1.1/src/main/resources/rules.drl @@ -0,0 +1,30 @@ +package org.onap.policy.drools.core.test; + +rule "Initialization" + when + then + { + System.out.println("Initialization rule running"); + } +end + +rule "Add elements of an int array" + when + $object : Object() + then + { + if ($object instanceof int[]) + { + int[] array = (int[])($object); + + System.out.println("Received array of length " + array.length); + int sum = 0; + for (int i = 1 ; i < array.length ; i += 1) + { + sum += array[i]; + } + array[0] = sum; + retract($object); + } + } +end diff --git a/policy-core/drools-artifact-1.2/pom.xml b/policy-core/drools-artifact-1.2/pom.xml new file mode 100644 index 00000000..6b39d7c4 --- /dev/null +++ b/policy-core/drools-artifact-1.2/pom.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + ONAP Policy Engine - Drools PDP + ================================================================================ + 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========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <artifactId>drools-artifact1</artifactId> + <version>17.2.0-SNAPSHOT</version> + <description>supports Junit tests in policy-core</description> + + <parent> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>drools-pdp</artifactId> + <version>1.1.0-SNAPSHOT</version> + </parent> +</project> diff --git a/policy-core/drools-artifact-1.2/src/main/resources/META-INF/kmodule.xml b/policy-core/drools-artifact-1.2/src/main/resources/META-INF/kmodule.xml new file mode 100644 index 00000000..22319689 --- /dev/null +++ b/policy-core/drools-artifact-1.2/src/main/resources/META-INF/kmodule.xml @@ -0,0 +1,6 @@ +<?xml version="1.0" encoding="UTF-8"?> +<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> + <kbase name="rules"> + <ksession name="session1"/> + </kbase> +</kmodule> diff --git a/policy-core/drools-artifact-1.2/src/main/resources/rules.drl b/policy-core/drools-artifact-1.2/src/main/resources/rules.drl new file mode 100644 index 00000000..e69b6597 --- /dev/null +++ b/policy-core/drools-artifact-1.2/src/main/resources/rules.drl @@ -0,0 +1,29 @@ +package org.onap.policy.drools.core.test; + +rule "Initialization" + when + then + { + System.out.println("Initialization rule running"); + } +end + +rule "Multiply elements of an int array" + when + $object : Object() + then + { + if ($object instanceof int[]) + { + int[] array = (int[])($object); + + System.out.println("Received array of length " + array.length); + int product = 1; + for (int i = 1 ; i < array.length ; i += 1) + { + product *= array[i]; + } + array[0] = product; + } + } +end diff --git a/policy-core/pom.xml b/policy-core/pom.xml index 076a4bf2..53e6f4aa 100644 --- a/policy-core/pom.xml +++ b/policy-core/pom.xml @@ -30,6 +30,57 @@ <version>1.1.0-SNAPSHOT</version> </parent> + <build> + <plugins> + + <!-- + 'maven-invoker-plugin' is used to build and install two versions of a + Drools artifact, both of which are used in Junit tests. These Maven + projects are invisible to Sonar and SonarQube, so there are no + complaints about multiple projects with the same artifact, and they + don't show up in the list of files or code line counts. + --> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-invoker-plugin</artifactId> + <version>3.0.1</version> + <executions> + + <execution> + <id>drools-artifact-1.1</id> + <goals> + <goal>run</goal> + </goals> + <phase>test-compile</phase> + <configuration> + <pom>drools-artifact-1.1/pom.xml</pom> + <goals> + <goal>install</goal> + </goals> + <streamLogs>true</streamLogs> + </configuration> + </execution> + + <execution> + <id>drools-artifact-1.2</id> + <goals> + <goal>run</goal> + </goals> + <phase>test-compile</phase> + <configuration> + <pom>drools-artifact-1.2/pom.xml</pom> + <goals> + <goal>install</goal> + </goals> + <streamLogs>true</streamLogs> + </configuration> + </execution> + + </executions> + </plugin> + </plugins> + </build> + <dependencies> <dependency> <groupId>org.kie</groupId> @@ -61,5 +112,5 @@ <artifactId>junit</artifactId> <scope>test</scope> </dependency> - </dependencies> + </dependencies> </project> diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java index 9fc2c837..2da53468 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java @@ -51,11 +51,11 @@ public class PolicyContainer implements Startable // set of all 'PolicyContainer' instances static private HashSet<PolicyContainer> containers = - new HashSet<PolicyContainer>(); + new HashSet<>(); // maps feature objects to per-PolicyContainer data private ConcurrentHashMap<Object, Object> adjuncts = - new ConcurrentHashMap<Object, Object>(); + new ConcurrentHashMap<>(); // 'KieContainer' associated with this 'PolicyContainer' private KieContainer kieContainer; @@ -66,7 +66,7 @@ public class PolicyContainer implements Startable // maps session name into the associated 'PolicySession' instance private HashMap<String, PolicySession> sessions = - new HashMap<String, PolicySession>(); + new HashMap<>(); // if not null, this is a 'KieScanner' looking for updates private KieScanner scanner = null; @@ -104,21 +104,22 @@ public class PolicyContainer implements Startable */ public PolicyContainer(ReleaseId releaseId) { - if (releaseId.getVersion().contains(",")) + ReleaseId newReleaseId = releaseId; + if (newReleaseId.getVersion().contains(",")) { // this is actually a comma-separated list of release ids - releaseId = loadArtifact(releaseId.getGroupId(), - releaseId.getArtifactId(), - releaseId.getVersion()); + newReleaseId = loadArtifact(newReleaseId.getGroupId(), + newReleaseId.getArtifactId(), + newReleaseId.getVersion()); } else { - kieContainer = kieServices.newKieContainer(releaseId); + kieContainer = kieServices.newKieContainer(newReleaseId); } synchronized(containers) { - if(releaseId != null){ - logger.info("Add a new kieContainer in containers: releaseId: " + releaseId.toString()); + if(newReleaseId != null){ + logger.info("Add a new kieContainer in containers: releaseId: " + newReleaseId.toString()); }else{ logger.warn("input releaseId is null"); } @@ -182,9 +183,9 @@ public class PolicyContainer implements Startable { // all of the 'newKieContainer' invocations failed -- throw the // most recent exception - throw(exception); + throw exception; } - return(releaseId); + return releaseId; } /** @@ -198,7 +199,7 @@ public class PolicyContainer implements Startable */ public String getName() { - return(kieContainer.getReleaseId().toString()); + return kieContainer.getReleaseId().toString(); } /** @@ -206,7 +207,7 @@ public class PolicyContainer implements Startable */ public KieContainer getKieContainer() { - return(kieContainer); + return kieContainer; } /** @@ -214,7 +215,7 @@ public class PolicyContainer implements Startable */ public ClassLoader getClassLoader() { - return(kieContainer.getClassLoader()); + return kieContainer.getClassLoader(); } /** @@ -223,7 +224,7 @@ public class PolicyContainer implements Startable */ public String getGroupId() { - return(kieContainer.getReleaseId().getGroupId()); + return kieContainer.getReleaseId().getGroupId(); } /** @@ -232,7 +233,7 @@ public class PolicyContainer implements Startable */ public String getArtifactId() { - return(kieContainer.getReleaseId().getArtifactId()); + return kieContainer.getReleaseId().getArtifactId(); } /** @@ -241,7 +242,7 @@ public class PolicyContainer implements Startable */ public String getVersion() { - return(kieContainer.getReleaseId().getVersion()); + return kieContainer.getReleaseId().getVersion(); } /** @@ -253,7 +254,7 @@ public class PolicyContainer implements Startable */ public PolicySession getPolicySession(String name) { - return(sessions.get(name)); + return sessions.get(name); } /** @@ -325,7 +326,7 @@ public class PolicyContainer implements Startable logger.info("activatePolicySession:session - " + (session == null ? "null" : session.getFullName()) + " is returned."); - return(session); + return session; } } @@ -352,14 +353,14 @@ public class PolicyContainer implements Startable if(name == null){ logger.warn("adoptKieSession:input name is null"); - throw(new IllegalArgumentException + throw new IllegalArgumentException ("KieSession input name is null " - + getName())); + + getName()); }else if(kieSession == null){ logger.warn("adoptKieSession:input kieSession is null"); - throw(new IllegalArgumentException + throw new IllegalArgumentException ("KieSession '" + name + "' is null " - + getName())); + + getName()); }else { logger.info("adoptKieSession:name: " + name + " kieSession: " + kieSession); } @@ -381,17 +382,17 @@ public class PolicyContainer implements Startable // default KieBase, if it exists if (!match && kieBase != kieContainer.getKieBase()) { - throw(new IllegalArgumentException + throw new IllegalArgumentException ("KieSession '" + name + "' does not reside within container " - + getName())); + + getName()); } synchronized (sessions) { if (sessions.get(name) != null) { - throw(new IllegalStateException - ("PolicySession '" + name + "' already exists")); + throw new IllegalStateException + ("PolicySession '" + name + "' already exists"); } // create the new 'PolicySession', add it to the table, @@ -415,7 +416,7 @@ public class PolicyContainer implements Startable + feature.getClass().getName(), e); } } - return(policySession); + return policySession; } } @@ -437,8 +438,8 @@ public class PolicyContainer implements Startable releaseId.getArtifactId(), newVersion)); - List<Message> messages = (results == null ? null : results.getMessages()); - return(messages == null ? null : messages.toString()); + List<Message> messages = results == null ? null : results.getMessages(); + return messages == null ? null : messages.toString(); } /** @@ -473,7 +474,7 @@ public class PolicyContainer implements Startable session.updated(); } - return(results); + return results; } /** @@ -483,7 +484,7 @@ public class PolicyContainer implements Startable { synchronized(containers) { - return(new HashSet<PolicyContainer>(containers)); + return new HashSet<>(containers); } } @@ -495,7 +496,7 @@ public class PolicyContainer implements Startable // KLUDGE WARNING: this is a temporary workaround -- if there are // no features, we don't have persistence, and 'activate' is never // called. In this case, make sure the container is started. - if (PolicySessionFeatureAPI.impl.getList().size() == 0) + if (PolicySessionFeatureAPI.impl.getList().isEmpty()) { start(); } @@ -503,7 +504,7 @@ public class PolicyContainer implements Startable // return current set of PolicySessions synchronized(sessions) { - return(new HashSet<PolicySession>(sessions.values())); + return new HashSet<>(sessions.values()); } } @@ -518,7 +519,7 @@ public class PolicyContainer implements Startable { String version = releaseId.getVersion(); if (scannerStarted == false && scanner == null && version != null - && (version.equals("LATEST") || version.equals("RELEASE") + && ("LATEST".equals(version) || "RELEASE".equals(version) || version.endsWith("-SNAPSHOT"))) { // create the scanner, and poll at 60 second intervals @@ -529,6 +530,7 @@ public class PolicyContainer implements Startable // start this in a separate thread -- it can block for a long time new Thread("Scanner Starter " + getName()) { + @Override public void run() { scanner = kieServices.newKieScanner(kieContainer); @@ -562,10 +564,10 @@ public class PolicyContainer implements Startable if (session != null) { session.getKieSession().insert(object); - return(true); + return true; } } - return(false); + return false; } /** @@ -586,7 +588,7 @@ public class PolicyContainer implements Startable rval = true; } } - return(rval); + return rval; } /*************************/ @@ -596,6 +598,7 @@ public class PolicyContainer implements Startable /** * {@inheritDoc} */ + @Override public synchronized boolean start() { if (!isStarted) @@ -619,12 +622,13 @@ public class PolicyContainer implements Startable } isStarted = true; } - return(true); + return true; } /** * {@inheritDoc} */ + @Override public synchronized boolean stop() { if (isStarted) @@ -634,7 +638,7 @@ public class PolicyContainer implements Startable synchronized (sessions) { // local set containing all of the sessions - localSessions = new HashSet<PolicySession>(sessions.values()); + localSessions = new HashSet<>(sessions.values()); // clear the 'name->session' map in 'PolicyContainer' sessions.clear(); @@ -664,12 +668,13 @@ public class PolicyContainer implements Startable } isStarted = false; } - return(true); + return true; } /** * {@inheritDoc} */ + @Override public synchronized void shutdown() { // Note that this method does not call 'destroy' on the 'KieSession' @@ -689,9 +694,10 @@ public class PolicyContainer implements Startable /** * {@inheritDoc} */ + @Override public boolean isAlive() { - return(isStarted); + return isStarted; } /*************************/ @@ -710,7 +716,7 @@ public class PolicyContainer implements Startable synchronized (sessions) { // local set containing all of the sessions - localSessions = new HashSet<PolicySession>(sessions.values()); + localSessions = new HashSet<>(sessions.values()); // clear the 'name->session' map in 'PolicyContainer' sessions.clear(); @@ -831,7 +837,7 @@ public class PolicyContainer implements Startable */ public Object getAdjunct(Object object) { - return(adjuncts.get(object)); + return adjuncts.get(object); } /** diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java index c18c1343..2a949c0b 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java @@ -62,7 +62,7 @@ public class PolicySession // maps feature objects to per-PolicyContainer data private ConcurrentHashMap<Object, Object> adjuncts = - new ConcurrentHashMap<Object, Object>(); + new ConcurrentHashMap<>(); // associated 'KieSession' instance private KieSession kieSession; @@ -72,7 +72,7 @@ public class PolicySession // supports 'getCurrentSession()' method static private ThreadLocal<PolicySession> policySession = - new ThreadLocal<PolicySession>(); + new ThreadLocal<>(); /** * Internal constructor - create a 'PolicySession' instance @@ -96,7 +96,7 @@ public class PolicySession */ public PolicyContainer getPolicyContainer() { - return(container); + return container; } /** @@ -104,7 +104,7 @@ public class PolicySession */ public KieSession getKieSession() { - return(kieSession); + return kieSession; } /** @@ -114,7 +114,7 @@ public class PolicySession */ public String getName() { - return(name); + return name; } /** @@ -123,7 +123,7 @@ public class PolicySession */ public String getFullName() { - return(container.getName() + ":" + name); + return container.getName() + ":" + name; } /** @@ -204,7 +204,7 @@ public class PolicySession */ public static PolicySession getCurrentSession() { - return(policySession.get()); + return policySession.get(); } /** @@ -218,7 +218,7 @@ public class PolicySession */ public Object getAdjunct(Object object) { - return(adjuncts.get(object)); + return adjuncts.get(object); } /** @@ -555,19 +555,19 @@ public class PolicySession // We want to continue looping, despite any exceptions that occur // while rules are fired. - KieSession kieSession = session.getKieSession(); + KieSession kieSession1 = session.getKieSession(); while (repeat) { try { - kieSession.fireUntilHalt(); + kieSession1.fireUntilHalt(); - // if we fall through, it means 'KieSession.halt()' was called, + // if we fall through, it means 'kieSession1.halt()' was called, // but this may be a result of 'KieScanner' doing an update } catch (Exception | LinkageError e) { - logger.error("startThread error in kieSession.fireUntilHalt", e); + logger.error("startThread error in kieSession1.fireUntilHalt", e); } } logger.info("fireUntilHalt() returned"); diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java index 6777eb59..39377ab7 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java @@ -39,7 +39,7 @@ public interface PolicySessionFeatureAPI extends OrderedService * implementing the 'FeatureAPI' interface. */ static public OrderedServiceImpl<PolicySessionFeatureAPI> impl = - new OrderedServiceImpl<PolicySessionFeatureAPI>(PolicySessionFeatureAPI.class); + new OrderedServiceImpl<>(PolicySessionFeatureAPI.class); /** * This method is called during initialization at a point right after @@ -68,7 +68,7 @@ public interface PolicySessionFeatureAPI extends OrderedService default public KieSession activatePolicySession (PolicyContainer policyContainer, String name, String kieBaseName) { - return(null); + return null; } /** @@ -86,7 +86,7 @@ public interface PolicySessionFeatureAPI extends OrderedService default public PolicySession.ThreadModel selectThreadModel (PolicySession session) { - return(null); + return null; } /** diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java index d3cf2e9d..19f6afb4 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java @@ -31,16 +31,21 @@ public class PdpJmx implements PdpJmxMBean { public static PdpJmx getInstance() { return instance; } - + + @Override public long getUpdates(){ return updates.longValue(); } + + @Override public long getRulesFired(){ return actions.longValue(); } + public void updateOccured(){ updates.incrementAndGet(); } + public void ruleFired(){ actions.incrementAndGet(); } diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java index ceb7049e..9136defb 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java @@ -36,7 +36,10 @@ import org.slf4j.LoggerFactory; public class PdpJmxListener { public static final Logger logger = LoggerFactory.getLogger(PdpJmxListener.class); - + + private PdpJmxListener() { + } + public static void stop() { final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java new file mode 100644 index 00000000..e83f026c --- /dev/null +++ b/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java @@ -0,0 +1,334 @@ +/*- + * ============LICENSE_START======================================================= + * policy-core + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.core; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * These tests focus on the following classes: + * PolicyContainer + * PolicySession + * PolicySessionFeatureAPI + */ +public class DroolsContainerTest +{ + /** + * This test is centered around the creation of a 'PolicyContainer' + * and 'PolicySession', and the updating of that container to a new + * version. + */ + @Test + public void createAndUpdate() throws Exception + { + // make sure feature log starts out clean + TestPolicySessionFeatureAPI.getLog(); + + // run 'globalInit', and verify expected feature hook fired + PolicyContainer.globalInit(new String[0]); + assertEquals(buildArrayList("globalInit"), + TestPolicySessionFeatureAPI.getLog()); + + // initial conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + + // create the container, and start it + PolicyContainer container = + new PolicyContainer("org.onap.policy.drools-pdp", + "drools-artifact1", "17.1.0-SNAPSHOT"); + container.start(); + assertTrue(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(buildArrayList("activatePolicySession", + "newPolicySession", + "selectThreadModel"), + TestPolicySessionFeatureAPI.getLog()); + + // this container should be on the list + { + Collection<PolicyContainer> containers = + PolicyContainer.getPolicyContainers(); + assertEquals(1, containers.size()); + assertTrue(containers.contains(container)); + } + + // verify initial container attributes + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT", + container.getName()); + assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); + assertEquals("drools-artifact1", container.getArtifactId()); + assertEquals("17.1.0-SNAPSHOT", container.getVersion()); + + try + { + // fetch the session, and verify that it exists + PolicySession session = container.getPolicySession("session1"); + assertTrue(session != null); + + // get all sessions, and verify that this one is the only one + { + Collection<PolicySession> sessions = container.getPolicySessions(); + assertEquals(1, sessions.size()); + assertTrue(sessions.contains(session)); + } + + // verify session attributes + assertEquals(container, session.getPolicyContainer()); + assertEquals("session1", session.getName()); + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT:session1", + session.getFullName()); + + // insert a new fact + int[] a = new int[]{0, 3, 8, 2}; + session.getKieSession().insert(a); + + // the Drools rules should add 3 + 8 + 2, and store 13 in a[0] + assertTrue(waitForChange(a) == 13); + + // update the container to a new version -- + // the rules will then multiply values rather than add them + assertEquals("[]", + container.updateToVersion("17.2.0-SNAPSHOT").toString()); + + // verify expected feature hooks fired + assertEquals(buildArrayList("selectThreadModel"), + TestPolicySessionFeatureAPI.getLog()); + + // verify new container attributes + assertEquals + ("org.onap.policy.drools-pdp:drools-artifact1:17.2.0-SNAPSHOT", + container.getName()); + assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); + assertEquals("drools-artifact1", container.getArtifactId()); + assertEquals("17.2.0-SNAPSHOT", container.getVersion()); + + // verify new session attributes + assertEquals(container, session.getPolicyContainer()); + assertEquals("session1", session.getName()); + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.2.0-SNAPSHOT:session1", + session.getFullName()); + + // the updated rules should now multiply 3 * 8 * 2, and return 48 + + a[0] = 0; + container.insert("session1", a); + assertTrue(waitForChange(a) == 48); + } + finally + { + container.shutdown(); + assertFalse(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(buildArrayList("disposeKieSession"), + TestPolicySessionFeatureAPI.getLog()); + } + + // final conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + } + + /** + * This test create a 'PolicyContainer' and 'PolicySession', and verifies + * their behavior, but uses alternate interfaces to increase code coverage. + * In addition, feature hook invocations will trigger exceptions in this + * test, also to increase code coverage. + */ + @Test + public void versionList() throws Exception + { + // make sure feature log starts out clean + TestPolicySessionFeatureAPI.getLog(); + + // trigger exceptions in all feature hooks + TestPolicySessionFeatureAPI.setExceptionTrigger(true); + + // run 'globalInit', and verify expected feature hook fired + PolicyContainer.globalInit(new String[0]); + assertEquals(buildArrayList("globalInit-exception"), + TestPolicySessionFeatureAPI.getLog()); + + // initial conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + + String versionList = + "17.3.0-SNAPSHOT,17.1.0-SNAPSHOT,17.2.0-SNAPSHOT"; + + // versions should be tried in order -- the 17.1.0-SNAPSHOT should "win", + // given the fact that '17.3.0-SNAPSHOT' doesn't exist + PolicyContainer container = + new PolicyContainer("org.onap.policy.drools-pdp", + "drools-artifact1", versionList); + // the following should be equivalent to 'container.start()' + PolicyContainer.activate(); + assertTrue(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(buildArrayList("activatePolicySession-exception", + "newPolicySession-exception", + "selectThreadModel-exception"), + TestPolicySessionFeatureAPI.getLog()); + + // this container should be on the list + { + Collection<PolicyContainer> containers = + PolicyContainer.getPolicyContainers(); + assertEquals(1, containers.size()); + assertTrue(containers.contains(container)); + } + + // verify initial container attributes + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT", + container.getName()); + assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); + assertEquals("drools-artifact1", container.getArtifactId()); + assertEquals("17.1.0-SNAPSHOT", container.getVersion()); + + // some container adjunct tests + { + Object bogusAdjunct = new Object(); + + // initially, no adjunct + assertSame(null, container.getAdjunct(this)); + + // set and verify adjunct + container.setAdjunct(this, bogusAdjunct); + assertSame(bogusAdjunct, container.getAdjunct(this)); + + // clear and verify adjunct + container.setAdjunct(this, null); + assertSame(null, container.getAdjunct(this)); + } + + try + { + // fetch the session, and verify that it exists + PolicySession session = container.getPolicySession("session1"); + assertTrue(session != null); + + // get all sessions, and verify that this one is the only one + { + Collection<PolicySession> sessions = container.getPolicySessions(); + assertEquals(1, sessions.size()); + assertTrue(sessions.contains(session)); + } + + // verify session attributes + assertEquals(container, session.getPolicyContainer()); + assertEquals("session1", session.getName()); + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT:session1", + session.getFullName()); + + // some session adjunct tests + { + Object bogusAdjunct = new Object(); + + // initially, no adjunct + assertSame(null, session.getAdjunct(this)); + + // set and verify adjunct + session.setAdjunct(this, bogusAdjunct); + assertSame(bogusAdjunct, session.getAdjunct(this)); + + // clear and verify adjunct + session.setAdjunct(this, null); + assertSame(null, session.getAdjunct(this)); + } + + // insert a new fact (using 'insertAll') + int[] a = new int[]{0, 7, 3, 4}; + container.insertAll(a); + + // the Drools rules should add 7 + 3 + 4, and store 14 in a[0] + assertTrue(waitForChange(a) == 14); + + // exercise some more API methods + assertEquals(container.getClassLoader(), + container.getKieContainer().getClassLoader()); + } + finally + { + // should be equivalent to 'shutdown' without persistence + container.destroy(); + assertFalse(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(buildArrayList("destroyKieSession-exception"), + TestPolicySessionFeatureAPI.getLog()); + + // clear exception trigger + TestPolicySessionFeatureAPI.setExceptionTrigger(false); + } + + // final conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + } + + /** + * This method is tied to the expected behavior of the drools sessions. + * Initially, the value of 'array[0]' should be 0. The Drools rules + * will either add or multiply 'array[1]' through 'array[n-1]', depending + * upon the version. It waits up to 30 seconds for a non-zero value + * to appear. + */ + private int waitForChange(int[] array) throws InterruptedException + { + int rval = -1; + + // the value is tested every 1/100 of a second, and it waits up to + // 3000 iterations (= 30 seconds) for a non-zero value + for (int i = 0 ; i < 3000 ; i += 1) + { + // wait for 10 milliseconds = 1/100 of a second + Thread.sleep(10); + if ((rval = array[0]) != 0) + { + // a non-zero value has been stored + break; + } + } + return(rval); + } + + /** + * @param args an array of string arguments + * @return an ArrayList constructed from the provided arguments + */ + private ArrayList<String> buildArrayList(String... args) + { + ArrayList<String> rval = new ArrayList<>(); + for (String arg : args) + { + rval.add(arg); + } + return(rval); + } +} diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java b/policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java new file mode 100644 index 00000000..f456d814 --- /dev/null +++ b/policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * policy-core + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.core; + +import java.util.ArrayList; +import org.kie.api.runtime.KieSession; + +/** + * This class supports 'DroolsContainerTest' by implementing + * 'PolicySessionFeatureAPI', and providing a means to indicate + * which hooks have been invoked. + */ +public class TestPolicySessionFeatureAPI implements PolicySessionFeatureAPI +{ + // contains the log entries since the most recent 'getLog()' call + static private ArrayList<String> log = new ArrayList<>(); + + // if 'true', trigger an exception right after doing the log, + // to verify that exceptions are handled + static private boolean exceptionTrigger = false; + + /** + * @return the current contents of the log, and clear the log + */ + static public ArrayList<String> getLog() + { + synchronized(log) + { + ArrayList<String> rval = new ArrayList<>(log); + log.clear(); + return(rval); + } + } + + /** + * This method controls whether these hooks trigger an exception after + * being invoked. + * + * @param indicator if 'true', subsequent hook method calls will trigger + * an exception; if 'false', no exception is triggered + */ + static public void setExceptionTrigger(boolean indicator) + { + exceptionTrigger = indicator; + } + + /** + * This method adds an entry to the log, and possibly triggers an exception + * + * @param arg value to add to the log + */ + static private void addLog(String arg) + { + if (exceptionTrigger) + { + // the log entry will include a '-exception' appended to the end + synchronized(log) + { + log.add(arg + "-exception"); + } + System.out.println("*** " + arg + "-exception invoked ***"); + + // throw an exception -- it is up to the invoking code to catch it + throw(new IllegalStateException("Triggered from " + arg)); + } + else + { + // create a log entry, and display to standard output + synchronized(log) + { + log.add(arg); + } + System.out.println("*** " + arg + " invoked ***"); + } + } + + /***************************************/ + /* 'PolicySessionFeatureAPI' interface */ + /***************************************/ + + /** + * {@inheritDoc} + */ + public int getSequenceNumber() + { + return(1); + } + + /** + * {@inheritDoc} + */ + public void globalInit(String args[], String configDir) + { + addLog("globalInit"); + } + + /** + * {@inheritDoc} + */ + public KieSession activatePolicySession + (PolicyContainer policyContainer, String name, String kieBaseName) + { + addLog("activatePolicySession"); + return(null); + } + + /** + * {@inheritDoc} + */ + public void newPolicySession(PolicySession policySession) + { + addLog("newPolicySession"); + } + + /** + * {@inheritDoc} + */ + public PolicySession.ThreadModel selectThreadModel(PolicySession session) + { + addLog("selectThreadModel"); + return(null); + } + + /** + * {@inheritDoc} + */ + public void disposeKieSession(PolicySession policySession) + { + addLog("disposeKieSession"); + } + + /** + * {@inheritDoc} + */ + public void destroyKieSession(PolicySession policySession) + { + addLog("destroyKieSession"); + } +} diff --git a/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI b/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI new file mode 100644 index 00000000..d6b088c3 --- /dev/null +++ b/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI @@ -0,0 +1 @@ +org.onap.policy.drools.core.TestPolicySessionFeatureAPI diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java index d8aceca5..13808329 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java @@ -217,7 +217,7 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory { * DMaaP Topic Name Index */ protected HashMap<String, DmaapTopicSource> dmaapTopicSources = - new HashMap<String, DmaapTopicSource>(); + new HashMap<>(); /** * {@inheritDoc} @@ -322,11 +322,11 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory { String readTopics = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS); if (readTopics == null || readTopics.isEmpty()) { logger.info("{}: no topic for DMaaP Source", this); - return new ArrayList<DmaapTopicSource>(); + return new ArrayList<>(); } - List<String> readTopicList = new ArrayList<String>(Arrays.asList(readTopics.split("\\s*,\\s*"))); + List<String> readTopicList = new ArrayList<>(Arrays.asList(readTopics.split("\\s*,\\s*"))); - List<DmaapTopicSource> dmaapTopicSource_s = new ArrayList<DmaapTopicSource>(); + List<DmaapTopicSource> dmaapTopicSource_s = new ArrayList<>(); synchronized(this) { for (String topic: readTopicList) { if (this.dmaapTopicSources.containsKey(topic)) { @@ -339,7 +339,7 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory { PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX); List<String> serverList; - if (servers != null && !servers.isEmpty()) serverList = new ArrayList<String>(Arrays.asList(servers.split("\\s*,\\s*"))); + if (servers != null && !servers.isEmpty()) serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); else serverList = new ArrayList<>(); String apiKey = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + @@ -572,7 +572,7 @@ class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory { @Override public synchronized List<DmaapTopicSource> inventory() { List<DmaapTopicSource> readers = - new ArrayList<DmaapTopicSource>(this.dmaapTopicSources.values()); + new ArrayList<>(this.dmaapTopicSources.values()); return readers; } diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java index d84ef355..6f3bd350 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java @@ -153,7 +153,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory { * UEB Topic Name Index */ protected HashMap<String, UebTopicSource> uebTopicSources = - new HashMap<String, UebTopicSource>(); + new HashMap<>(); /** * {@inheritDoc} @@ -209,9 +209,9 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory { logger.info("{}: no topic for UEB Source", this); return new ArrayList<UebTopicSource>(); } - List<String> readTopicList = new ArrayList<String>(Arrays.asList(readTopics.split("\\s*,\\s*"))); + List<String> readTopicList = new ArrayList<>(Arrays.asList(readTopics.split("\\s*,\\s*"))); - List<UebTopicSource> newUebTopicSources = new ArrayList<UebTopicSource>(); + List<UebTopicSource> newUebTopicSources = new ArrayList<>(); synchronized(this) { for (String topic: readTopicList) { if (this.uebTopicSources.containsKey(topic)) { @@ -228,7 +228,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory { continue; } - List<String> serverList = new ArrayList<String>(Arrays.asList(servers.split("\\s*,\\s*"))); + List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); String apiKey = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + @@ -378,7 +378,7 @@ class IndexedUebTopicSourceFactory implements UebTopicSourceFactory { @Override public synchronized List<UebTopicSource> inventory() { List<UebTopicSource> readers = - new ArrayList<UebTopicSource>(this.uebTopicSources.values()); + new ArrayList<>(this.uebTopicSources.values()); return readers; } diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java index 46d6b60f..10bc8325 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java @@ -183,7 +183,7 @@ public interface BusPublisher { if (servers == null || servers.isEmpty()) throw new IllegalArgumentException("No DMaaP servers or DME2 partner provided"); - ArrayList<String> dmaapServers = new ArrayList<String>(); + ArrayList<String> dmaapServers = new ArrayList<>(); if(useHttps){ for (String server: servers) { dmaapServers.add(server + ":3905"); @@ -205,7 +205,7 @@ public interface BusPublisher { this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); } else if (protocol == ProtocolTypeConstants.DME2) { - ArrayList<String> dmaapServers = new ArrayList<String>(); + ArrayList<String> dmaapServers = new ArrayList<>(); dmaapServers.add("0.0.0.0:3904"); this.publisher = @@ -377,8 +377,9 @@ public interface BusPublisher { props.setProperty("TransportType", "DME2"); props.setProperty("MethodType", "POST"); - for (String key : additionalProps.keySet()) { - String value = additionalProps.get(key); + for (Map.Entry<String,String> entry : additionalProps.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); if (value != null) props.setProperty(key, value); diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java index 52438381..b7df8ca3 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java @@ -87,7 +87,7 @@ public abstract class SingleThreadedBusTopicSource /** * All my subscribers for new message notifications */ - protected final ArrayList<TopicListener> topicListeners = new ArrayList<TopicListener>(); + protected final ArrayList<TopicListener> topicListeners = new ArrayList<>(); /** @@ -168,10 +168,10 @@ public abstract class SingleThreadedBusTopicSource @Override public void unregister(TopicListener topicListener) { - boolean stop = false; + boolean stop; synchronized (this) { super.unregister(topicListener); - stop = (this.topicListeners.isEmpty()); + stop = this.topicListeners.isEmpty(); } if (stop) { diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java index 0c8bf6a6..b1b29808 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java @@ -49,7 +49,7 @@ public abstract class TopicBase implements Topic { /** * event cache */ - protected CircularFifoQueue<String> recentEvents = new CircularFifoQueue<String>(10); + protected CircularFifoQueue<String> recentEvents = new CircularFifoQueue<>(10); /** * Am I running? @@ -71,7 +71,7 @@ public abstract class TopicBase implements Topic { /** * All my subscribers for new message notifications */ - protected final ArrayList<TopicListener> topicListeners = new ArrayList<TopicListener>(); + protected final ArrayList<TopicListener> topicListeners = new ArrayList<>(); /** * Instantiates a new Topic Base diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java index aa0a8e6b..06aa4630 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java @@ -85,7 +85,7 @@ class IndexedHttpClientFactory implements HttpClientFactory { */ private static Logger logger = LoggerFactory.getLogger(IndexedHttpClientFactory.class); - protected HashMap<String, HttpClient> clients = new HashMap<String, HttpClient>(); + protected HashMap<String, HttpClient> clients = new HashMap<>(); @Override public synchronized HttpClient build(String name, boolean https, boolean selfSignedCerts, @@ -108,7 +108,7 @@ class IndexedHttpClientFactory implements HttpClientFactory { @Override public synchronized ArrayList<HttpClient> build(Properties properties) throws KeyManagementException, NoSuchAlgorithmException { - ArrayList<HttpClient> clientList = new ArrayList<HttpClient>(); + ArrayList<HttpClient> clientList = new ArrayList<>(); String clientNames = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES); if (clientNames == null || clientNames.isEmpty()) { @@ -116,7 +116,7 @@ class IndexedHttpClientFactory implements HttpClientFactory { } List<String> clientNameList = - new ArrayList<String>(Arrays.asList(clientNames.split("\\s*,\\s*"))); + new ArrayList<>(Arrays.asList(clientNames.split("\\s*,\\s*"))); for (String clientName : clientNameList) { String httpsString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + @@ -189,7 +189,7 @@ class IndexedHttpClientFactory implements HttpClientFactory { @Override public synchronized List<HttpClient> inventory() { - return new ArrayList<HttpClient>(this.clients.values()); + return new ArrayList<>(this.clients.values()); } @Override diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java index 56e9ccdd..b6366d00 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java @@ -100,7 +100,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory { /** * servers index */ - protected HashMap<Integer, HttpServletServer> servers = new HashMap<Integer, HttpServletServer>(); + protected HashMap<Integer, HttpServletServer> servers = new HashMap<>(); @Override public synchronized HttpServletServer build(String name, String host, int port, @@ -122,7 +122,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory { public synchronized ArrayList<HttpServletServer> build(Properties properties) throws IllegalArgumentException { - ArrayList<HttpServletServer> serviceList = new ArrayList<HttpServletServer>(); + ArrayList<HttpServletServer> serviceList = new ArrayList<>(); String serviceNames = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES); if (serviceNames == null || serviceNames.isEmpty()) { @@ -131,7 +131,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory { } List<String> serviceNameList = - new ArrayList<String>(Arrays.asList(serviceNames.split("\\s*,\\s*"))); + new ArrayList<>(Arrays.asList(serviceNames.split("\\s*,\\s*"))); for (String serviceName : serviceNameList) { String servicePortString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + @@ -206,14 +206,14 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory { if (restClasses != null && !restClasses.isEmpty()) { List<String> restClassesList = - new ArrayList<String>(Arrays.asList(restClasses.split("\\s*,\\s*"))); + new ArrayList<>(Arrays.asList(restClasses.split("\\s*,\\s*"))); for (String restClass : restClassesList) service.addServletClass(restUriPath, restClass); } if (restPackages != null && !restPackages.isEmpty()) { List<String> restPackageList = - new ArrayList<String>(Arrays.asList(restPackages.split("\\s*,\\s*"))); + new ArrayList<>(Arrays.asList(restPackages.split("\\s*,\\s*"))); for (String restPackage : restPackageList) service.addServletPackage(restUriPath, restPackage); } @@ -236,7 +236,7 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory { @Override public synchronized List<HttpServletServer> inventory() { - return new ArrayList<HttpServletServer>(this.servers.values()); + return new ArrayList<>(this.servers.values()); } @Override @@ -252,8 +252,8 @@ class IndexedHttpServletServerFactory implements HttpServletServerFactory { @Override public synchronized void destroy() throws IllegalArgumentException, IllegalStateException { - List<HttpServletServer> servers = this.inventory(); - for (HttpServletServer server: servers) { + List<HttpServletServer> httpServletServers = this.inventory(); + for (HttpServletServer server: httpServletServers) { server.shutdown(); } diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java index 55d058f5..e0a46173 100644 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java +++ b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java @@ -243,7 +243,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable } } - return (this.jettyServer.isRunning()); + return this.jettyServer.isRunning(); } } @@ -373,7 +373,7 @@ public abstract class JettyServletServer implements HttpServletServer, Runnable public String toString() { StringBuilder builder = new StringBuilder(); builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port) - .append(", user=").append(user).append(", password=").append((password != null)).append(", contextPath=") + .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=") .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=").append(this.context) .append(", connector=").append(connector).append(", jettyThread=").append(jettyThread) .append("]"); diff --git a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java index e217ee7d..905e50c2 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java +++ b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java @@ -27,6 +27,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Properties; @@ -208,7 +209,7 @@ public class FileSystemPersistence implements SystemPersistence { @Override public List<Properties> getControllerProperties() { final List<Properties> controllers = new ArrayList<>(); - final File[] controllerFiles = this.configurationDirectory.toFile().listFiles(); + final File[] controllerFiles = this.sortedListFiles(); for (final File controllerFile : controllerFiles) { if (controllerFile.getName().endsWith(PROPERTIES_FILE_CONTROLLER_SUFFIX)) { final int idxSuffix = controllerFile.getName().indexOf(PROPERTIES_FILE_CONTROLLER_SUFFIX); @@ -262,7 +263,7 @@ public class FileSystemPersistence implements SystemPersistence { @Override public List<Properties> getEnvironmentProperties() { final List<Properties> envs = new ArrayList<>(); - final File[] envFiles = this.configurationDirectory.toFile().listFiles(); + final File[] envFiles = this.sortedListFiles(); for (final File envFile : envFiles) { if (envFile.getName().endsWith(ENV_SUFFIX)) { final String name = envFile.getName().substring(0, envFile.getName().indexOf(ENV_SUFFIX)); @@ -290,6 +291,15 @@ public class FileSystemPersistence implements SystemPersistence { } } + /** + * provides a list of files sorted by name in ascending order in the configuration directory + */ + protected File[] sortedListFiles() { + final File[] dirFiles = this.configurationDirectory.toFile().listFiles(); + Arrays.sort(dirFiles, (a, b) -> a.getName().compareTo(b.getName())); + return dirFiles; + } + @Override public String toString() { final StringBuilder builder = new StringBuilder(); diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java index 762f4476..6f14076f 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/EventProtocolCoder.java @@ -670,13 +670,13 @@ abstract class GenericEventProtocolCoder { * and consequently the second value will be the less likely. */ protected final HashMap<String, Pair<ProtocolCoderToolset,ProtocolCoderToolset>> coders = - new HashMap<String, Pair<ProtocolCoderToolset,ProtocolCoderToolset>>(); + new HashMap<>(); /** * Mapping topic + classname -> Protocol Set */ protected final HashMap<String, List<Pair<ProtocolCoderToolset,ProtocolCoderToolset>>> reverseCoders = - new HashMap<String, List<Pair<ProtocolCoderToolset,ProtocolCoderToolset>>>(); + new HashMap<>(); protected boolean multipleToolsetRetries = false; @@ -735,7 +735,7 @@ abstract class GenericEventProtocolCoder { this, reverseKey, key, toolsets.first()); List<Pair<ProtocolCoderToolset,ProtocolCoderToolset>> reverseMappings = - new ArrayList<Pair<ProtocolCoderToolset,ProtocolCoderToolset>>(); + new ArrayList<>(); reverseMappings.add(toolsets); reverseCoders.put(reverseKey, reverseMappings); } @@ -767,7 +767,7 @@ abstract class GenericEventProtocolCoder { // are detected in the gson encoding Pair<ProtocolCoderToolset,ProtocolCoderToolset> coderTools = - new Pair<ProtocolCoderToolset,ProtocolCoderToolset>(gsonCoderTools, + new Pair<>(gsonCoderTools, jacksonCoderTools); logger.info("{}: adding coders for new {}: {}", this, key, coderTools.first()); @@ -800,7 +800,7 @@ abstract class GenericEventProtocolCoder { } } else { List<Pair<ProtocolCoderToolset,ProtocolCoderToolset>> toolsets = - new ArrayList<Pair<ProtocolCoderToolset,ProtocolCoderToolset>>(); + new ArrayList<>(); toolsets.add(coderTools); logger.info("{}: adding toolset for reverse key {}: {}", this, reverseKey, toolsets); @@ -909,7 +909,7 @@ abstract class GenericEventProtocolCoder { String key = this.codersKey(groupId, artifactId, topic); synchronized(this) { - return (coders.containsKey(key)); + return coders.containsKey(key); } } @@ -1102,7 +1102,7 @@ abstract class GenericEventProtocolCoder { protected List<DroolsController> droolsCreators(String topic, Object encodedClass) throws IllegalStateException, IllegalArgumentException { - List<DroolsController> droolsControllers = new ArrayList<DroolsController>(); + List<DroolsController> droolsControllers = new ArrayList<>(); String reverseKey = this.reverseCodersKey(topic, encodedClass.getClass().getCanonicalName()); if (!this.reverseCoders.containsKey(reverseKey)) { @@ -1127,8 +1127,8 @@ abstract class GenericEventProtocolCoder { // figure out the right toolset String groupId = encoderSet.first().getGroupId(); String artifactId = encoderSet.first().getArtifactId(); - List<CoderFilters> coders = encoderSet.first().getCoders(); - for (CoderFilters coder : coders) { + List<CoderFilters> coderFilters = encoderSet.first().getCoders(); + for (CoderFilters coder : coderFilters) { if (coder.getCodedClass().equals(encodedClass.getClass().getCanonicalName())) { DroolsController droolsController = DroolsController.factory.get(groupId, artifactId, ""); @@ -1206,7 +1206,7 @@ abstract class GenericEventProtocolCoder { String key = this.codersKey(groupId, artifactId, ""); - List<CoderFilters> codersFilters = new ArrayList<CoderFilters>(); + List<CoderFilters> codersFilters = new ArrayList<>(); for (Map.Entry<String, Pair<ProtocolCoderToolset,ProtocolCoderToolset>> entry : coders.entrySet()) { if (entry.getKey().startsWith(key)) { codersFilters.addAll(entry.getValue().first().getCoders()); @@ -1235,7 +1235,7 @@ abstract class GenericEventProtocolCoder { String key = this.codersKey(groupId, artifactId, ""); - List<Pair<ProtocolCoderToolset,ProtocolCoderToolset>> coderToolset = new ArrayList<Pair<ProtocolCoderToolset,ProtocolCoderToolset>>(); + List<Pair<ProtocolCoderToolset,ProtocolCoderToolset>> coderToolset = new ArrayList<>(); for (Map.Entry<String, Pair<ProtocolCoderToolset,ProtocolCoderToolset>> entry : coders.entrySet()) { if (entry.getKey().startsWith(key)) { coderToolset.add(entry.getValue()); @@ -1293,12 +1293,12 @@ abstract class GenericEventProtocolCoder { throw new IllegalArgumentException("No Coder found for " + key); - List<CoderFilters> coders = new ArrayList<CoderFilters>(); + List<CoderFilters> coderFilters = new ArrayList<>(); for (Pair<ProtocolCoderToolset,ProtocolCoderToolset> toolset: toolsets) { - coders.addAll(toolset.first().getCoders()); + coderFilters.addAll(toolset.first().getCoders()); } - return coders; + return coderFilters; } /** @@ -1390,4 +1390,4 @@ class EventProtocolEncoder extends GenericEventProtocolCoder { builder.append("EventProtocolEncoder [toString()=").append(super.toString()).append("]"); return builder.toString(); } -}
\ No newline at end of file +} diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilter.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilter.java index 6afeb26a..0a52d254 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilter.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/JsonProtocolFilter.java @@ -119,7 +119,7 @@ public class JsonProtocolFilter { /** * all the filters to be applied */ - protected List<FilterRule> rules = new ArrayList<FilterRule>(); + protected List<FilterRule> rules = new ArrayList<>(); /** * @@ -134,7 +134,7 @@ public class JsonProtocolFilter { throw new IllegalArgumentException("No raw filters provided"); } - List<FilterRule> filters = new ArrayList<FilterRule>(); + List<FilterRule> filters = new ArrayList<>(); for (Pair<String, String> filterPair: rawFilters) { if (filterPair.first() == null || filterPair.first().isEmpty()) { continue; diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java index 1c8dafea..df51473d 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolset.java @@ -87,7 +87,7 @@ public abstract class ProtocolCoderToolset { /** * Protocols and associated Filters */ - protected final List<CoderFilters> coders = new ArrayList<CoderFilters>(); + protected final List<CoderFilters> coders = new ArrayList<>(); /** * Tree model (instead of class model) generic parsing to be able to inspect elements @@ -488,7 +488,7 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { * Adapter for ZonedDateTime */ public static class GsonUTCAdapter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> { - + @Override public ZonedDateTime deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { try { @@ -500,6 +500,7 @@ class GsonProtocolCoderToolset extends ProtocolCoderToolset { return null; } + @Override public JsonElement serialize(ZonedDateTime datetime, Type type, JsonSerializationContext context) { return new JsonPrimitive(datetime.format(format)); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java index ded7a52c..b0b8b504 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/ControllerConfiguration.java @@ -67,7 +67,7 @@ public class ControllerConfiguration { @JsonProperty("drools") private DroolsConfiguration drools; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); protected final static Object NOT_FOUND_VALUE = new Object(); /** @@ -75,6 +75,7 @@ public class ControllerConfiguration { * */ public ControllerConfiguration() { + // Empty } /** diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/DroolsConfiguration.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/DroolsConfiguration.java index 5f32d7a4..4c672e7b 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/DroolsConfiguration.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/DroolsConfiguration.java @@ -63,7 +63,7 @@ public class DroolsConfiguration { @JsonProperty("version") private String version; @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); protected final static Object NOT_FOUND_VALUE = new Object(); /** @@ -71,6 +71,7 @@ public class DroolsConfiguration { * */ public DroolsConfiguration() { + // Empty } /** @@ -196,21 +197,21 @@ public class DroolsConfiguration { switch (name) { case "artifactId": if (value instanceof String) { - setArtifactId(((String) value)); + setArtifactId((String) value); } else { throw new IllegalArgumentException(("property \"artifactId\" is of type \"java.lang.String\", but got "+ value.getClass().toString())); } return true; case "groupId": if (value instanceof String) { - setGroupId(((String) value)); + setGroupId((String) value); } else { throw new IllegalArgumentException(("property \"groupId\" is of type \"java.lang.String\", but got "+ value.getClass().toString())); } return true; case "version": if (value instanceof String) { - setVersion(((String) value)); + setVersion((String) value); } else { throw new IllegalArgumentException(("property \"version\" is of type \"java.lang.String\", but got "+ value.getClass().toString())); } @@ -239,21 +240,21 @@ public class DroolsConfiguration { public<T >T get(String name) { Object value = declaredPropertyOrNotFound(name, DroolsConfiguration.NOT_FOUND_VALUE); if (DroolsConfiguration.NOT_FOUND_VALUE!= value) { - return ((T) value); + return (T) value; } else { - return ((T) getAdditionalProperties().get(name)); + return (T) getAdditionalProperties().get(name); } } public void set(String name, Object value) { if (!declaredProperty(name, value)) { - getAdditionalProperties().put(name, ((Object) value)); + getAdditionalProperties().put(name, value); } } public DroolsConfiguration with(String name, Object value) { if (!declaredProperty(name, value)) { - getAdditionalProperties().put(name, ((Object) value)); + getAdditionalProperties().put(name, value); } return this; } diff --git a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/PdpdConfiguration.java b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/PdpdConfiguration.java index d7295fd4..8d6f9bfd 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/PdpdConfiguration.java +++ b/policy-management/src/main/java/org/onap/policy/drools/protocol/configuration/PdpdConfiguration.java @@ -67,9 +67,9 @@ public class PdpdConfiguration { * */ @JsonProperty("controllers") - private List<ControllerConfiguration> controllers = new ArrayList<ControllerConfiguration>(); + private List<ControllerConfiguration> controllers = new ArrayList<>(); @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); + private Map<String, Object> additionalProperties = new HashMap<>(); protected final static Object NOT_FOUND_VALUE = new Object(); /** @@ -77,6 +77,7 @@ public class PdpdConfiguration { * */ public PdpdConfiguration() { + // Empty } /** @@ -201,21 +202,21 @@ public class PdpdConfiguration { switch (name) { case "requestID": if (value instanceof String) { - setRequestID(((String) value)); + setRequestID((String) value); } else { throw new IllegalArgumentException(("property \"requestID\" is of type \"java.lang.String\", but got "+ value.getClass().toString())); } return true; case "entity": if (value instanceof String) { - setEntity(((String) value)); + setEntity((String) value); } else { throw new IllegalArgumentException(("property \"entity\" is of type \"java.lang.String\", but got "+ value.getClass().toString())); } return true; case "controllers": if (value instanceof List) { - setControllers(((List<ControllerConfiguration> ) value)); + setControllers((List<ControllerConfiguration> ) value); } else { throw new IllegalArgumentException(("property \"controllers\" is of type \"java.util.List<org.onap.policy.drools.protocol.configuration.Controller>\", but got "+ value.getClass().toString())); } @@ -244,21 +245,21 @@ public class PdpdConfiguration { public<T >T get(String name) { Object value = declaredPropertyOrNotFound(name, PdpdConfiguration.NOT_FOUND_VALUE); if (PdpdConfiguration.NOT_FOUND_VALUE!= value) { - return ((T) value); + return (T) value; } else { - return ((T) getAdditionalProperties().get(name)); + return (T) getAdditionalProperties().get(name); } } public void set(String name, Object value) { if (!declaredProperty(name, value)) { - getAdditionalProperties().put(name, ((Object) value)); + getAdditionalProperties().put(name, value); } } public PdpdConfiguration with(String name, Object value) { if (!declaredProperty(name, value)) { - getAdditionalProperties().put(name, ((Object) value)); + getAdditionalProperties().put(name, value); } return this; } @@ -276,7 +277,7 @@ public class PdpdConfiguration { if ((other instanceof PdpdConfiguration) == false) { return false; } - PdpdConfiguration rhs = ((PdpdConfiguration) other); + PdpdConfiguration rhs = (PdpdConfiguration) other; return new EqualsBuilder().append(requestID, rhs.requestID).append(entity, rhs.entity).append(controllers, rhs.controllers).append(additionalProperties, rhs.additionalProperties).isEquals(); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java index 48eedfa5..93bdc0b2 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java @@ -375,6 +375,7 @@ public class RestManager { if (controller != null) return Response.status(Response.Status.NOT_MODIFIED).entity(controller).build(); } catch (final IllegalArgumentException e) { + logger.trace("OK ", e); // This is OK } catch (final IllegalStateException e) { logger.info("{}: cannot get policy-controller because of {}", this, e.getMessage(), e); diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerFactory.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerFactory.java index 34c8589f..d0b625d7 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerFactory.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyControllerFactory.java @@ -190,13 +190,13 @@ class IndexedPolicyControllerFactory implements PolicyControllerFactory { * Policy Controller Name Index */ protected HashMap<String,PolicyController> policyControllers = - new HashMap<String,PolicyController>(); + new HashMap<>(); /** * Group/Artifact Ids Index */ protected HashMap<String,PolicyController> coordinates2Controller = - new HashMap<String,PolicyController>(); + new HashMap<>(); /** * produces key for indexing controller names @@ -479,7 +479,7 @@ class IndexedPolicyControllerFactory implements PolicyControllerFactory { @Override public List<PolicyController> inventory() { List<PolicyController> controllers = - new ArrayList<PolicyController>(this.policyControllers.values()); + new ArrayList<>(this.policyControllers.values()); return controllers; } @@ -488,7 +488,7 @@ class IndexedPolicyControllerFactory implements PolicyControllerFactory { */ @Override public List<String> getFeatures() { - List<String> features = new ArrayList<String>(); + List<String> features = new ArrayList<>(); for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { features.add(feature.getName()); } diff --git a/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java b/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java index db8f306c..788da053 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java @@ -19,17 +19,23 @@ */ package org.onap.policy.drools.persistence.test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.policy.drools.persistence.FileSystemPersistence; import org.onap.policy.drools.persistence.SystemPersistence; import org.onap.policy.drools.properties.PolicyProperties; import org.slf4j.Logger; @@ -65,6 +71,14 @@ public class SystemPersistenceTest { */ public static final String TEST_CONTROLLER_FILE_BAK = TEST_CONTROLLER_NAME + "-controller.properties.bak"; + + /** + * Test JUnit Environment/Engine properties + */ + private static final String ENV_PROPS = "envProps"; + private static final String ENV_PROPS_FILE = ENV_PROPS + ".environment"; + private static final String POLICY_ENGINE_PROPERTIES_FILE = "policy-engine.properties"; + @Test public void nonDefaultConfigDir() throws IOException { @@ -78,14 +92,51 @@ public class SystemPersistenceTest { assertTrue(SystemPersistence.manager.getConfigurationPath().toString() .equals(SystemPersistence.DEFAULT_CONFIGURATION_DIR)); + this.engineConfiguration(); this.persistConfiguration(); cleanUpWorkingDirs(); } + public void engineConfiguration() { + SystemPersistence.manager.setConfigurationDir(OTHER_CONFIG_DIR); + final Path policyEnginePropsPath = Paths.get(OTHER_CONFIG_DIR + "/" + FileSystemPersistence.PROPERTIES_FILE_ENGINE); + final Path environmentPropertiesPath = Paths.get(OTHER_CONFIG_DIR + "/" + ENV_PROPS_FILE); + + Properties policyEnginePropsObject, emptyProps; + emptyProps = new Properties(); + + List<Properties> envPropertesList = new ArrayList<>(); + envPropertesList.add(emptyProps); + + policyEnginePropsObject = new Properties(); + policyEnginePropsObject.setProperty("foo", "bar"); + policyEnginePropsObject.setProperty("fiz", "buz"); + + try { + + if (Files.notExists(environmentPropertiesPath)) { + Files.createFile(environmentPropertiesPath); + } + + if (Files.notExists(policyEnginePropsPath)) { + OutputStream fout = new FileOutputStream(policyEnginePropsPath.toFile()); + policyEnginePropsObject.store(fout, ""); + fout.close(); + } + } catch (IOException e) { + logger.error("Problem creating {}", policyEnginePropsPath); + } + + assertEquals(SystemPersistence.manager.getEngineProperties(), policyEnginePropsObject); + assertEquals(SystemPersistence.manager.getEnvironmentProperties(ENV_PROPS), emptyProps); + assertEquals(SystemPersistence.manager.getEnvironmentProperties(), envPropertesList); + + } + public void persistConfiguration() { logger.info("enter"); - + final Path controllerPath = Paths .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE); @@ -121,9 +172,18 @@ public class SystemPersistenceTest { final Path testControllerBakPath = Paths .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); + final Path policyEnginePath = Paths + .get(OTHER_CONFIG_DIR + "/" + POLICY_ENGINE_PROPERTIES_FILE); + + final Path environmentPath = Paths + .get(OTHER_CONFIG_DIR + "/" + ENV_PROPS_FILE); + Files.deleteIfExists(testControllerPath); Files.deleteIfExists(testControllerBakPath); + Files.deleteIfExists(policyEnginePath); + Files.deleteIfExists(environmentPath); Files.deleteIfExists(Paths.get(OTHER_CONFIG_DIR)); + } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java new file mode 100644 index 00000000..bfebeacf --- /dev/null +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/ControllerConfigurationTest.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * Configuration Test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.drools.protocol.configuration; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.junit.Test; + +public class ControllerConfigurationTest { + + + private static final String NAME = "name"; + private static final String OPERATION = "operation"; + private static final String NAME2 = "name2"; + private static final String OPERATION2 = "operation2"; + + private static final String ARTIFACT = "org.onap.artifact"; + private static final String GROUPID = "group"; + private static final String VERSION = "1.0.0"; + + private static final String ARTIFACT2 = "org.onap.artifact2"; + private static final String GROUPID2 = "group2"; + private static final String VERSION2 = "1.0.1"; + + private static final String ADDITIONAL_PROPERTY_KEY = "foo"; + private static final String ADDITIONAL_PROPERTY_VALUE = "bar"; + + private static final DroolsConfiguration DROOLS_CONFIG = new DroolsConfiguration(ARTIFACT, GROUPID, VERSION); + private static final DroolsConfiguration DROOLS_CONFIG2 = new DroolsConfiguration(ARTIFACT2, GROUPID2, VERSION2); + + private static final String DROOLS_STRING = "drools"; + @Test + public void test() { + + Properties additionalProperties = new Properties(); + additionalProperties.put(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); + + ControllerConfiguration controllerConfig = new ControllerConfiguration(NAME, OPERATION, DROOLS_CONFIG); + + assertTrue(controllerConfig.equals(controllerConfig)); + assertFalse(controllerConfig.equals(new Object())); + + ControllerConfiguration controllerConfig2 = new ControllerConfiguration(); + controllerConfig2.setName(NAME2); + controllerConfig2.setOperation(OPERATION2); + controllerConfig2.setDrools(DROOLS_CONFIG2); + + assertEquals(controllerConfig2.getName(), NAME2); + assertEquals(controllerConfig2.getOperation(), OPERATION2); + assertEquals(controllerConfig2.getDrools(), DROOLS_CONFIG2); + + assertEquals(controllerConfig2, controllerConfig2.withName(NAME2)); + assertEquals(controllerConfig2, controllerConfig2.withOperation(OPERATION2)); + assertEquals(controllerConfig2, controllerConfig2.withDrools(DROOLS_CONFIG2)); + + controllerConfig2.setAdditionalProperty(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); + assertEquals(controllerConfig2.getAdditionalProperties(), additionalProperties); + + assertEquals(controllerConfig2, controllerConfig2.withAdditionalProperty(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE)); + + assertTrue(controllerConfig2.declaredProperty(NAME, NAME2)); + assertTrue(controllerConfig2.declaredProperty(OPERATION, OPERATION2)); + assertTrue(controllerConfig2.declaredProperty(DROOLS_STRING, DROOLS_CONFIG2)); + assertFalse(controllerConfig2.declaredProperty("dummy", NAME)); + + + assertEquals(controllerConfig2.declaredPropertyOrNotFound(NAME, NAME2), NAME2); + assertEquals(controllerConfig2.declaredPropertyOrNotFound(OPERATION, OPERATION2), OPERATION2); + assertEquals(controllerConfig2.declaredPropertyOrNotFound(DROOLS_STRING, DROOLS_CONFIG2), DROOLS_CONFIG2); + assertEquals(controllerConfig2.declaredPropertyOrNotFound("dummy", NAME), NAME); + + int hashCode = new HashCodeBuilder().append(NAME2).append(OPERATION2).append(DROOLS_CONFIG2).append(additionalProperties).toHashCode(); + assertEquals(controllerConfig2.hashCode(), hashCode); + + } + + +} diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java new file mode 100644 index 00000000..8ecda75d --- /dev/null +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/DroolsConfigurationTest.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * Configuration Test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.drools.protocol.configuration; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Properties; + +import org.apache.commons.lang3.builder.HashCodeBuilder; +import org.junit.Test; + +public class DroolsConfigurationTest { + private static final String ARTIFACT_ID_STRING = "artifactId"; + private static final String GROUP_ID_STRING = "groupId"; + private static final String VERSION_STRING = "version"; + + + private static final String NAME = "name"; + private static final String OPERATION = "operation"; + private static final String NAME2 = "name2"; + private static final String OPERATION2 = "operation2"; + + private static final String ARTIFACT = "org.onap.artifact"; + private static final String GROUPID = "group"; + private static final String VERSION = "1.0.0"; + + private static final String ARTIFACT2 = "org.onap.artifact2"; + private static final String GROUPID2 = "group2"; + private static final String VERSION2 = "1.0.1"; + + private static final String ADDITIONAL_PROPERTY_KEY = "foo"; + private static final String ADDITIONAL_PROPERTY_VALUE = "bar"; + + private static final DroolsConfiguration DROOLS_CONFIG = new DroolsConfiguration(ARTIFACT, GROUPID, VERSION); + private static final DroolsConfiguration DROOLS_CONFIG2 = new DroolsConfiguration(ARTIFACT2, GROUPID2, VERSION2); + + + + @Test + public void test() { + Properties additionalProperties = new Properties(); + additionalProperties.put(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); + + DroolsConfiguration droolsConfig = new DroolsConfiguration(ARTIFACT, GROUPID, VERSION); + assertTrue(droolsConfig.equals(droolsConfig)); + + droolsConfig.set(ARTIFACT_ID_STRING, "foobar"); + assertEquals(droolsConfig.get(ARTIFACT_ID_STRING),"foobar"); + + assertEquals(droolsConfig.with(ARTIFACT_ID_STRING, "foobar2"), droolsConfig); + + DroolsConfiguration droolsConfig2 = new DroolsConfiguration(); + droolsConfig2.setArtifactId(ARTIFACT2); + droolsConfig2.setGroupId(GROUPID2); + droolsConfig2.setVersion(VERSION2); + + assertEquals(droolsConfig2.getArtifactId(), ARTIFACT2); + assertEquals(droolsConfig2.getGroupId(), GROUPID2); + assertEquals(droolsConfig2.getVersion(), VERSION2); + + assertEquals(droolsConfig2.withArtifactId(ARTIFACT2), droolsConfig2); + assertEquals(droolsConfig2.withGroupId(GROUPID2), droolsConfig2); + assertEquals(droolsConfig2.withVersion(VERSION2), droolsConfig2); + + droolsConfig2.setAdditionalProperty(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE); + assertEquals(droolsConfig2.getAdditionalProperties(), additionalProperties); + + assertEquals(droolsConfig2, droolsConfig2.withAdditionalProperty(ADDITIONAL_PROPERTY_KEY, ADDITIONAL_PROPERTY_VALUE)); + + assertTrue(droolsConfig2.declaredProperty(ARTIFACT_ID_STRING, ARTIFACT2)); + assertTrue(droolsConfig2.declaredProperty(GROUP_ID_STRING, GROUPID2)); + assertTrue(droolsConfig2.declaredProperty(VERSION_STRING, VERSION2)); + assertFalse(droolsConfig2.declaredProperty("dummy", NAME)); + + assertEquals(droolsConfig2.declaredPropertyOrNotFound(ARTIFACT_ID_STRING, ARTIFACT2), ARTIFACT2); + assertEquals(droolsConfig2.declaredPropertyOrNotFound(GROUP_ID_STRING, GROUPID2), GROUPID2); + assertEquals(droolsConfig2.declaredPropertyOrNotFound(VERSION_STRING, VERSION2), VERSION2); + assertEquals(droolsConfig2.declaredPropertyOrNotFound("dummy", ARTIFACT2), ARTIFACT2); + + int hashCode = new HashCodeBuilder().append(ARTIFACT2).append(GROUPID2).append(VERSION2).append(additionalProperties).toHashCode(); + assertEquals(droolsConfig2.hashCode(), hashCode); + + + + + } + + +} diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java new file mode 100644 index 00000000..84c85b8a --- /dev/null +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/configuration/PdpdConfigurationTest.java @@ -0,0 +1,250 @@ +/*- + * ============LICENSE_START======================================================= + * Configuration Test + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.drools.protocol.configuration; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PdpdConfigurationTest { + + private static final Logger logger = LoggerFactory.getLogger(PdpdConfigurationTest.class); + + private static final String REQUEST_ID = UUID.randomUUID().toString(); + private static final String REQUEST_ID2 = UUID.randomUUID().toString(); + + private static final String ENTITY = "entity1"; + private static final String ENTITY2 = "entity2"; + + private static final String PROPERTY1 = "property1"; + private static final String PROPERTY2 = "property2"; + + private static final String VALUE1 = "value1"; + private static final String VALUE2 = "value2"; + + private static final String ARTIFACT = "org.onap.artifact"; + private static final String GROUPID = "group"; + private static final String VERSION = "1.0.0"; + + private static final String ARTIFACT2 = "org.onap.artifact2"; + private static final String GROUPID2 = "group2"; + private static final String VERSION2 = "1.0.1"; + + private static final String NAME = "name"; + private static final String OPERATION = "operation"; + + private static final String NAME2 = "name2"; + private static final String OPERATION2 = "operation2"; + + @Test + public void test() { + // + // Empty constructor test + // + DroolsConfiguration drools = new DroolsConfiguration(); + drools.set("artifactId", ARTIFACT); + drools.set("groupId", GROUPID); + drools.set("version", VERSION); + drools.set(PROPERTY1, VALUE1); + + assertTrue(drools.equals(drools)); + assertFalse(drools.equals(new Object())); + + logger.info("Drools HashCode {}", drools.hashCode()); + + // + // Constructor with values test get calls + // + DroolsConfiguration drools2 = new DroolsConfiguration( + drools.get("artifactId"), + drools.get("groupId"), + drools.get("version")); + + // + // get Property + // + + drools2.set(PROPERTY1, drools.get(PROPERTY1)); + + assertTrue(drools.equals(drools2)); + + // + // with methods + // + drools2.withArtifactId(ARTIFACT2).withGroupId(GROUPID2).withVersion(VERSION2).withAdditionalProperty(PROPERTY2, VALUE2); + + assertFalse(drools.equals(drools2)); + + // + // Test get additional properties + // + assertEquals(drools.getAdditionalProperties().size(), 1); + + // + // Test Not found + // + assertEquals(drools.declaredPropertyOrNotFound(PROPERTY2, DroolsConfiguration.NOT_FOUND_VALUE), DroolsConfiguration.NOT_FOUND_VALUE); + + logger.info("drools {}", drools); + logger.info("drools2 {}", drools2); + + // + // Test Controller Default Constructor + // + ControllerConfiguration controller = new ControllerConfiguration(); + + // + // Test set + // + + controller.set("name", NAME); + controller.set("operation", OPERATION); + controller.set("drools", drools); + controller.set(PROPERTY1, VALUE1); + + assertTrue(controller.equals(controller)); + assertFalse(controller.equals(new Object())); + + logger.info("Controller HashCode {}", controller.hashCode()); + + // + // Controller Constructor gets + // + ControllerConfiguration controller2 = new ControllerConfiguration( + controller.get("name"), + controller.get("operation"), + controller.get("drools")); + + // + // Test get property + // + + controller2.set(PROPERTY1, controller.get(PROPERTY1)); + + assertTrue(controller.equals(controller2)); + + // + // test with methods + // + + controller2.withDrools(drools2).withName(NAME2).withOperation(OPERATION2).withAdditionalProperty(PROPERTY2, VALUE2); + + assertFalse(controller.equals(controller2)); + + // + // Test additional properties + // + assertEquals(controller.getAdditionalProperties().size(), 1); + + // + // Not found + // + assertEquals(controller.declaredPropertyOrNotFound(PROPERTY2, ControllerConfiguration.NOT_FOUND_VALUE), ControllerConfiguration.NOT_FOUND_VALUE); + + // + // toString + // + logger.info("Controller {}", controller); + logger.info("Controller2 {}", controller2); + + // + // PDP Configuration empty constructor + // + PdpdConfiguration config = new PdpdConfiguration(); + + // + // Test set + // + + config.set("requestID", REQUEST_ID); + config.set("entity", ENTITY); + List<ControllerConfiguration> controllers = new ArrayList<>(); + controllers.add(controller); + config.set("controllers", controllers); + config.set(PROPERTY1, VALUE1); + + assertTrue(config.equals(config)); + assertFalse(config.equals(new Object())); + + logger.info("Config HashCode {}", config.hashCode()); + + // + // Test constructor with values + // + + PdpdConfiguration config2 = new PdpdConfiguration( + config.get("requestID"), + config.get("entity"), + config.get("controllers")); + + // + // Test set + // + + config2.set(PROPERTY1, config.get(PROPERTY1)); + + assertTrue(config.equals(config2)); + + // + // Test with methods + // + List<ControllerConfiguration> controllers2 = new ArrayList<>(); + controllers2.add(controller2); + config2.withRequestID(REQUEST_ID2).withEntity(ENTITY2).withController(controllers2); + + assertFalse(config.equals(config2)); + + // + // Test additional properties + // + + assertEquals(config.getAdditionalProperties().size(), 1); + + // + // Test NOT FOUND + // + assertEquals(config.declaredPropertyOrNotFound(PROPERTY2, ControllerConfiguration.NOT_FOUND_VALUE), ControllerConfiguration.NOT_FOUND_VALUE); + + // + // toString + // + logger.info("Config {}", config); + logger.info("Config2 {}", config2); + + } + + @Test + public void testConstructor() { + + PdpdConfiguration config = new PdpdConfiguration(REQUEST_ID, ENTITY, null); + assertEquals(config.getRequestID(), REQUEST_ID); + assertEquals(config.getEntity(), ENTITY); + + } + +} diff --git a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java new file mode 100644 index 00000000..3a9f8a4b --- /dev/null +++ b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java @@ -0,0 +1,667 @@ +/*- + * ============LICENSE_START======================================================= + * policy-management + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.drools.server.restful.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Properties; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.system.PolicyEngine; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class RestManagerTest { + + + public static final int DEFAULT_TELEMETRY_PORT = 9698; + private static final String HOST = "localhost"; + private static final String REST_MANAGER_PATH = "/policy/pdp"; + private static final String HOST_URL = "http://" + HOST + ":" + DEFAULT_TELEMETRY_PORT + REST_MANAGER_PATH; + private static final String FOO_CONTROLLER = "foo-controller"; + + private static final String UEB_TOPIC = "PDPD-CONFIGURATION"; + private static final String DMAAP_TOPIC = "com.att.ecomp-policy.DCAE_CL_EVENT_TEST"; + private static final String NOOP_TOPIC = "NOOP_TOPIC"; + + private static final String UEB_SOURCE_SERVER_PROPERTY = PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + + "." + UEB_TOPIC + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String UEB_SINK_SERVER_PROPERTY = PolicyProperties.PROPERTY_UEB_SINK_TOPICS + + "." + UEB_TOPIC + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String DMAAP_SOURCE_SERVER_PROPERTY = PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String DMAAP_SINK_SERVER_PROPERTY = PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String UEB_SERVER = "uebsb91sfdc.it.att.com"; + private static final String DMAAP_SERVER = "olsd005.wnsnet.attws.com"; + private static final String DMAAP_MECHID = "m03822@ecomp-policy.att.com"; + private static final String DMAAP_PASSWD = "Ec0mpP0l1cy"; + + private static final String DMAAP_SOURCE_MECHID_KEY = PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; + private static final String DMAAP_SOURCE_PASSWD_KEY = PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; + + private static final String DMAAP_SINK_MECHID_KEY = PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; + private static final String DMAAP_SINK_PASSWD_KEY = PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; + + + private static CloseableHttpClient client; + + private static final Logger logger = LoggerFactory.getLogger(RestManagerTest.class); + + @BeforeClass + public static void setUp() { + /* override default port */ + final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); + engineProps.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, + "" + DEFAULT_TELEMETRY_PORT); + engineProps.put(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS, UEB_TOPIC); + engineProps.put(PolicyProperties.PROPERTY_UEB_SINK_TOPICS, UEB_TOPIC); + engineProps.put(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS, DMAAP_TOPIC); + engineProps.put(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS, DMAAP_TOPIC); + engineProps.put(UEB_SOURCE_SERVER_PROPERTY, UEB_SERVER); + engineProps.put(UEB_SINK_SERVER_PROPERTY, UEB_SERVER); + engineProps.put(DMAAP_SOURCE_SERVER_PROPERTY, DMAAP_SERVER); + engineProps.put(DMAAP_SINK_SERVER_PROPERTY, DMAAP_SERVER); + engineProps.put(DMAAP_SOURCE_MECHID_KEY, DMAAP_MECHID); + engineProps.put(DMAAP_SOURCE_PASSWD_KEY, DMAAP_PASSWD); + engineProps.put(DMAAP_SINK_MECHID_KEY, DMAAP_MECHID); + engineProps.put(DMAAP_SINK_PASSWD_KEY, DMAAP_PASSWD); + engineProps.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); + + + PolicyEngine.manager.configure(engineProps); + PolicyEngine.manager.start(); + + client = HttpClients.createDefault(); + + } + + @AfterClass + public static void tearDown() { + PolicyEngine.manager.shutdown(); + + } + + + @Test + public void putDeleteTest() throws ClientProtocolException, IOException, InterruptedException { + HttpPut httpPut; + HttpDelete httpDelete; + CloseableHttpResponse response; + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info("/engine/topics/sources/ueb/{}/events response code: {}", UEB_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/switches/lock"); + response = client.execute(httpPut); + logger.info("/engine/topics/switches/lock response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info("/engine/topics/sources/ueb/{}/events response code: {}", UEB_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/topics/switches/lock"); + response = client.execute(httpDelete); + logger.info("/engine/topics/switches/lock response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches/lock"); + response = client.execute(httpPut); + logger.info("/engine/topics/sources/ueb/{}/switches/lock: {}", UEB_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches/lock"); + response = client.execute(httpDelete); + logger.info("/engine/topics/sources/ueb/{}/switches/lock: {}", UEB_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches/lock"); + response = client.execute(httpPut); + logger.info("/engine/topics/sources/dmaap/{}/switches/lock: {}", DMAAP_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches/lock"); + response = client.execute(httpDelete); + logger.info("/engine/topics/sources/dmaap/{}/switches/lock: {}", DMAAP_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/switches/activation"); + response = client.execute(httpPut); + logger.info("/engine/switches/activation response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/switches/activation"); + response = client.execute(httpDelete); + logger.info("/engine/switches/activation response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + } + + + @Test + public void getTest() throws ClientProtocolException, IOException, InterruptedException { + + HttpGet httpGet; + CloseableHttpResponse response; + String responseBody; + + httpGet = new HttpGet(HOST_URL + "/engine"); + response = client.execute(httpGet); + logger.info("/engine response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/features"); + response = client.execute(httpGet); + logger.info("/engine/features response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/features/inventory"); + response = client.execute(httpGet); + logger.info("/engine/features/inventory response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/features/foobar"); + response = client.execute(httpGet); + logger.info("/engine/features/foobar response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/inputs"); + response = client.execute(httpGet); + logger.info("/engine/inputs response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/properties"); + response = client.execute(httpGet); + logger.info("/engine/properties response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/environment"); + response = client.execute(httpGet); + logger.info("/engine/environment response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + PolicyEngine.manager.setEnvironmentProperty("foo", "bar"); + httpGet = new HttpGet(HOST_URL + "/engine/environment/foo"); + response = client.execute(httpGet); + responseBody = getResponseBody(response); + logger.info("/engine/environment/foo response code: {}",response.getStatusLine().getStatusCode()); + logger.info("/engine/environment/foo response body: {}",responseBody); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("bar", responseBody); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/switches"); + response = client.execute(httpGet); + logger.info("/engine/switches response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + Properties controllerProps = new Properties(); + PolicyEngine.manager.createPolicyController(FOO_CONTROLLER, controllerProps); + httpGet = new HttpGet(HOST_URL + "/engine/controllers"); + response = client.execute(httpGet); + responseBody = getResponseBody(response); + logger.info("/engine/controllers response code: {}",response.getStatusLine().getStatusCode()); + logger.info("/engine/controllers response body: {}",responseBody); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("[\"" + FOO_CONTROLLER +"\"]", responseBody); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/inventory"); + response = client.execute(httpGet); + logger.info("/engine/controllers/inventory response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/features"); + response = client.execute(httpGet); + logger.info("/engine/controllers/features response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/features/inventory"); + response = client.execute(httpGet); + logger.info("/engine/controllers/features/inventory response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/features/dummy"); + response = client.execute(httpGet); + logger.info("/engine/controllers/features/dummy response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER); + response = client.execute(httpGet); + logger.info("/engine/controllers/ response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller"); + response = client.execute(httpGet); + logger.info("/engine/controllers/nonexistantcontroller response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/properties"); + response = client.execute(httpGet); + responseBody = getResponseBody(response); + logger.info("/engine/controllers/contoller/properties response code: {}", response.getStatusLine().getStatusCode()); + logger.info("/engine/controllers/contoller/properties response code: {}", responseBody); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("{}", responseBody); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/properties"); + response = client.execute(httpGet); + logger.info("/engine/controllers/nonexistantcontroller/properties response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/inputs"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/inputs response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/switches"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/switches response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/drools response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/drools"); + response = client.execute(httpGet); + logger.info("/engine/controllers/nonexistantcontroller/drools response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/drools/facts response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/drools/facts"); + response = client.execute(httpGet); + logger.info("/engine/controllers/nonexistantcontroller/drools/facts response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/dummy"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/drools/facts/fact response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/dummy/dummy"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/drools/facts/fact response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session/query/queriedEntity"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/drools/facts/session/query/queriedEntity response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/decoders response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/decoders"); + response = client.execute(httpGet); + logger.info("/engine/controllers/nonexistantcontroller/decoders response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/filters"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controllers/decoders/filters response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/decoders/filters"); + response = client.execute(httpGet); + logger.info("engine/controllers/nonexistantcontroller/decoders/filters response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controllers/decoders/topics response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controllers/decoders/topic/filters response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/decoders/topic/filters/factType response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType/rules"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controllers/decoders/topic/filters/factType/rules response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType/rules/ruleName"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controllers/decoders/topic/filters/factType/rules/ruleName response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/encoders"); + response = client.execute(httpGet); + logger.info("/engine/controllers/controller/encoders response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + httpGet = new HttpGet(HOST_URL + "/engine/topics"); + response = client.execute(httpGet); + logger.info("/engine/topics response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/switches"); + response = client.execute(httpGet); + logger.info("/engine/topics/switches response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources"); + response = client.execute(httpGet); + logger.info("/engine/topics/sources response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks"); + response = client.execute(httpGet); + logger.info("/engine/topics/sinks response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb"); + response = client.execute(httpGet); + logger.info("/engine/topics/sinks/ueb response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb"); + response = client.execute(httpGet); + logger.info("/engine/topics/sources/ueb response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap"); + response = client.execute(httpGet); + logger.info("/engine/topics/sources/dmaap response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap"); + response = client.execute(httpGet); + logger.info("/engine/topics/sinks/dmaap response code: {}",response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC); + response = client.execute(httpGet); + logger.info("engine/topics/sources/ueb/{} response code: {}", UEB_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/foobar"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/ueb/foobar response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/" + UEB_TOPIC); + response = client.execute(httpGet); + logger.info("engine/topics/sources/ueb/{} response code: {}", UEB_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/foobar"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/ueb/foobar response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC); + response = client.execute(httpGet); + logger.info("engine/topics/sources/dmaap/{} response code: {}", DMAAP_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/dmaap/foobar response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC); + response = client.execute(httpGet); + logger.info("engine/topics/sources/dmaap/{} response code: {}", DMAAP_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/dmaap/foobar response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/ueb/{}/events response code: {}", UEB_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/foobar/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/ueb/foobar/events response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/" + UEB_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/ueb/{}/events response code: {}", UEB_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/foobar/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/ueb/foobar/events response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/dmaap/{}/events response code: {}", DMAAP_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/dmaap/foobar/events response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/dmaap/{}/events response code: {}", DMAAP_TOPIC,response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/dmaap/foobar/events response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/noop response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop/" + NOOP_TOPIC); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/noop/{} response code: {}", NOOP_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop/" + NOOP_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info("engine/topics/sinks/noop/{}/events response code: {}", NOOP_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/ueb/{}/switches response code: {}", UEB_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches"); + response = client.execute(httpGet); + logger.info("engine/topics/sources/dmaap/{}/switches response code: {}", DMAAP_TOPIC, response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/tools/uuid"); + response = client.execute(httpGet); + logger.info("engine/tools/uuid response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/tools/loggers"); + response = client.execute(httpGet); + logger.info("engine/tools/loggers response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/tools/loggers/ROOT"); + response = client.execute(httpGet); + logger.info("engine/tools/loggers/ROOT response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + } + + + public String getResponseBody(CloseableHttpResponse response) { + + HttpEntity entity; + try { + entity = response.getEntity(); + return EntityUtils.toString(entity); + + } catch (IOException e) { + + } + + return null; + } + +} diff --git a/policy-management/src/test/resources/logback-test.xml b/policy-management/src/test/resources/logback-test.xml index 4a3b561f..b2ddf807 100644 --- a/policy-management/src/test/resources/logback-test.xml +++ b/policy-management/src/test/resources/logback-test.xml @@ -10,7 +10,7 @@ <logger name="org.onap.policy.drools.system.test" level="INFO"/> - <root level="WARN"> + <root level="INFO"> <appender-ref ref="STDOUT"/> </root> diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/OrderedServiceImpl.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/OrderedServiceImpl.java index 88a53313..ee70a4b5 100644 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/OrderedServiceImpl.java +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/OrderedServiceImpl.java @@ -67,7 +67,7 @@ public class OrderedServiceImpl<T extends OrderedService> { rebuildList(); } - return(implementers); + return implementers; } /** @@ -85,7 +85,7 @@ public class OrderedServiceImpl<T extends OrderedService> public synchronized List<T> rebuildList() { // build a list of all of the current implementors - List<T> tmp = new LinkedList<T>(); + List<T> tmp = new LinkedList<>(); for (T service : serviceLoader) { tmp.add((T)getSingleton(service)); @@ -95,6 +95,7 @@ public class OrderedServiceImpl<T extends OrderedService> // according to full class name. Collections.sort(tmp, new Comparator<T>() { + @Override public int compare(T o1, T o2) { int s1 = o1.getSequenceNumber(); @@ -120,7 +121,7 @@ public class OrderedServiceImpl<T extends OrderedService> // create an unmodifiable version of this list implementers = Collections.unmodifiableList(tmp); logger.info("***** OrderedServiceImpl implementers:\n {}", implementers); - return(implementers); + return implementers; } // use this to ensure that we only use one unique instance of each class @@ -151,6 +152,6 @@ public class OrderedServiceImpl<T extends OrderedService> rval = service; classToSingleton.put(service.getClass(), service); } - return(rval); + return rval; } } diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/PropertyUtil.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/PropertyUtil.java index 9cfe2ed1..84043d8f 100644 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/PropertyUtil.java +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/PropertyUtil.java @@ -56,7 +56,7 @@ public class PropertyUtil // load properties (may throw an IOException) rval.load(fis); - return(rval); + return rval; } finally { @@ -75,7 +75,7 @@ public class PropertyUtil */ static public Properties getProperties(String fileName) throws IOException { - return(getProperties(new File(fileName))); + return getProperties(new File(fileName)); } /* ============================================================ */ @@ -87,6 +87,7 @@ public class PropertyUtil * This is the callback interface, used for sending notifications of * changes in the properties file. */ + @FunctionalInterface public interface Listener { /** @@ -100,7 +101,7 @@ public class PropertyUtil // this table maps canonical file into a 'ListenerRegistration' instance static private HashMap<File, ListenerRegistration> registrations = - new HashMap<File, ListenerRegistration>(); + new HashMap<>(); /** * This is an internal class - one instance of this exists for each @@ -141,7 +142,7 @@ public class PropertyUtil properties = getProperties(file); // no listeners yet - listeners = new LinkedList<Listener>(); + listeners = new LinkedList<>(); // add to static table, so this instance can be shared registrations.put(file, this); @@ -163,6 +164,7 @@ public class PropertyUtil // create and schedule the timer task, so this is periodically polled timerTask = new TimerTask() { + @Override public void run() { try @@ -186,7 +188,7 @@ public class PropertyUtil synchronized Properties addListener(Listener listener) { listeners.add(listener); - return((Properties)properties.clone()); + return (Properties)properties.clone(); } /** @@ -203,7 +205,7 @@ public class PropertyUtil // one is being removed. synchronized(registrations) { - if (listeners.size() == 0) + if (listeners.isEmpty()) { timerTask.cancel(); registrations.remove(file); @@ -226,7 +228,7 @@ public class PropertyUtil // Save old set, and initial set of changed properties. Properties oldProperties = properties; HashSet<String> changedProperties = - new HashSet<String>(oldProperties.stringPropertyNames()); + new HashSet<>(oldProperties.stringPropertyNames()); // Fetch the list of listeners that we will potentially notify, // and the new properties. Note that this is in a 'synchronized' @@ -259,7 +261,7 @@ public class PropertyUtil } // 'changedProperties' should be correct at this point - if (changedProperties.size() != 0) + if (!changedProperties.isEmpty()) { // there were changes - notify everyone in 'listeners' for (final Listener notify : listeners) @@ -269,12 +271,13 @@ public class PropertyUtil final Properties tmpProperties = (Properties)(properties.clone()); final HashSet<String> tmpChangedProperties = - new HashSet<String>(changedProperties); + new HashSet<>(changedProperties); // Do the notification in a separate thread, so blocking // won't cause any problems. new Thread() { + @Override public void run() { notify.propertiesChanged @@ -309,7 +312,7 @@ public class PropertyUtil if (listener == null) { // no listener specified -- just fetch the properties - return(getProperties(file)); + return getProperties(file); } // Convert the file to a canonical form in order to avoid the situation @@ -327,7 +330,7 @@ public class PropertyUtil // a new registration is needed reg = new ListenerRegistration(file); } - return(reg.addListener(listener)); + return reg.addListener(listener); } } @@ -350,7 +353,7 @@ public class PropertyUtil static public Properties getProperties(String fileName, Listener listener) throws IOException { - return(getProperties(new File(fileName), listener)); + return getProperties(new File(fileName), listener); } /** diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/ReflectionUtil.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/ReflectionUtil.java index ba00c57e..d300058f 100644 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/ReflectionUtil.java +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/ReflectionUtil.java @@ -32,6 +32,9 @@ import org.slf4j.LoggerFactory; public class ReflectionUtil { protected final static Logger logger = LoggerFactory.getLogger(ReflectionUtil.class); + + private ReflectionUtil(){ + } /** * returns (if exists) a class fetched from a given classloader @@ -82,7 +85,7 @@ public class ReflectionUtil { * @return */ public static boolean isSubclass(Class<?> parent, Class<?> presumedSubclass) { - return (parent.isAssignableFrom(presumedSubclass)); + return parent.isAssignableFrom(presumedSubclass); } } @@ -75,6 +75,8 @@ <module>feature-test-transaction</module> <module>api-state-management</module> <module>feature-state-management</module> + <module>api-active-standby-management</module> + <module>feature-active-standby-management</module> <module>packages</module> </modules> |