From e87b18923c23a1a0fbfaae1c75645a577b96c892 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Wed, 3 Jun 2020 09:26:33 -0400 Subject: Remove usecases and legacy actor code Made the following changes to remove usescase and legacy actor code: - deleted the usecases controller and feature - deleted code associated with legacy actors, with the exception of AaiManager, which is needed by RestControlLoopManager - moved the contents of the "guard" project into the m2/guard project, as that is the only thing that still needs it - modified the m2/GuardContext to get the name of its persistence unit from the properties so it could be overridden by junit tests - used eclipselink constants Also fixed a bug in the properties for the VFC actor. Addressed review comment: - removed usecases from Dockerfile Issue-ID: POLICY-2558 Change-Id: I677d68c9efed9247c3d55773abdcc736b577a6b4 Signed-off-by: Jim Hahn --- controlloop/common/controller-frankfurt/pom.xml | 6 - controlloop/common/controller-usecases/pom.xml | 236 --- .../src/main/resources/META-INF/kmodule.xml | 27 - .../src/main/resources/usecases.drl | 1711 -------------------- .../org/onap/policy/controlloop/UsecasesTest.java | 120 -- .../src/test/resources/META-INF/persistence.xml | 43 - .../resources/config/controlloop-system.properties | 21 - .../config/controlloop.properties.environment | 54 - .../config/usecases-controller.properties | 77 - .../src/test/resources/usecases.pom | 30 - controlloop/common/eventmanager/pom.xml | 6 - .../eventmanager/ControlLoopEventManager.java | 880 ---------- .../eventmanager/ControlLoopOperationManager.java | 1207 -------------- .../eventmanager/LockCallbackWorkingMemory.java | 80 - .../ophistory/OperationHistoryDataManagerImpl.java | 7 +- .../java/org/onap/policy/drools/PolicyEngine.java | 26 - .../onap/policy/drools/PolicyEngineListener.java | 32 - .../policy/drools/impl/PolicyEngineJUnitImpl.java | 147 -- .../controlloop/ControlLoopExceptionTest.java | 2 +- .../eventmanager/ControlLoopEventManagerTest.java | 802 --------- .../ControlLoopOperationManagerTest.java | 929 ----------- .../LockCallbackWorkingMemoryTest.java | 96 -- .../onap/policy/drools/DroolsPolicyEngineTest.java | 79 - .../common/feature-controlloop-management/pom.xml | 5 - .../server/restful/RestControlLoopManager.java | 13 +- .../server/restful/RestControlLoopManagerTest.java | 12 +- .../common/feature-controlloop-usecases/pom.xml | 114 -- .../src/assembly/assemble_zip.xml | 85 - .../feature/config/logback-include-usecases.xml | 56 - .../feature/config/usecases-controller.properties | 64 - .../feature/usecases/UsecasesFeature.java | 48 - ...p.policy.drools.features.PolicyEngineFeatureApi | 1 - .../feature/usecases/UsecasesFeatureTest.java | 31 - controlloop/common/guard/pom.xml | 177 -- .../java/org/onap/policy/guard/CallGuardTask.java | 155 -- .../java/org/onap/policy/guard/GuardResult.java | 25 - .../org/onap/policy/guard/PolicyGuardRequest.java | 84 - .../org/onap/policy/guard/PolicyGuardResponse.java | 71 - .../onap/policy/guard/PolicyGuardXacmlHelper.java | 139 -- .../guard/PolicyGuardXacmlRequestAttributes.java | 123 -- .../onap/policy/guard/PolicyGuardYamlToXacml.java | 210 --- .../src/main/java/org/onap/policy/guard/Util.java | 149 -- .../src/main/resources/META-INF/persistence.xml | 43 - .../org/onap/policy/guard/CallGuardTaskTest.java | 78 - .../org/onap/policy/guard/GuardResultTest.java | 42 - .../java/org/onap/policy/guard/GuardUtilTest.java | 102 -- .../onap/policy/guard/PolicyGuardRequestTest.java | 59 - .../onap/policy/guard/PolicyGuardResponseTest.java | 55 - .../policy/guard/PolicyGuardXacmlHelperTest.java | 150 -- .../PolicyGuardXacmlRequestAttributesTest.java | 74 - .../policy/guard/PolicyGuardYamlToXacmlTest.java | 248 --- .../onap/policy/guard/SupportTextFileUtils.java | 65 - .../src/test/resources/META-INF/persistence.xml | 43 - .../src/test/resources/blacklist_template.xml | 117 -- .../test/resources/frequency_limiter_template.xml | 127 -- controlloop/common/pom.xml | 3 - .../controlloop/common/rules/test/Rules.java | 9 - controlloop/m2/guard/pom.xml | 72 +- .../java/org/onap/policy/guard/CallGuardTask.java | 155 ++ .../java/org/onap/policy/guard/GuardContext.java | 18 +- .../java/org/onap/policy/guard/GuardResult.java | 25 + .../org/onap/policy/guard/PolicyGuardRequest.java | 84 + .../org/onap/policy/guard/PolicyGuardResponse.java | 71 + .../onap/policy/guard/PolicyGuardXacmlHelper.java | 139 ++ .../guard/PolicyGuardXacmlRequestAttributes.java | 123 ++ .../onap/policy/guard/PolicyGuardYamlToXacml.java | 210 +++ .../src/main/java/org/onap/policy/guard/Util.java | 146 ++ .../src/main/resources/META-INF/persistence.xml | 43 + .../org/onap/policy/guard/CallGuardTaskTest.java | 78 + .../org/onap/policy/guard/GuardContextTest.java | 12 +- .../org/onap/policy/guard/GuardResultTest.java | 42 + .../java/org/onap/policy/guard/GuardUtilTest.java | 102 ++ .../onap/policy/guard/PolicyGuardRequestTest.java | 59 + .../onap/policy/guard/PolicyGuardResponseTest.java | 55 + .../policy/guard/PolicyGuardXacmlHelperTest.java | 150 ++ .../PolicyGuardXacmlRequestAttributesTest.java | 74 + .../policy/guard/PolicyGuardYamlToXacmlTest.java | 248 +++ .../onap/policy/guard/SupportTextFileUtils.java | 65 + .../src/test/resources/META-INF/persistence.xml | 43 + .../src/test/resources/blacklist_template.xml | 117 ++ .../test/resources/frequency_limiter_template.xml | 127 ++ .../docker-controlloop/src/main/docker/Dockerfile | 4 +- 82 files changed, 2255 insertions(+), 9402 deletions(-) delete mode 100644 controlloop/common/controller-usecases/pom.xml delete mode 100644 controlloop/common/controller-usecases/src/main/resources/META-INF/kmodule.xml delete mode 100644 controlloop/common/controller-usecases/src/main/resources/usecases.drl delete mode 100644 controlloop/common/controller-usecases/src/test/java/org/onap/policy/controlloop/UsecasesTest.java delete mode 100644 controlloop/common/controller-usecases/src/test/resources/META-INF/persistence.xml delete mode 100644 controlloop/common/controller-usecases/src/test/resources/config/controlloop-system.properties delete mode 100644 controlloop/common/controller-usecases/src/test/resources/config/controlloop.properties.environment delete mode 100644 controlloop/common/controller-usecases/src/test/resources/config/usecases-controller.properties delete mode 100644 controlloop/common/controller-usecases/src/test/resources/usecases.pom delete mode 100644 controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java delete mode 100644 controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java delete mode 100644 controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemory.java delete mode 100644 controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java delete mode 100644 controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java delete mode 100644 controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java delete mode 100644 controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java delete mode 100644 controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java delete mode 100644 controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemoryTest.java delete mode 100644 controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java delete mode 100644 controlloop/common/feature-controlloop-usecases/pom.xml delete mode 100644 controlloop/common/feature-controlloop-usecases/src/assembly/assemble_zip.xml delete mode 100644 controlloop/common/feature-controlloop-usecases/src/main/feature/config/logback-include-usecases.xml delete mode 100644 controlloop/common/feature-controlloop-usecases/src/main/feature/config/usecases-controller.properties delete mode 100644 controlloop/common/feature-controlloop-usecases/src/main/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeature.java delete mode 100644 controlloop/common/feature-controlloop-usecases/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi delete mode 100644 controlloop/common/feature-controlloop-usecases/src/test/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeatureTest.java delete mode 100644 controlloop/common/guard/pom.xml delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java delete mode 100644 controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java delete mode 100644 controlloop/common/guard/src/main/resources/META-INF/persistence.xml delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java delete mode 100644 controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java delete mode 100644 controlloop/common/guard/src/test/resources/META-INF/persistence.xml delete mode 100644 controlloop/common/guard/src/test/resources/blacklist_template.xml delete mode 100644 controlloop/common/guard/src/test/resources/frequency_limiter_template.xml create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardResult.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java create mode 100644 controlloop/m2/guard/src/main/java/org/onap/policy/guard/Util.java create mode 100644 controlloop/m2/guard/src/main/resources/META-INF/persistence.xml create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java create mode 100644 controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java create mode 100644 controlloop/m2/guard/src/test/resources/META-INF/persistence.xml create mode 100644 controlloop/m2/guard/src/test/resources/blacklist_template.xml create mode 100644 controlloop/m2/guard/src/test/resources/frequency_limiter_template.xml (limited to 'controlloop') diff --git a/controlloop/common/controller-frankfurt/pom.xml b/controlloop/common/controller-frankfurt/pom.xml index a00058d51..03938d4cf 100644 --- a/controlloop/common/controller-frankfurt/pom.xml +++ b/controlloop/common/controller-frankfurt/pom.xml @@ -75,12 +75,6 @@ ${policy.models.version} provided - - org.onap.policy.drools-applications.controlloop.common - guard - ${project.version} - provided - org.onap.policy.models.policy-models-interactions.model-impl sdc diff --git a/controlloop/common/controller-usecases/pom.xml b/controlloop/common/controller-usecases/pom.xml deleted file mode 100644 index 5ab5d346e..000000000 --- a/controlloop/common/controller-usecases/pom.xml +++ /dev/null @@ -1,236 +0,0 @@ - - - - - 4.0.0 - - - org.onap.policy.drools-applications.controlloop.common - drools-applications-common - 1.7.1-SNAPSHOT - - - controller-usecases - kjar - - ${project.artifactId} - Usecases Experimental Controller - - - - - org.kie - kie-maven-plugin - true - - - - - - - org.onap.policy.models.policy-models-interactions.model-impl - events - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - appc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - appclcm - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - sdnr - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - vfc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - sdnc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - so - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - aai - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - sdc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-impl - cds - ${policy.models.version} - provided - - - org.onap.policy.drools-applications.controlloop.common - eventmanager - ${project.version} - provided - - - org.onap.policy.drools-applications.controlloop.common - guard - ${project.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actorServiceProvider - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.appc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.appclcm - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.sdnr - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.so - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.vfc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.sdnc - ${policy.models.version} - provided - - - org.onap.policy.models.policy-models-interactions.model-actors - actor.cds - ${policy.models.version} - - - org.onap.policy.models.policy-models-interactions - model-yaml - ${policy.models.version} - provided - - - org.onap.policy.drools-pdp - policy-management - ${version.policy.drools-pdp} - provided - true - - - org.onap.policy.drools-applications.controlloop.common - rules-test - ${project.version} - test - - - com.h2database - h2 - test - - - - - - - only-eclipse - - - m2e.version - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.kie - kie-maven-plugin - - build - - - - - - - - - - - - - - - - diff --git a/controlloop/common/controller-usecases/src/main/resources/META-INF/kmodule.xml b/controlloop/common/controller-usecases/src/main/resources/META-INF/kmodule.xml deleted file mode 100644 index e1a23863a..000000000 --- a/controlloop/common/controller-usecases/src/main/resources/META-INF/kmodule.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - diff --git a/controlloop/common/controller-usecases/src/main/resources/usecases.drl b/controlloop/common/controller-usecases/src/main/resources/usecases.drl deleted file mode 100644 index 95260fc91..000000000 --- a/controlloop/common/controller-usecases/src/main/resources/usecases.drl +++ /dev/null @@ -1,1711 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Bell Canada. - * ================================================================================ - * 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.controlloop; - -import org.apache.commons.lang3.tuple.Pair; - -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.policy.controlloop.drl.legacy.ControlLoopParams; -import org.onap.policy.controlloop.CanonicalOnset; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopException; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopResponse; -import org.onap.policy.controlloop.policy.PolicyResult; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.controlloop.policy.Policy; -import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; -import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NewEventStatus; -import org.onap.policy.controlloop.eventmanager.ControlLoopOperationManager; -import org.onap.policy.controlloop.eventmanager.LockCallbackWorkingMemory; -import org.onap.policy.controlloop.utils.ControlLoopUtils; -import org.onap.policy.controlloop.actor.so.SoActor; -import org.onap.policy.controlloop.actor.cds.CdsActor; -import org.onap.policy.controlloop.actor.cds.CdsActor.CdsActorServiceManager; -import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants; -import org.onap.policy.aai.AaiCqResponse; -import org.onap.policy.appc.Request; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.CommonHeader; -import org.onap.policy.appclcm.AppcLcmDmaapWrapper; -import org.onap.policy.cds.CdsResponse; -import org.onap.policy.cds.client.CdsProcessorGrpcClient; -import org.onap.policy.cds.properties.CdsServerProperties; -import org.onap.policy.sdnr.PciRequestWrapper; -import org.onap.policy.sdnr.PciResponseWrapper; -import org.onap.policy.sdnr.PciRequest; -import org.onap.policy.sdnr.PciResponse; -import org.onap.policy.vfc.VfcRequest; -import org.onap.policy.vfc.VfcResponse; -import org.onap.policy.vfc.VfcManager; -import org.onap.policy.so.SoManager; -import org.onap.policy.so.SoRequest; -import org.onap.policy.so.SoResponseWrapper; -import org.onap.policy.sdnc.SdncRequest; -import org.onap.policy.sdnc.SdncManager; -import org.onap.policy.sdnc.SdncResponse; -import org.onap.policy.drools.core.lock.Lock; -import org.onap.policy.guard.PolicyGuardRequest; -import org.onap.policy.guard.PolicyGuardResponse; -import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes; -import org.onap.policy.guard.PolicyGuardXacmlHelper; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; - -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -import java.time.Instant; -import java.util.LinkedList; -import java.util.Iterator; - - -import org.onap.policy.drools.system.PolicyEngineConstants; - -/* - * This object is to provide support for timeouts - * due to a bug in drools' built-in timers - */ -declare ControlLoopTimer - closedLoopControlName : String - requestId : String - delay : String - expired : boolean - //timerType is the type of timer: either "ClosedLoop" or "Operation" - timerType : String -end - -/* -* -* Called when the ControlLoopParams object has been inserted into working memory from the BRMSGW. -* -*/ -rule "INSERT.PARAMS" - when - $params : ControlLoopParams() - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {} : TOSCA-POLICY=[{}]", $params.getClosedLoopControlName(), $params.getPolicyName() + "." - + drools.getRule().getName(), $params.getToscaPolicy()); -end - -/* -* -* Called when a Tosca Policy is present. -* -*/ -rule "NEW.TOSCA.POLICY" - when - $policy : ToscaPolicy() - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: [{}|{}|{}|{}]: CONTENT: {}", drools.getRule().getName(), - $policy.getType(), $policy.getTypeVersion(), $policy.getName(), - $policy.getVersion(), $policy); - - ControlLoopParams params = ControlLoopUtils.toControlLoopParams($policy); - if (params != null) { - insert(params); - } -end - -/* - * Remove Control Loop Parameters. - */ -rule "REMOVE.PARAMS" - when - $params : ControlLoopParams( $policyName : getPolicyName(), $policyVersion : getPolicyVersion() ) - not ( ToscaPolicy( getName() == $policyName, getVersion() == $policyVersion ) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: [{}|{}|{}]", drools.getRule().getName(), - $params.getPolicyScope(), $params.getPolicyName(), $params.getPolicyVersion()); - - retract($params); -end - -/* -* -* This rule responds to DCAE Events where there is no manager yet. Either it is -* the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled) -* -*/ -rule "EVENT" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - not ( ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - - try { - - // - // Check the event, because we need it to not be null when - // we create the ControlLoopEventManager. The ControlLoopEventManager - // will do extra syntax checking as well check if the closed loop is disabled. - // - if ($event.getRequestId() == null) { - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setFrom("policy"); - notification.setMessage("Missing requestId"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - // - // Retract it from memory - // - retract($event); - } else { - // - // Create an EventManager - // - ControlLoopEventManager manager = new ControlLoopEventManager($clName, $event.getRequestId()); - // - // Determine if EventManager can actively process the event - // (i.e. syntax, is_closed_loop_disabled checks etc.) - // - VirtualControlLoopNotification notification = manager.activate($params.getToscaPolicy(), $event); - notification.setFrom("pdp-0001-controller=controlloop"); // Engine.getInstanceName() - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - // - // Are we actively pursuing this event? - // - if (notification.getNotification() == ControlLoopNotificationType.ACTIVE) { - // - // Insert Event Manager into memory, this will now kick off processing. - // - insert(manager); - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Setup the Overall Control Loop timer - // - ControlLoopTimer clTimer = new ControlLoopTimer(); - clTimer.setTimerType("ClosedLoop"); - clTimer.setClosedLoopControlName($event.getClosedLoopControlName()); - clTimer.setRequestId($event.getRequestId().toString()); - clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s"); - // - // Insert it - // - insert(clTimer); - } else { - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Retract it from memory - // - retract($event); - } - - // - // Now that the manager is inserted into Drools working memory, we'll wait for - // another rule to fire in order to continue processing. This way we can also - // then screen for additional ONSET and ABATED events for this RequestId. - // - } - } catch (Exception e) { - logger.warn("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName(), e); - - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage("Exception occurred: " + e.getMessage()); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - // - // - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Retract the event - // - retract($event); - } -end - -/* -* -* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager -* is now created. We can start processing the yaml specification via the Event Manager. -* -*/ -rule "EVENT.MANAGER" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : VirtualControlLoopEvent( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $clTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "ClosedLoop", !expired ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}: event={} manager={} clTimer={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $clTimer); - - try { - // - // Check which event this is. - // - ControlLoopEventManager.NewEventStatus eventStatus = $manager.onNewEvent($event); - // - // Check what kind of event this is - // - if (eventStatus == NewEventStatus.SUBSEQUENT_ONSET) { - // - // We don't care about subsequent onsets - // - logger.info("{}: {}: subsequent onset", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - retract($event); - return; - } - if (eventStatus == NewEventStatus.SYNTAX_ERROR) { - // - // Ignore any bad syntax events - // - logger.warn("{}: {}: syntax error", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - retract($event); - return; - } - // - // We only want the initial ONSET event in memory, - // all the other events need to be retracted to support - // cleanup and avoid the other rules being fired for this event. - // - if (eventStatus != NewEventStatus.FIRST_ONSET) { - logger.warn("{}: {}: no first onset", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - retract($event); - } - - logger.debug("{}: {}: target={}", $clName, - $params.getPolicyName() + "." + drools.getRule().getName(), $event.getTarget()); - // - // Now start seeing if we need to process this event - // - - // - // Check if this is a Final Event - // - VirtualControlLoopNotification notification = $manager.isControlLoopFinal(); - - - if (notification != null) { - // - // Its final, but are we waiting for abatement? - // - if ($manager.getNumAbatements() > 0) { - logger.info("{}: {}: abatement received for {}. Closing the control loop", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event.getRequestId()); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - // - // In this case, we are done - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Unlock the target - // - Lock lock = $manager.unlockCurrentOperation(); - if(lock != null) { - logger.debug("{}: {}.{}: retracting lock={}", $clName, - $params.getPolicyName(), drools.getRule().getName(), lock); - retract(lock); - } - // - // Retract everything from memory - // - logger.info("{}: {}: retracting onset, manager, and timer", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - - retract($manager.getOnsetEvent()); - - // don't retract manager, etc. - a clean-up rule will do that - - // - // TODO - what if we get subsequent Events for this RequestId? - // By default, it will all start over again. May be confusing for Ruby. - // Or, we could track this and then subsequently ignore the events - // - } else { - // - // Check whether we need to wait for abatement - // - if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.getNotification() == ControlLoopNotificationType.FINAL_SUCCESS) { - logger.info("{}: {}: waiting for abatement ..", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - } else { - logger.info("{}: {}: no abatement expect for {}. Closing the control loop", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event.getRequestId()); - - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - // - // In this case, we are done - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Unlock the target - // - Lock lock = $manager.unlockCurrentOperation(); - if(lock != null) { - logger.debug("{}: {}.{}: retracting lock={}", $clName, - $params.getPolicyName(), drools.getRule().getName(), lock); - retract(lock); - } - // - // Retract everything from memory - // - logger.info("{}: {}: retracting onset, manager, and timer", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - - retract($manager.getOnsetEvent()); - - // don't retract manager, etc. - a clean-up rule will do that - } - } - } else { - // - // NOT final, so let's ask for the next operation - // - ControlLoopOperationManager operation = $manager.processControlLoop(); - if (operation != null) { - // - // Let's ask for a lock right away - // - logger.info("{}: {}.{}: requesting lock for operation={}", - $clName, $params.getPolicyName(), drools.getRule().getName(), - operation); - - Pair oldNew = $manager.lockCurrentOperation( - new LockCallbackWorkingMemory($params.getClosedLoopControlName(), drools.getWorkingMemory())); - if(oldNew.getLeft() != null) { - logger.debug("{}: {}.{}: retracting lock={}", $clName, - $params.getPolicyName(), drools.getRule().getName(), oldNew.getLeft()); - retract(oldNew.getLeft()); - } - if(oldNew.getRight() != null) { - logger.debug("{}: {}.{}: inserting lock={}", $clName, - $params.getPolicyName(), drools.getRule().getName(), oldNew.getRight()); - insert(oldNew.getRight()); - } - - // - // insert the operation into memory - // - insert(operation); - - // - // insert operation timeout object - // - ControlLoopTimer opTimer = new ControlLoopTimer(); - opTimer.setTimerType("Operation"); - opTimer.setClosedLoopControlName($event.getClosedLoopControlName()); - opTimer.setRequestId($event.getRequestId().toString()); - Integer timeout = operation.getOperationTimeout(); - opTimer.setDelay(timeout > 0 ? timeout.toString() + "s" : $clTimer.getDelay()); - insert(opTimer); - - } else { - // - // Probably waiting for abatement - // - logger.info("{}: {}: no operation, probably waiting for abatement", - $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - } - } - } catch (Exception e) { - logger.warn("{}: {}: unexpected", - $clName, - $params.getPolicyName() + "." + drools.getRule().getName(), e); - - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage(e.getMessage()); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - retract($event); - - // don't retract manager, etc. - a clean-up rule will do that - } - -end - -/* -* -* Lock denied -* -*/ -rule "EVENT.MANAGER.OPERATION.LOCK.DENIED" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : VirtualControlLoopEvent( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId(), "None".equalsIgnoreCase(getGuardApprovalStatus()) ) - $lock : Lock (ownerKey == $event.getRequestId().toString(), isUnavailable()) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}.{}: event={} manager={} operation={} lock={}", - $clName, $params.getPolicyName(), drools.getRule().getName(), - $event, $manager, $operation, $lock); - - logger.debug("The target resource {} is already processing", $event.getAai().get($event.getTarget())); - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage("The target " + $event.getAai().get($event.getTarget()) + " is already locked"); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - retract($event); - - // don't retract manager, etc. - a clean-up rule will do that -end - -/* -* -* Guard Permitted, let's send request to the actor. -* -*/ -rule "EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : VirtualControlLoopEvent( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId(), "Permit".equalsIgnoreCase(getGuardApprovalStatus()) ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}: event={} manager={} operation={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation); - - Object request = null; - boolean caughtException = false; - - try { - request = $operation.startOperation($event); - - if (request != null) { - logger.debug("{}: {}: starting operation ..", - $clName, - $params.getPolicyName() + "." + drools.getRule().getName()); - // - // Tell interested parties we are performing this Operation - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.OPERATION); - notification.setMessage($operation.getOperationMessage()); - notification.setHistory($operation.getHistory()); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - switch ($operation.policy.getActor()){ - - case "APPC": - - if (request instanceof Request) { - PolicyEngineConstants.getManager().deliver("APPC-CL", request); - } - else if (request instanceof AppcLcmDmaapWrapper) { - PolicyEngineConstants.getManager().deliver("APPC-LCM-READ", request); - } - break; - case "SO": - // at this point the AAI named query request should have already been made, the response - // recieved and used in the construction of the SO Request which is stored in operationRequest - - if(request instanceof SoRequest) { - // Call SO. The response will be inserted into memory once it's received - class mySoCallback implements SoManager.SoCallback { - public void onSoResponseWrapper(SoResponseWrapper wrapper) { - drools.getWorkingMemory().insert(wrapper); - } - } - SoActor.sendRequest($event.getRequestId().toString(), - new mySoCallback(), - request, - PolicyEngineConstants.getManager().getEnvironmentProperty("so.url"), - PolicyEngineConstants.getManager().getEnvironmentProperty("so.username"), - PolicyEngineConstants.getManager().getEnvironmentProperty("so.password")); - } - break; - case "VFC": - if (request instanceof VfcRequest) { - class myVfcCallback implements VfcManager.VfcCallback { - - public void onResponse(VfcResponse responseError) { - drools.getWorkingMemory().insert(responseError); - } - }; - // Start VFC thread - Thread t = new Thread(new VfcManager(new myVfcCallback(), - (VfcRequest)request, - PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.url"), - PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.username"), - PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.password"))); - t.start(); - } - break; - case "SDNR": - if (request instanceof PciRequestWrapper) { - PolicyEngineConstants.getManager().deliver("SDNR-CL", request); - } - break; - - case "SDNC": - if (request instanceof SdncRequest) { - class mySdncCallback implements SdncManager.SdncCallback { - public void onCallback(SdncResponse response) { - drools.getWorkingMemory().insert(response); - } - } - // Start SDNC thread - Thread t = new Thread(new SdncManager(new mySdncCallback(), - (SdncRequest)request, - PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.url"), - PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.username"), - PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.password"))); - t.start(); - } - break; - - case "CDS": - - if(request instanceof ExecutionServiceInput) { - - // Instantiate cds actor, service manager and grpc properties - - CdsActor cdsActor = new CdsActor(); - CdsActor.CdsActorServiceManager cdsActorServiceManager = cdsActor.new CdsActorServiceManager(); - - CdsServerProperties props = new CdsServerProperties(); - props.setHost(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcHost")); - props.setPort(Integer.parseInt(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcPort"))); - props.setUsername(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcUsername")); - props.setPassword(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcPassword")); - props.setTimeout(Integer.parseInt(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcTimeout"))); - - // Send cds grpc request - try (CdsProcessorGrpcClient client = new CdsProcessorGrpcClient(cdsActorServiceManager, props)) { - CdsResponse response = - cdsActorServiceManager.sendRequestToCds(client, props, (ExecutionServiceInput) request); - logger.info("CDS response: {}", response); - insert(response); - } - } - break; - } - } else { - // - // What happens if its null? - // - logger.warn("{}: {}: unexpected null operation request", - $clName, - $params.getPolicyName() + "." + drools.getRule().getName()); - if ("SO".equals($operation.policy.getActor())) { - retract($opTimer); - retract($operation); - modify($manager) {finishOperation($operation)}; - } - else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) { - retract($opTimer); - retract($operation); - modify($manager) {finishOperation($operation)}; - } - else if ("sdnc".equalsIgnoreCase($operation.policy.getActor())) { - retract($opTimer); - retract($operation); - modify($manager) {finishOperation($operation)}; - } - } - - } catch (Exception e) { - String msg = e.getMessage(); - logger.warn("{}: {}: operation={}: AAI failure: {}", - $clName, - $params.getPolicyName() + "." + drools.getRule().getName(), - $operation, msg, e); - $operation.setOperationHasException(msg); - - if(request != null) { - // - // Create a notification for it ("DB Write - end operation") - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - } - - retract($opTimer); - retract($operation); - caughtException = true; - } - - // Having the modify statement in the catch clause doesn't work for whatever reason - if (caughtException) { - modify($manager) {finishOperation($operation)}; - } -end - - -/* -* -* We were able to acquire a lock so now let's ask Xacml Guard whether -* we are allowed to proceed with the request to the actor. -* -*/ -rule "EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : VirtualControlLoopEvent( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId(), "None".equalsIgnoreCase(getGuardApprovalStatus()) ) - $lock : Lock (ownerKey == $event.getRequestId().toString(), isActive()) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}: event={} manager={} operation={} lock={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $lock); - - // - // Sending notification that we are about to query Guard ("DB write - start operation") - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.OPERATION); - notification.setMessage("Sending guard query for " + $operation.policy.getActor() + " " - + $operation.policy.getRecipe()); - notification.setHistory($operation.getHistory()); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - // - // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, - // just change guardEnabled to false. - // - // In order to use REST XACML, provide a URL instead of "" as a second argument - // to the CallGuardTask() and set the first argument to null - // (instead of XacmlPdpEngine). - // - - // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled - boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngineConstants.getManager().getEnvironmentProperty("guard.disabled")); - - if(guardEnabled){ - - Thread t = new Thread(new org.onap.policy.guard.CallGuardTask( - drools.getWorkingMemory(), - $event.getClosedLoopControlName(), - $operation.policy.getActor().toString(), - $operation.policy.getRecipe(), - $operation.getTargetEntity(), - $event.getRequestId().toString(), - () -> { - try { - AaiCqResponse resp_cq = $manager.getCqResponse($event); - if (resp_cq == null){ - return null; - } else { - String custId = $operation.policy.getTarget().getModelCustomizationId(); - String invId = $operation.policy.getTarget().getModelInvariantId(); - String verId = $operation.policy.getTarget().getModelVersionId(); - return resp_cq.getVfModuleCount(custId, invId, verId); - } - } catch (Exception e){ - logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e); - } - return null; - })); - t.start(); - } - else{ - insert(new PolicyGuardResponse("Permit", $event.getRequestId(), $operation.policy.getRecipe())); - } - -end - -// -// This rule will be triggered when a thread talking to the XACML Guard inserts a -// guardResponse object into the working memory -// -rule "GUARD.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $guardResponse : PolicyGuardResponse(requestId == $event.getRequestId(), $operation.policy.recipe == operation) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}: event={} manager={} operation={} opTimer={} guardResponse={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $opTimer, $guardResponse); - - - //we will permit the operation if there was no Guard for it - if("Indeterminate".equalsIgnoreCase($guardResponse.getResult())){ - $guardResponse.setResult("Permit"); - } - - // - // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny") - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setNotification(ControlLoopNotificationType.OPERATION); - notification.setMessage("Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe() - + " is " + $guardResponse.getResult()); - notification.setHistory($operation.getHistory()); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - if("Permit".equalsIgnoreCase($guardResponse.getResult())){ - - modify($operation){setGuardApprovalStatus($guardResponse.getResult())}; - } - else { - //This is the Deny case - $operation.startOperation($event); - $operation.setOperationHasGuardDeny(); - retract($opTimer); - retract($operation); - modify($manager) {finishOperation($operation)}; - } - - retract($guardResponse); - -end - -/* -* -* This rule responds to APPC Response Events -* -* I would have like to be consistent and write the Response like this: -* $response : Response( CommonHeader.RequestId == $onset.getRequestId() ) -* -* However, no compile error was given. But a runtime error was given. I think -* because drools is confused between the classname CommonHeader vs the property CommonHeader. -* -*/ -rule "APPC.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : Response( getCommonHeader().RequestId == $event.getRequestId() ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $opTimer, $response); - // - // Get the result of the operation - // - PolicyResult policyResult = $operation.onResponse($response); - if (policyResult != null) { - logger.debug("{}: {}: operation finished - result={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - policyResult); - // - // This Operation has completed, construct a notification showing our results. (DB write - end operation) - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - if (policyResult.equals(PolicyResult.SUCCESS)) { - notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS); - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - } else { - notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE); - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - } - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete() == true) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // We must also retract the timer object - // NOTE: We could write a Rule to do this - // - retract($opTimer); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } - } else { - // - // Its not finished yet (i.e. expecting more Response objects) - // - // Or possibly it is a leftover response that we timed the request out previously - // - } - // - // We are going to retract these objects from memory - // - retract($response); -end - -/* -* -* The problem with Responses is that they don't have a controlLoopControlName -* field in them, so the only way to attach them is via RequestId. If we have multiple -* control loop .drl's loaded in the same container, we need to be sure the cleanup -* rules don't remove Responses for other control loops. -* -*/ -rule "APPC.RESPONSE.CLEANUP" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $response : Response($id : getCommonHeader().RequestId ) - not ( CanonicalOnset( requestId == $id ) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: orphan appc response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), $id); - - // - // Retract it - // - retract($response); -end - -/* -* -* This rule responds to APPC Response Events using the new LCM interface provided by appc -* -*/ -rule "APPC.LCM.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : AppcLcmDmaapWrapper( getBody().getOutput().getCommonHeader().getRequestId() == $event.getRequestId() ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer, $response); - - // - // Get the result of the operation - // - PolicyResult policyResult = $operation.onResponse($response); - if (policyResult != null) { - logger.debug("{}: {}: operation finished - result={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - policyResult); - - // - // This Operation has completed, construct a notification showing our results. (DB write - end operation) - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - if (policyResult.equals(PolicyResult.SUCCESS)) { - notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS); - } else { - notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE); - } - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete() == true) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // We must also retract the timer object - // NOTE: We could write a Rule to do this - // - retract($opTimer); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } - } else { - // - // Its not finished yet (i.e. expecting more Response objects) - // - // Or possibly it is a leftover response that we timed the request out previously - // - } - // - // We are going to retract these objects from memory - // - retract($response); -end - -/* -* -* Clean Up any lingering LCM reponses -* -*/ -rule "APPC.LCM.RESPONSE.CLEANUP" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $response : AppcLcmDmaapWrapper($id : getBody().getOutput().getCommonHeader().getRequestId() ) - not ( CanonicalOnset( requestId == $id ) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: orphan appc response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), $id); - // - // Retract it - // - retract($response); -end - -/* -* -* This rule responds to SO Response Events -* -*/ -rule "SO.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : SoResponseWrapper(requestId.toString() == $event.getRequestId().toString() ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer, $response); - - // Get the result of the operation - // - PolicyResult policyResult = $operation.onResponse($response); - if (policyResult != null) { - logger.debug("{}: {}: operation finished - result={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - policyResult); - - // - // This Operation has completed, construct a notification showing our results - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - if (policyResult.equals(PolicyResult.SUCCESS)) { - notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS); - } else { - notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE); - - } - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete() == true) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // We must also retract the timer object - // NOTE: We could write a Rule to do this - // - retract($opTimer); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } - } else { - // - // Its not finished yet (i.e. expecting more Response objects) - // - // Or possibly it is a leftover response that we timed the request out previously - // - } - // - // We are going to retract these objects from memory - // - retract($response); - -end - -/* -* -* This rule responds to VFC Response Events -* -*/ -rule "VFC.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : VfcResponse( requestId.toString() == $event.getRequestId().toString() ) - then - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer, $response); - - // Get the result of the operation - // - PolicyResult policyResult = $operation.onResponse($response); - if (policyResult != null) { - // - // This Operation has completed, construct a notification showing our results - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete() == true) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // We must also retract the timer object - // NOTE: We could write a Rule to do this - // - retract($opTimer); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } - } else { - // - // Its not finished yet (i.e. expecting more Response objects) - // - // Or possibly it is a leftover response that we timed the request out previously - // - } - // - // We are going to retract these objects from memory - // - retract($response); - -end - -/* -* -* This rule responds to SDNC Response Events -* -*/ -rule "SDNC.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : SdncResponse( requestId.toString() == $event.getRequestId().toString() ) - then - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer, $response); - - // Get the result of the operation - // - PolicyResult policyResult = $operation.onResponse($response); - if (policyResult != null) { - // - // This Operation has completed, construct a notification showing our results - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete()) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // We must also retract the timer object - // NOTE: We could write a Rule to do this - // - retract($opTimer); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } - } else { - // - // Its not finished yet (i.e. expecting more Response objects) - // - // Or possibly it is a leftover response that we timed the request out previously - // - } - // - // We are going to retract these objects from memory - // - retract($response); - -end - - -/** - * This rule responds to CDS Response Events - */ -rule "${policyName}.CDS.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $params.getClosedLoopControlName() ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : CdsResponse( requestId == $event.getRequestId().toString() ) - - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $params.getClosedLoopControlName(), drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer, $response); - - // Get the result of the operation - PolicyResult policyResult = $operation.onResponse($response); - - if (policyResult != null) { - logger.debug("{}: {}: operation finished - result={}", - $params.getClosedLoopControlName(), drools.getRule().getName(), - policyResult); - - // The operation has completed, construct a notification showing our results - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName(drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - notification.setNotification( - ($response != null && CdsActorConstants.SUCCESS.equals($response.getStatus())) - ? ControlLoopNotificationType.OPERATION_SUCCESS : ControlLoopNotificationType.OPERATION_FAILURE); - - // Send the notification - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - // Ensure the operation is complete - if ($operation.isOperationComplete()) { - - // It is complete, remove it from memory - retract($operation); - - // We must also retract the timer object - // NOTE: We could write a Rule to do this - retract($opTimer); - - // Complete the operation - modify($manager) {finishOperation($operation)}; - - } else { - // Just doing this will kick off the LOCKED rule again - modify($operation) {}; - } - } else { - // Its not finished yet (i.e. expecting more Response objects) - // Or possibly it is a leftover response that we timed the request out previously - logger.info( - "policyResult is null" - + "\nIt's not finished yet (i.e. expecting more Response objects)" - + "\nOr possibly it is a leftover response that we timed the request out previously"); - } - - // We are going to retract these objects from memory - retract($response); - -end - -/* -/* -* -* This manages a single timer. -* Due to a bug in the drools code, the drools timer needed to be split from most of the objects in the when clause -* -*/ -rule "TIMER.FIRED" - timer (expr: $timeout) - when - $timer : ControlLoopTimer($timeout : delay, !expired) - then - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("This is TIMER.FIRED"); - modify($timer){setExpired(true)}; - end - -/* -* -* This is the timer that manages the timeout for an individual operation. -* -*/ -rule "EVENT.MANAGER.OPERATION.TIMEOUT" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : VirtualControlLoopEvent( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", expired ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer); - - // - // Tell it its timed out - // - $operation.setOperationHasTimedOut(); - // - // Create a notification for it ("DB Write - end operation") - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - // - // Get rid of the timer - // - retract($opTimer); - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete() == true) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } -end - -/* -* -* This is the timer that manages the overall control loop timeout. -* -*/ -rule "EVENT.MANAGER.TIMEOUT" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : VirtualControlLoopEvent( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $clTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "ClosedLoop", expired ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - - logger.debug("{}: {}: event={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event); - // - // Tell the Event Manager it has timed out - // - VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut(); - if (notification != null) { - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - // - // Let interested parties know - // - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - } - // - // Retract the event - // - retract($event); -end - -/* -* -* This rule cleans up the manager and other objects after an event has -* been retracted. -* -*/ -rule "EVENT.MANAGER.CLEANUP" - when - $manager : ControlLoopEventManager( $clName : getClosedLoopControlName(), $requestId : getRequestId() ) - $operations : LinkedList() - from collect( ControlLoopOperationManager( onset.closedLoopControlName == $clName, - onset.getRequestId() == $requestId ) ) - $timers : LinkedList() - from collect( ControlLoopTimer( closedLoopControlName == $clName, - requestId == $requestId.toString() ) ) - not( VirtualControlLoopEvent( closedLoopControlName == $clName, requestId == $requestId ) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, drools.getRule().getName()); - - logger.debug("{}: {}: manager={} timers={} operations={}", - $clName, drools.getRule().getName(), - $manager, $timers.size(), $operations.size()); - - // - // Retract lock by invoking unlock() - // - Lock lock = $manager.unlockCurrentOperation(); - if(lock != null) { - retract(lock); - } - - // - // Retract EVERYTHING - // - retract($manager); - - for(Object manager: $operations) { - retract((ControlLoopOperationManager) manager); - } - for(Object timer: $timers) { - retract((ControlLoopTimer) timer); - } -end - -/* -* -* This rule will clean up any rogue onsets where there is no -* ControlLoopParams object corresponding to the onset event. -* -*/ -rule "EVENT.CLEANUP" - when - $event : VirtualControlLoopEvent( $clName: closedLoopControlName ) - not ( ControlLoopParams( getClosedLoopControlName() == $clName) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, drools.getRule().getName()); - logger.debug("{}: {}: orphan onset event={}", - $clName, drools.getRule().getName(), $event); - - retract($event); -end - -/* -* -* This rule responds to SDNR Response Events. -* -*/ -rule "SDNR.RESPONSE" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $event : CanonicalOnset( closedLoopControlName == $clName ) - $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId() ) - $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), - onset.getRequestId() == $event.getRequestId() ) - $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(), - requestId == $event.getRequestId().toString(), timerType == "Operation", !expired ) - $response : PciResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.getRequestId() ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - $event, $manager, $operation, $operation, $opTimer, $response); - - // - // Get the result of the operation - // - PolicyResult policyResult = $operation.onResponse($response); - if (policyResult != null) { - logger.debug("{}: {}: operation finished - result={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), - policyResult); - - // - // This Operation has completed, construct a notification showing our results. (DB write - end operation) - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.setFrom("policy"); - notification.setPolicyName($params.getPolicyName() + "." + drools.getRule().getName()); - notification.setPolicyScope($params.getPolicyScope()); - notification.setPolicyVersion($params.getPolicyVersion()); - notification.setMessage($operation.getOperationHistory()); - notification.setHistory($operation.getHistory()); - if (policyResult.equals(PolicyResult.SUCCESS)) { - notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS); - } else { - notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE); - } - PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification); - - ControlLoopResponse clResponse = $operation.getControlLoopResponse($response, $event); - PolicyEngineConstants.getManager().deliver("DCAE_CL_RSP", clResponse); - // - // Ensure the operation is complete - // - if ($operation.isOperationComplete() == true) { - // - // It is complete, remove it from memory - // - retract($operation); - // - // We must also retract the timer object - // NOTE: We could write a Rule to do this - // - retract($opTimer); - // - // Complete the operation - // - modify($manager) {finishOperation($operation)}; - } else { - // - // Just doing this will kick off the LOCKED rule again - // - modify($operation) {}; - } - } else { - // - // Its not finished yet (i.e. expecting more Response objects) - // - // Or possibly it is a leftover response that we timed the request out previously - // - } - // - // We are going to retract these objects from memory - // - retract($response); -end - -/* -* -* Clean Up any lingering SDNR reponses. -* -*/ -rule "SDNR.RESPONSE.CLEANUP" - when - $params : ControlLoopParams( $clName : getClosedLoopControlName() ) - $response : PciResponseWrapper($id : getBody().getCommonHeader().getRequestId ) - not ( CanonicalOnset( requestId == $id ) ) - then - - Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage()); - logger.info("{}: {}", $clName, $params.getPolicyName() + "." + drools.getRule().getName()); - logger.debug("{}: {}: orphan sdnr response={}", - $clName, $params.getPolicyName() + "." + drools.getRule().getName(), $id); - // - // Retract it - // - retract($response); -end diff --git a/controlloop/common/controller-usecases/src/test/java/org/onap/policy/controlloop/UsecasesTest.java b/controlloop/common/controller-usecases/src/test/java/org/onap/policy/controlloop/UsecasesTest.java deleted file mode 100644 index 1250dc80f..000000000 --- a/controlloop/common/controller-usecases/src/test/java/org/onap/policy/controlloop/UsecasesTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2020 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.controlloop; - -import lombok.Getter; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.runner.RunWith; -import org.onap.policy.controlloop.common.rules.test.BaseRuleTest; -import org.onap.policy.controlloop.common.rules.test.Listener; -import org.onap.policy.controlloop.common.rules.test.NamedRunner; -import org.onap.policy.controlloop.common.rules.test.TestNames; -import org.onap.policy.drools.utils.PropertyUtil; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; -import org.onap.policy.simulators.Util; - -/** - * Tests use case rules. Only a subset of available tests will work with these rules, thus - * a "FilterRunner" is used to filter out the other test cases. - * - *

- * Note: this only runs tests whose names start with "testV" (e.g., testVcpe(), - * testVdns()). - */ -@RunWith(NamedRunner.class) -@TestNames(prefixes = {"testV"}) - -public class UsecasesTest extends BaseRuleTest { - - @Getter() - protected static final String CONTROLLER_NAME = "usecases"; - - /** - * Sets up statics. - */ - @BeforeClass - public static void setUpBeforeClass() { - initStatics(CONTROLLER_NAME); - - rules.configure("src/main/resources"); - PropertyUtil.setSystemProperties(rules.getPdpdRepo().getSystemProperties("controlloop")); - rules.getPdpd().setEnvironment(rules.getPdpdRepo().getEnvironmentProperties("controlloop.properties")); - - rules.start(); - simulators.start(Util::buildAaiSim, Util::buildSoSim, Util::buildVfcSim, Util::buildGuardSim, - Util::buildSdncSim); - } - - /** - * Cleans up statics. - */ - @AfterClass - public static void tearDownAfterClass() { - finishStatics(); - } - - /** - * Sets up. - */ - @Before - public void setUp() { - init(); - } - - /** - * Tears down. - */ - @After - public void tearDown() { - finish(); - } - - @Override - protected void waitForLockAndPermit(ToscaPolicy policy, Listener policyClMgt) { - String policyName = policy.getIdentifier().getName(); - - policyClMgt.await(notif -> notif.getNotification() == ControlLoopNotificationType.ACTIVE - && (policyName + ".EVENT").equals(notif.getPolicyName())); - - policyClMgt.await(notif -> notif.getNotification() == ControlLoopNotificationType.OPERATION - && (policyName + ".EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED") - .equals(notif.getPolicyName())); - - policyClMgt.await(notif -> notif.getNotification() == ControlLoopNotificationType.OPERATION - && (policyName + ".GUARD.RESPONSE").equals(notif.getPolicyName()) - && notif.getMessage().startsWith("Guard result") && notif.getMessage().endsWith("Permit")); - - policyClMgt.await(notif -> notif.getNotification() == ControlLoopNotificationType.OPERATION - && (policyName + ".EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED") - .equals(notif.getPolicyName())); - } - - @Override - protected VirtualControlLoopNotification waitForFinal(ToscaPolicy policy, - Listener policyClMgt, ControlLoopNotificationType finalType) { - - return policyClMgt.await(notif -> notif.getNotification() == finalType - && (notif.getPolicyName().contains(policy.getIdentifier().getName() + ".EVENT.MANAGER"))); - } -} diff --git a/controlloop/common/controller-usecases/src/test/resources/META-INF/persistence.xml b/controlloop/common/controller-usecases/src/test/resources/META-INF/persistence.xml deleted file mode 100644 index 5589713be..000000000 --- a/controlloop/common/controller-usecases/src/test/resources/META-INF/persistence.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - - org.onap.policy.guard.OperationsHistory - - - - - - - - - - - - - - - diff --git a/controlloop/common/controller-usecases/src/test/resources/config/controlloop-system.properties b/controlloop/common/controller-usecases/src/test/resources/config/controlloop-system.properties deleted file mode 100644 index ff6658526..000000000 --- a/controlloop/common/controller-usecases/src/test/resources/config/controlloop-system.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# ============LICENSE_START======================================================= -# ONAP -# ================================================================================ -# Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= -# - -OperationsHistoryPU=OperationsHistoryPUTest \ No newline at end of file diff --git a/controlloop/common/controller-usecases/src/test/resources/config/controlloop.properties.environment b/controlloop/common/controller-usecases/src/test/resources/config/controlloop.properties.environment deleted file mode 100644 index d0b5448c4..000000000 --- a/controlloop/common/controller-usecases/src/test/resources/config/controlloop.properties.environment +++ /dev/null @@ -1,54 +0,0 @@ -# -# ============LICENSE_START======================================================= -# ONAP -# ================================================================================ -# Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. -# Modifications Copyright (C) 2019 Bell Canada. -# ================================================================================ -# 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========================================================= -# - -sql.db.host= -sql.db.username= -sql.db.password= - -aai.url=http://localhost:6666 -aai.username=AAI -aai.password=AAI - -so.url=http://localhost:6667 -so.username=SO -so.password=SO - -vfc.url=http://localhost:6668/api/nslcm/v1 -vfc.username=VFC -vfc.password=VFC - -pdpx.host=localhost -pdpx.username=pdpx -pdpx.password=pdpx - -guard.url=http://localhost:6669/policy/pdpx/v1/decision -guard.jdbc.url=jdbc:mariadb://localhost:3306/operationshistory -guard.disabled=false - -sdnc.url=sdnc -sdnc.username=sdnc -sdnc.password=sdnc - -cds.grpcHost=localhost -cds.grpcPort=7878 -cds.grpcUsername=grpc-username -cds.grpcPassword=grpc-password -cds.grpcTimeout=10 \ No newline at end of file diff --git a/controlloop/common/controller-usecases/src/test/resources/config/usecases-controller.properties b/controlloop/common/controller-usecases/src/test/resources/config/usecases-controller.properties deleted file mode 100644 index a8d202cd5..000000000 --- a/controlloop/common/controller-usecases/src/test/resources/config/usecases-controller.properties +++ /dev/null @@ -1,77 +0,0 @@ -# -# ============LICENSE_START======================================================= -# ONAP -# ================================================================================ -# Copyright (C) 2019-2020 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========================================================= -# - -controller.name=usecases - -rules.groupId=org.onap.policy.controlloop -rules.artifactId=usecases -rules.version=1.0.0 - -noop.source.topics=DCAE_TOPIC,APPC-CL,APPC-LCM-WRITE,SDNR-CL-RSP,POLICY-CL-MGT,APPC-LCM-READ,SDNR-CL,DCAE_CL_RSP - -noop.source.topics.DCAE_TOPIC.events=\ - org.onap.policy.controlloop.CanonicalOnset,org.onap.policy.controlloop.CanonicalAbated -noop.source.topics.DCAE_TOPIC.events.org.onap.policy.controlloop.CanonicalOnset.\ - filter=[?($.closedLoopEventStatus == 'ONSET')] -noop.source.topics.DCAE_TOPIC.events.org.onap.policy.controlloop.CanonicalAbated.\ - filter=[?($.closedLoopEventStatus == 'ABATED')] -noop.source.topics.DCAE_TOPIC.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gson - -noop.source.topics.APPC-CL.events=org.onap.policy.appc.Response,org.onap.policy.appc.Request -noop.source.topics.APPC-CL.events.org.onap.policy.appc.Response.filter=[?($.CommonHeader && $.Status)] -noop.source.topics.APPC-CL.events.org.onap.policy.appc.Request.filter=[?($.CommonHeader && $.Action)] -noop.source.topics.APPC-CL.events.custom.gson=org.onap.policy.appc.util.Serialization,gsonPretty - -noop.source.topics.APPC-LCM-WRITE.events=org.onap.policy.appclcm.AppcLcmDmaapWrapper -noop.source.topics.APPC-LCM-WRITE.events.org.onap.policy.appclcm.AppcLcmDmaapWrapper.filter=[?($.type == 'response')] -noop.source.topics.APPC-LCM-WRITE.events.custom.gson=org.onap.policy.appclcm.util.Serialization,gson - -noop.source.topics.SDNR-CL-RSP.events=org.onap.policy.sdnr.PciResponseWrapper -noop.source.topics.SDNR-CL-RSP.events.org.onap.policy.sdnr.PciResponseWrapper.filter=[?($.type == 'response')] -noop.source.topics.SDNR-CL-RSP.events.custom.gson=org.onap.policy.sdnr.util.Serialization,gson - -noop.source.topics.POLICY-CL-MGT.events=org.onap.policy.controlloop.VirtualControlLoopNotification -noop.source.topics.POLICY-CL-MGT.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gsonPretty - -noop.source.topics.APPC-LCM-READ.events=org.onap.policy.appclcm.AppcLcmDmaapWrapper -noop.source.topics.APPC-LCM-READ.events.custom.gson=org.onap.policy.appclcm.util.Serialization,gson - -noop.source.topics.SDNR-CL.events=org.onap.policy.sdnr.PciRequestWrapper -noop.source.topics.SDNR-CL.events.custom.gson=org.onap.policy.sdnr.util.Serialization,gson - -noop.source.topics.DCAE_CL_RSP.events=org.onap.policy.controlloop.ControlLoopResponse -noop.source.topics.DCAE_CL_RSP.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gsonPretty - -noop.sink.topics=APPC-CL,APPC-LCM-READ,POLICY-CL-MGT,SDNR-CL,DCAE_CL_RSP - -noop.sink.topics.APPC-CL.events=org.onap.policy.appc.Request -noop.sink.topics.APPC-CL.events.custom.gson=org.onap.policy.appc.util.Serialization,gsonPretty - -noop.sink.topics.APPC-LCM-READ.events=org.onap.policy.appclcm.AppcLcmDmaapWrapper -noop.sink.topics.APPC-LCM-READ.events.custom.gson=org.onap.policy.appclcm.util.Serialization,gson - -noop.sink.topics.POLICY-CL-MGT.events=org.onap.policy.controlloop.VirtualControlLoopNotification -noop.sink.topics.POLICY-CL-MGT.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gsonPretty - -noop.sink.topics.SDNR-CL.events=org.onap.policy.sdnr.PciRequestWrapper -noop.sink.topics.SDNR-CL.events.custom.gson=org.onap.policy.sdnr.util.Serialization,gson - -noop.sink.topics.DCAE_CL_RSP.events=org.onap.policy.controlloop.ControlLoopResponse -noop.sink.topics.DCAE_CL_RSP.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gsonPretty diff --git a/controlloop/common/controller-usecases/src/test/resources/usecases.pom b/controlloop/common/controller-usecases/src/test/resources/usecases.pom deleted file mode 100644 index aebbf3e68..000000000 --- a/controlloop/common/controller-usecases/src/test/resources/usecases.pom +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - 4.0.0 - - org.onap.policy.controlloop - usecases - 1.0.0 - \ No newline at end of file diff --git a/controlloop/common/eventmanager/pom.xml b/controlloop/common/eventmanager/pom.xml index f4698bb4b..911196deb 100644 --- a/controlloop/common/eventmanager/pom.xml +++ b/controlloop/common/eventmanager/pom.xml @@ -102,12 +102,6 @@ ${policy.models.version} provided - - org.onap.policy.drools-applications.controlloop.common - guard - ${project.version} - provided - org.onap.policy.models.policy-models-interactions.model-impl events diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java deleted file mode 100644 index 5546a0baa..000000000 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java +++ /dev/null @@ -1,880 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * controlloop event manager - * ================================================================================ - * Copyright (C) 2017-2020 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.controlloop.eventmanager; - -import static org.onap.policy.controlloop.ControlLoopTargetType.PNF; -import static org.onap.policy.controlloop.ControlLoopTargetType.VM; -import static org.onap.policy.controlloop.ControlLoopTargetType.VNF; - -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.aai.AaiCqResponse; -import org.onap.policy.aai.AaiManager; -import org.onap.policy.aai.util.AaiException; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopException; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.FinalResult; -import org.onap.policy.controlloop.policy.Policy; -import org.onap.policy.controlloop.processor.ControlLoopProcessor; -import org.onap.policy.drools.core.lock.Lock; -import org.onap.policy.drools.core.lock.LockCallback; -import org.onap.policy.drools.core.lock.LockImpl; -import org.onap.policy.drools.core.lock.LockState; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; -import org.onap.policy.rest.RestManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ControlLoopEventManager implements Serializable { - public static final String PROV_STATUS_ACTIVE = "ACTIVE"; - private static final String VM_NAME = "VM_NAME"; - private static final String VNF_NAME = "VNF_NAME"; - public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; - public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; - public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; - public static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled"; - public static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled"; - private static final String PNF_IS_IN_MAINT = "pnf.in-maint"; - public static final String GENERIC_VNF_PROV_STATUS = "generic-vnf.prov-status"; - public static final String VSERVER_PROV_STATUS = "vserver.prov-status"; - public static final String PNF_ID = "pnf.pnf-id"; - public static final String PNF_NAME = "pnf.pnf-name"; - - public static final String AAI_URL = "aai.url"; - public static final String AAI_USERNAME_PROPERTY = "aai.username"; - public static final String AAI_PASS_PROPERTY = "aai.password"; - - - /** - * Additional time, in seconds, to add to a "lock" request. This ensures that the lock won't expire right before an - * operation completes. - */ - private static final int ADDITIONAL_LOCK_SEC = 60; - - private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class); - - private static final long serialVersionUID = -1216568161322872641L; - - private static final Set VALID_TARGETS; - - static { - VALID_TARGETS = Collections.unmodifiableSet(new HashSet<>( - Stream.of(VM_NAME, VNF_NAME, VSERVER_VSERVER_NAME, GENERIC_VNF_VNF_ID, GENERIC_VNF_VNF_NAME, PNF_NAME) - .map(String::toLowerCase).collect(Collectors.toList()))); - } - - public final String closedLoopControlName; - private final UUID requestId; - - private String controlLoopResult; - private ControlLoopProcessor processor = null; - private VirtualControlLoopEvent onset; - private Integer numOnsets = 0; - private Integer numAbatements = 0; - private VirtualControlLoopEvent abatement; - private FinalResult controlLoopTimedOut = null; - - private boolean isActivated = false; - private LinkedList controlLoopHistory = new LinkedList<>(); - private ControlLoopOperationManager currentOperation = null; - private ControlLoopOperationManager lastOperationManager = null; - private transient Lock targetLock = null; - private boolean useTargetLock = true; - - /** - * Constructs the object. - * - * @param closedLoopControlName name of the control loop - * @param requestId ID of the request with which this manager is associated - */ - public ControlLoopEventManager(String closedLoopControlName, UUID requestId) { - this.closedLoopControlName = closedLoopControlName; - this.requestId = requestId; - } - - public String getClosedLoopControlName() { - return closedLoopControlName; - } - - public String getControlLoopResult() { - return controlLoopResult; - } - - public void setControlLoopResult(String controlLoopResult) { - this.controlLoopResult = controlLoopResult; - } - - public Integer getNumOnsets() { - return numOnsets; - } - - public void setNumOnsets(Integer numOnsets) { - this.numOnsets = numOnsets; - } - - public Integer getNumAbatements() { - return numAbatements; - } - - public void setNumAbatements(Integer numAbatements) { - this.numAbatements = numAbatements; - } - - public boolean isActivated() { - return isActivated; - } - - public void setActivated(boolean isActivated) { - this.isActivated = isActivated; - } - - public boolean useTargetLock() { - return useTargetLock(); - } - - public void setUseTargetLock(boolean useTargetLock) { - this.useTargetLock = useTargetLock; - } - - public VirtualControlLoopEvent getOnsetEvent() { - return this.onset; - } - - public VirtualControlLoopEvent getAbatementEvent() { - return this.abatement; - } - - public ControlLoopProcessor getProcessor() { - return this.processor; - } - - public UUID getRequestId() { - return requestId; - } - - - private VirtualControlLoopNotification rejectNotification(VirtualControlLoopEvent event, String message) { - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event); - notification.setNotification(ControlLoopNotificationType.REJECTED); - notification.setMessage(message); - return notification; - } - - /** - * Preactivations check for an event. - * - * @param event the event - * @return the VirtualControlLoopNotification - */ - private VirtualControlLoopNotification preActivationChecks(VirtualControlLoopEvent event) { - try { - // - // This method should ONLY be called ONCE - // - if (this.isActivated) { - return rejectNotification(event, "ControlLoopEventManager has already been activated."); - } - - // - // Syntax check the event - // - checkEventSyntax(event); - } catch (ControlLoopException e) { - logger.warn("{}: invalid event syntax: ", this, e); - return rejectNotification(event, e.getMessage()); - - } - - return new VirtualControlLoopNotification(event); - } - - /** - * Activate a control loop event. - * - * @param event the event - * @return the VirtualControlLoopNotification - */ - public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) { - VirtualControlLoopNotification notification = preActivationChecks(event); - if (notification.getNotification() == ControlLoopNotificationType.REJECTED) { - return notification; - } - - return postActivate(event, notification); - } - - /** - * Activate a control loop event. - * - * @param yamlSpecification the yaml specification - * @param event the event - * @return the VirtualControlLoopNotification - */ - public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) { - VirtualControlLoopNotification notification = preActivationChecks(event); - if (notification.getNotification() == ControlLoopNotificationType.REJECTED) { - return notification; - } - - if (yamlSpecification == null || yamlSpecification.length() < 1) { - return rejectNotification(event, "yaml specification is null or 0 length"); - } - - String decodedYaml = null; - try { - decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8"); - if (decodedYaml != null && decodedYaml.length() > 0) { - yamlSpecification = decodedYaml; - } - } catch (UnsupportedEncodingException e) { - logger.warn("{}: YAML decode in activate by YAML specification and event threw: ", this, e); - return rejectNotification(event, e.getMessage()); - } - - try { - // - // Parse the YAML specification - // - this.processor = new ControlLoopProcessor(yamlSpecification); - } catch (ControlLoopException e) { - logger.error("{}: activate by YAML specification and event threw: ", this, e); - return rejectNotification(event, e.getMessage()); - } - - return postActivate(event, notification); - } - - /** - * Activate a control loop event. - * - * @param toscaPolicy the tosca policy - * @param event the event - * @return the VirtualControlLoopNotification - */ - public VirtualControlLoopNotification activate(ToscaPolicy toscaPolicy, VirtualControlLoopEvent event) { - VirtualControlLoopNotification notification = preActivationChecks(event); - if (notification.getNotification() == ControlLoopNotificationType.REJECTED) { - return notification; - } - - try { - this.processor = new ControlLoopProcessor(toscaPolicy); - } catch (ControlLoopException e) { - logger.error("{}: activate from Tosca Policy threw: ", this, e); - return rejectNotification(event, e.getMessage()); - } - - return postActivate(event, notification); - } - - private VirtualControlLoopNotification postActivate( - VirtualControlLoopEvent event, VirtualControlLoopNotification notification) { - // - // At this point we are good to go with this event - // - this.onset = event; - this.numOnsets = 1; - - // - // Set ourselves as active - // - this.isActivated = true; - - notification.setNotification(ControlLoopNotificationType.ACTIVE); - return notification; - } - - /** - * Check if the control loop is final. - * - * @return a VirtualControlLoopNotification if the control loop is final, otherwise null is returned - * @throws ControlLoopException if an error occurs - */ - public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException { - validateFinalControlLoop(); - // - // Ok, start creating the notification - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); - // - // Check if the overall control loop has timed out - // - if (this.isControlLoopTimedOut()) { - // - // Yes we have timed out - // - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage("Control Loop timed out"); - notification.getHistory().addAll(this.controlLoopHistory); - return notification; - } - // - // Check if the current policy is Final - // - FinalResult result = this.processor.checkIsCurrentPolicyFinal(); - if (result == null) { - // - // we are not at a final result - // - return null; - } - - switch (result) { - case FINAL_FAILURE_EXCEPTION: - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage("Exception in processing closed loop"); - break; - case FINAL_FAILURE: - case FINAL_FAILURE_RETRIES: - case FINAL_FAILURE_TIMEOUT: - case FINAL_FAILURE_GUARD: - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - break; - case FINAL_OPENLOOP: - notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP); - break; - case FINAL_SUCCESS: - notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS); - break; - default: - return null; - } - // - // Be sure to add all the history - // - notification.getHistory().addAll(this.controlLoopHistory); - return notification; - } - - private void validateFinalControlLoop() throws ControlLoopException { - // - // Check if they activated us - // - if (!this.isActivated) { - throw new ControlLoopException("ControlLoopEventManager MUST be activated first."); - } - // - // Make sure we are expecting this call. - // - if (this.onset == null) { - throw new ControlLoopException("No onset event for ControlLoopEventManager."); - } - } - - /** - * Process the control loop. - * - * @return a ControlLoopOperationManager - * @throws ControlLoopException if an error occurs - */ - public ControlLoopOperationManager processControlLoop() throws ControlLoopException { - validateFinalControlLoop(); - // - // Is there a current operation? - // - if (this.currentOperation != null) { - // - // Throw an exception, or simply return the current operation? - // - throw new ControlLoopException("Already working an Operation, do not call this method."); - } - // - // Ensure we are not FINAL - // - VirtualControlLoopNotification notification = this.isControlLoopFinal(); - if (notification != null) { - // - // This is weird, we require them to call the isControlLoopFinal() method first - // - // We should really abstract this and avoid throwing an exception, because it really - // isn't an exception. - // - throw new ControlLoopException("Control Loop is in FINAL state, do not call this method."); - } - // - // Not final so get the policy that needs to be worked on. - // - Policy policy = this.processor.getCurrentPolicy(); - if (policy == null) { - throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy."); - } - // - // And setup an operation - // - this.lastOperationManager = this.currentOperation; - this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this); - // - // Return it - // - return this.currentOperation; - } - - /** - * Finish an operation. - * - * @param operation the operation - */ - public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException { - // - // Verify we have a current operation - // - if (this.currentOperation != null) { - // - // Validate they are finishing the current operation - // PLD - this is simply comparing the policy. Do we want to equals the whole object? - // - if (this.currentOperation.policy.equals(operation.policy)) { - logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(), - this.currentOperation.getOperationResult()); - // - // Save history - // - this.controlLoopHistory.addAll(this.currentOperation.getHistory()); - // - // Move to the next Policy - // - this.processor.nextPolicyForResult(this.currentOperation.getOperationResult()); - // - // Just null this out - // - this.lastOperationManager = this.currentOperation; - this.currentOperation = null; - - // - // Don't release the lock - it may be re-used by the next operation - // - - return; - } - logger.debug("Cannot finish current operation {} does not match given operation {}", - this.currentOperation.policy, operation.policy); - return; - } - throw new ControlLoopException("No operation to finish."); - } - - /** - * Obtain a lock for the current operation. - * - * @param callback call-back to be invoked when the lock state changes - * @return a pair containing the old lock and the new lock, either of which may be null - * @throws ControlLoopException if an error occurs - */ - public synchronized Pair lockCurrentOperation(LockCallback callback) throws ControlLoopException { - // - // Sanity check - // - if (this.currentOperation == null) { - throw new ControlLoopException("Do not have a current operation."); - } - - // - // Release the old lock if it's for a different resource. - // - Lock oldLock = null; - if (this.targetLock != null - && !this.targetLock.getResourceId().equals(this.currentOperation.getTargetEntity())) { - logger.debug("{}: different resource - releasing old lock", getClosedLoopControlName()); - oldLock = this.targetLock; - this.targetLock = null; - } - - // keep the lock a little longer than the operation, including retries - int optimeout = Math.max(1, this.currentOperation.getOperationTimeout()); - int nattempts = 1 + Math.max(0, this.currentOperation.getMaxRetries()); - int holdSec = optimeout * nattempts + ADDITIONAL_LOCK_SEC; - - // - // Have we acquired it already? - // - if (this.targetLock != null) { - // we have the lock - just extend it - this.targetLock.extend(holdSec, callback); - return Pair.of(oldLock, null); - - } else if (this.useTargetLock) { - this.targetLock = createRealLock(this.currentOperation.getTargetEntity(), this.onset.getRequestId(), - holdSec, callback); - return Pair.of(oldLock, this.targetLock); - - } else { - // Not using target locks - create a lock w/o actually locking. - logger.debug("{}: not using target locking; using pseudo locks", getClosedLoopControlName()); - this.targetLock = createPseudoLock(this.currentOperation.getTargetEntity(), this.onset.getRequestId(), - holdSec, callback); - - // Note: no need to invoke callback, as the lock is already ACTIVE - - return Pair.of(oldLock, this.targetLock); - } - } - - /** - * Releases the lock for the current operation, deleting it from working memory. - * - * @return the lock, if the operation was locked, {@code null} otherwise - */ - public synchronized Lock unlockCurrentOperation() { - if (this.targetLock == null) { - return null; - } - - Lock lock = this.targetLock; - this.targetLock = null; - - lock.free(); - - return lock; - } - - public enum NewEventStatus { - FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR; - } - - /** - * An event onset/abatement. - * - * @param event the event - * @return the status - * @throws AaiException if an error occurs retrieving information from A&AI - */ - public NewEventStatus onNewEvent(VirtualControlLoopEvent event) throws AaiException { - try { - this.checkEventSyntax(event); - if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) { - // - // Check if this is our original ONSET - // - if (event.equals(this.onset)) { - // - // DO NOT retract it - // - return NewEventStatus.FIRST_ONSET; - } - // - // Log that we got an onset - // - this.numOnsets++; - return NewEventStatus.SUBSEQUENT_ONSET; - } else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { - // - // Have we already got an abatement? - // - if (this.abatement == null) { - // - // Save this - // - this.abatement = event; - // - // Keep track that we received another - // - this.numAbatements++; - // - // - // - return NewEventStatus.FIRST_ABATEMENT; - } else { - // - // Keep track that we received another - // - this.numAbatements++; - // - // - // - return NewEventStatus.SUBSEQUENT_ABATEMENT; - } - } - } catch (ControlLoopException e) { - logger.error("{}: onNewEvent threw: ", this, e); - } - return NewEventStatus.SYNTAX_ERROR; - } - - - /** - * Commit the abatement to the history database. - * - * @param message the abatement message - * @param outcome the abatement outcome - */ - public void commitAbatement(String message, String outcome) { - if (this.lastOperationManager == null) { - logger.error("{}: commitAbatement: no operation manager", this); - return; - } - try { - this.lastOperationManager.commitAbatement(message, outcome); - } catch (NoSuchElementException e) { - logger.error("{}: commitAbatement threw an exception ", this, e); - } - } - - - /** - * Set the control loop time out. - * - * @return a VirtualControlLoopNotification - */ - public VirtualControlLoopNotification setControlLoopTimedOut() { - this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT; - VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset); - notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE); - notification.setMessage("Control Loop timed out"); - notification.getHistory().addAll(this.controlLoopHistory); - return notification; - } - - public boolean isControlLoopTimedOut() { - return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT); - } - - /** - * Get the control loop timeout. - * - * @param defaultTimeout the default timeout - * @return the timeout - */ - public int getControlLoopTimeout(Integer defaultTimeout) { - if (this.processor != null && this.processor.getControlLoop() != null) { - Integer timeout = this.processor.getControlLoop().getTimeout(); - if (timeout != null && timeout > 0) { - return timeout; - } - } - if (defaultTimeout != null) { - return defaultTimeout; - } - return 0; - } - - /** - * Check an event syntax. - * - * @param event the event syntax - * @throws ControlLoopException if an error occurs - */ - public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException { - validateStatus(event); - if (StringUtils.isBlank(event.getClosedLoopControlName())) { - throw new ControlLoopException("No control loop name"); - } - if (event.getRequestId() == null) { - throw new ControlLoopException("No request ID"); - } - if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) { - return; - } - if (StringUtils.isBlank(event.getTarget())) { - throw new ControlLoopException("No target field"); - } else if (!VALID_TARGETS.contains(event.getTarget().toLowerCase())) { - throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME"); - } - validateAaiData(event); - } - - private void validateStatus(VirtualControlLoopEvent event) throws ControlLoopException { - if (event.getClosedLoopEventStatus() == null - || (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET - && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED)) { - throw new ControlLoopException("Invalid value in closedLoopEventStatus"); - } - } - - private void validateAaiData(VirtualControlLoopEvent event) throws ControlLoopException { - Map eventAai = event.getAai(); - if (eventAai == null) { - throw new ControlLoopException("AAI is null"); - } - switch (event.getTargetType()) { - case VM: - case VNF: - validateAaiVmVnfData(eventAai); - return; - case PNF: - validateAaiPnfData(eventAai); - return; - default: - throw new ControlLoopException("The target type is not supported"); - } - } - - private void validateAaiVmVnfData(Map eventAai) throws ControlLoopException { - if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null - && eventAai.get(GENERIC_VNF_VNF_NAME) == null) { - throw new ControlLoopException( - "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing"); - } - } - - private void validateAaiPnfData(Map eventAai) throws ControlLoopException { - if (eventAai.get(PNF_NAME) == null) { - throw new ControlLoopException("AAI PNF object key pnf-name is missing"); - } - } - - /** - * Is closed loop disabled for an event. - * - * @param event the event - * @return true if the control loop is disabled, false otherwise - */ - public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) { - Map aai = event.getAai(); - return (isAaiTrue(aai.get(VSERVER_IS_CLOSED_LOOP_DISABLED)) - || isAaiTrue(aai.get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) - || isAaiTrue(aai.get(PNF_IS_IN_MAINT))); - } - - /** - * Does provisioning status, for an event, have a value other than ACTIVE. - * - * @param event the event - * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null}, {@code false} otherwise - */ - protected static boolean isProvStatusInactive(VirtualControlLoopEvent event) { - Map aai = event.getAai(); - return (!PROV_STATUS_ACTIVE.equals(aai.getOrDefault(VSERVER_PROV_STATUS, PROV_STATUS_ACTIVE)) - || !PROV_STATUS_ACTIVE.equals(aai.getOrDefault(GENERIC_VNF_PROV_STATUS, PROV_STATUS_ACTIVE))); - } - - /** - * Determines the boolean value represented by the given AAI field value. - * - * @param aaiValue value to be examined - * @return the boolean value represented by the field value, or {@code false} if the value is {@code null} - */ - protected static boolean isAaiTrue(String aaiValue) { - return ("true".equalsIgnoreCase(aaiValue) || "T".equalsIgnoreCase(aaiValue) || "yes".equalsIgnoreCase(aaiValue) - || "Y".equalsIgnoreCase(aaiValue)); - } - - @Override - public String toString() { - return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestId=" + requestId - + ", processor=" + processor + ", onset=" + (onset != null ? onset.getRequestId() : "null") - + ", numOnsets=" + numOnsets + ", numAbatements=" + numAbatements + ", isActivated=" + isActivated - + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]"; - } - - /** - * This function calls Aai Custom Query and responds with the AaiCqResponse. - * - * @param event input event - * @return AaiCqResponse Response from Aai for custom query. Can not be null. - * @throws AaiException if error occurs - */ - public AaiCqResponse getCqResponse(VirtualControlLoopEvent event) throws AaiException { - - Map aai = event.getAai(); - - if (aai.containsKey(VSERVER_IS_CLOSED_LOOP_DISABLED) || aai.containsKey(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) { - - if (isClosedLoopDisabled(event)) { - throw new AaiException("is-closed-loop-disabled is set to true on VServer or VNF"); - } - - if (isProvStatusInactive(event)) { - throw new AaiException("prov-status is not ACTIVE on VServer or VNF"); - } - } - - if (!aai.containsKey(VSERVER_VSERVER_NAME)) { - throw new AaiException("Vserver name is missing"); - } - - UUID reqId = event.getRequestId(); - AaiCqResponse response = null; - String vserverId = event.getAai().get(VSERVER_VSERVER_NAME); - - String aaiHostUrl = PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_URL); - String aaiUser = PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_USERNAME_PROPERTY); - String aaiPassword = PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_PASS_PROPERTY); - - response = new AaiManager(new RestManager()).getCustomQueryResponse(aaiHostUrl, aaiUser, aaiPassword, reqId, - vserverId); - - if (response == null) { - throw new AaiException("Target vnf-id could not be found"); - } - - return response; - - } - - /** - * Get the specified pnf data from aai. - * @param event the event containing pnf id. - * @return pnf key value data. - * @throws AaiException if an aai error occurs. - */ - public Map getPnf(VirtualControlLoopEvent event) throws AaiException { - Map aai = event.getAai(); - - if (!aai.containsKey(PNF_NAME)) { - throw new AaiException("Missing unique identifier for PNF AAI object in the event."); - } - - UUID reqId = event.getRequestId(); - String pnfName = event.getAai().get(PNF_NAME); - String aaiHostUrl = PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_URL); - String aaiUser = PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_USERNAME_PROPERTY); - String aaiPassword = PolicyEngineConstants.getManager().getEnvironmentProperty(AAI_PASS_PROPERTY); - - Map pnfParams = - new AaiManager(new RestManager()).getPnf(aaiHostUrl, aaiUser, aaiPassword, reqId, pnfName); - - if (pnfParams == null) { - throw new AaiException("Aai response is undefined"); - } - return pnfParams; - } - - - // the following methods may be overridden by junit tests - - protected Lock createRealLock(String targetEntity, UUID requestId, int holdSec, LockCallback callback) { - return PolicyEngineConstants.getManager().createLock(targetEntity, requestId.toString(), holdSec, callback, - false); - } - - // note: the "callback" is required, because it will be invoked when lock.extend() is - // invoked - protected Lock createPseudoLock(String targetEntity, UUID requestId, int holdSec, LockCallback callback) { - return new LockImpl(LockState.ACTIVE, targetEntity, requestId.toString(), holdSec, callback); - } -} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java deleted file mode 100644 index d16468de2..000000000 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java +++ /dev/null @@ -1,1207 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * controlloop operation manager - * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. - * Modifications Copyright (C) 2019 Tech Mahindra - * Modifications Copyright (C) 2019 Bell Canada. - * ================================================================================ - * 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.controlloop.eventmanager; - -import java.io.Serializable; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Properties; -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import org.apache.commons.lang3.tuple.Pair; -import org.eclipse.persistence.config.PersistenceUnitProperties; -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.ServiceInstance; -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.policy.aai.AaiCqResponse; -import org.onap.policy.aai.util.AaiException; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.ResponseCode; -import org.onap.policy.appclcm.AppcLcmDmaapWrapper; -import org.onap.policy.cds.CdsResponse; -import org.onap.policy.controlloop.ControlLoopEvent; -import org.onap.policy.controlloop.ControlLoopException; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.ControlLoopResponse; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.actor.appc.AppcActor; -import org.onap.policy.controlloop.actor.appclcm.AppcLcmActor; -import org.onap.policy.controlloop.actor.cds.CdsActor; -import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants; -import org.onap.policy.controlloop.actor.sdnc.SdncActor; -import org.onap.policy.controlloop.actor.sdnr.SdnrActor; -import org.onap.policy.controlloop.actor.so.SoActor; -import org.onap.policy.controlloop.actor.vfc.VfcActor; -import org.onap.policy.controlloop.policy.Policy; -import org.onap.policy.controlloop.policy.PolicyResult; -import org.onap.policy.controlloop.policy.TargetType; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.onap.policy.guard.OperationsHistory; -import org.onap.policy.guard.Util; -import org.onap.policy.sdnc.SdncResponse; -import org.onap.policy.sdnr.PciResponseWrapper; -import org.onap.policy.so.SoResponseWrapper; -import org.onap.policy.vfc.VfcResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ControlLoopOperationManager implements Serializable { - private static final String SUCCESS_MSG = " Success"; - private static final String FAILED_MSG = " Failed"; - private static final long serialVersionUID = -3773199283624595410L; - private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class); - - private static final String VSERVER_VSERVER_NAME = "vserver.vserver-name"; - private static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name"; - private static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id"; - - private static final String AAI_SERVICE_INSTANCE_ID_KEY = "service-instance.service-instance-id"; - private static final String PNF_NAME = "pnf.pnf-name"; - - // - // These properties are not changeable, but accessible - // for Drools Rule statements. - // - public final ControlLoopEvent onset; - public final Policy policy; - - // - // Properties used to track the Operation - // - private int attempts = 0; - private Operation currentOperation = null; - private LinkedList operationHistory = new LinkedList<>(); - private PolicyResult policyResult = null; - private ControlLoopEventManager eventManager = null; - private String targetEntity; - private String guardApprovalStatus = "NONE"; // "NONE", "PERMIT", "DENY" - private AaiCqResponse aaiCqResponse; - private transient Object operationRequest; - - /** - * Construct an instance. - * - * @param onset the onset event - * @param policy the policy - * @param em the event manager - * @throws ControlLoopException if an error occurs - */ - public ControlLoopOperationManager(ControlLoopEvent onset, Policy policy, - ControlLoopEventManager em) throws ControlLoopException { - - this.onset = onset; - this.policy = policy; - this.guardApprovalStatus = "NONE"; - this.eventManager = em; - - try { - if (TargetType.VNF.equals(policy.getTarget().getType()) - || TargetType.VFMODULE.equals(policy.getTarget().getType())) { - this.aaiCqResponse = - this.eventManager.getCqResponse((VirtualControlLoopEvent) onset); - } - - this.targetEntity = getTarget(policy); - - initActor(policy); - - } catch (AaiException e) { - throw new ControlLoopException(e.getMessage(), e); - } - } - - private void initActor(Policy policy) throws AaiException, ControlLoopException { - // - // Let's make a sanity check - // - switch (policy.getActor()) { - case "APPC": - initAppc(policy); - break; - case "SO": - break; - case "SDNR": - break; - case "VFC": - break; - case "SDNC": - break; - case "CDS": - break; - default: - throw new ControlLoopException( - "ControlLoopEventManager: policy has an unknown actor."); - } - } - - private void initAppc(Policy policy) throws AaiException { - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - /* - * The target vnf-id may not be the same as the source vnf-id specified in the yaml, the - * target - * vnf-id is retrieved by a named query to A&AI. - */ - GenericVnf genvnf = this.aaiCqResponse - .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID()); - if (genvnf == null) { - logger.info("Target entity could not be found"); - throw new AaiException("Target vnf-id could not be found"); - } - this.targetEntity = genvnf.getVnfId(); - - } - } - - public ControlLoopEventManager getEventManager() { - return eventManager; - } - - public void setEventManager(ControlLoopEventManager eventManager) { - this.eventManager = eventManager; - } - - public String getTargetEntity() { - return this.targetEntity; - } - - @Override - public String toString() { - return "ControlLoopOperationManager [onset=" - + (onset != null ? onset.getRequestId() : "null") + ", policy=" - + (policy != null ? policy.getId() : "null") + ", attempts=" + attempts - + ", policyResult=" + policyResult + ", currentOperation=" + currentOperation - + ", operationHistory=" + operationHistory + "]"; - } - - // - // Internal class used for tracking - // - private class Operation implements Serializable { - private static final long serialVersionUID = 1L; - - private ControlLoopOperation clOperation = new ControlLoopOperation(); - private PolicyResult policyResult = null; - private int attempt = 0; - - @Override - public String toString() { - return "Operation [attempt=" + attempt + ", policyResult=" + policyResult - + ", operation=" + clOperation + "]"; - } - } - - public Object getOperationRequest() { - return operationRequest; - } - - public String getGuardApprovalStatus() { - return guardApprovalStatus; - } - - public void setGuardApprovalStatus(String guardApprovalStatus) { - this.guardApprovalStatus = guardApprovalStatus; - } - - /** - * Get the target for a policy. - * - * @param policy the policy - * @return the target - * @throws ControlLoopException if an error occurs - */ - public String getTarget(Policy policy) throws ControlLoopException { - if (policy.getTarget() == null) { - throw new ControlLoopException("The target is null"); - } - - if (policy.getTarget().getType() == null) { - throw new ControlLoopException("The target type is null"); - } - - switch (policy.getTarget().getType()) { - case PNF: - return getPnfTarget(); - case VM: - case VNF: - return getVfModuleTarget(); - case VFMODULE: - return getVfModuleTarget(); - default: - throw new ControlLoopException("The target type is not supported"); - } - } - - private String getVfModuleTarget() throws ControlLoopException { - VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset; - if (this.onset.getTarget().equalsIgnoreCase(VSERVER_VSERVER_NAME)) { - return virtualOnsetEvent.getAai().get(VSERVER_VSERVER_NAME); - } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_ID)) { - return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID); - } else if (this.onset.getTarget().equalsIgnoreCase(GENERIC_VNF_VNF_NAME)) { - /* - * If the onset is enriched with the vnf-id, we don't need an A&AI response - */ - if (virtualOnsetEvent.getAai().containsKey(GENERIC_VNF_VNF_ID)) { - return virtualOnsetEvent.getAai().get(GENERIC_VNF_VNF_ID); - } - - /* - * If the vnf-name was retrieved from the onset then the vnf-id must be obtained from - * the event - * manager's A&AI GET query - */ - try { - String vnfId = this.aaiCqResponse.getDefaultGenericVnf().getVnfId(); - if (vnfId == null) { - throw new AaiException("No vnf-id found"); - } - return vnfId; - - } catch (AaiException e) { - throw new ControlLoopException(e.getMessage(), e); - } - } - throw new ControlLoopException("Target does not match target type"); - } - - private String getPnfTarget() throws ControlLoopException { - VirtualControlLoopEvent virtualOnsetEvent = (VirtualControlLoopEvent) this.onset; - if (!PNF_NAME.equalsIgnoreCase(onset.getTarget())) { - throw new ControlLoopException( - "Target in the onset event is either null or does not match target key expected in AAI section."); - } - return virtualOnsetEvent.getAai().get(PNF_NAME); - } - - /** - * Start an operation. - * - * @param onset the onset event - * @return the operation request - * @throws ControlLoopException if an error occurs - */ - public Object startOperation(/* VirtualControlLoopEvent */ControlLoopEvent onset) - throws ControlLoopException { - verifyOperatonCanRun(); - - // - // Setup - // - this.policyResult = null; - Operation operation = new Operation(); - operation.attempt = ++this.attempts; - operation.clOperation.setActor(this.policy.getActor()); - operation.clOperation.setOperation(this.policy.getRecipe()); - operation.clOperation.setTarget(this.policy.getTarget().toString()); - operation.clOperation.setSubRequestId(Integer.toString(operation.attempt)); - // - // Now determine which actor we need to construct a request for - // - try { - switch (policy.getActor()) { - case "APPC": - return startAppcOperation(onset, operation); - case "SO": - return startSoOperation(onset, operation); - case "VFC": - return startVfcOperation(onset, operation); - case "SDNR": - return startSdnrOperation(onset, operation); - case "SDNC": - return startSdncOperation(onset, operation); - case "CDS": - return startCdsOperation(onset, operation); - default: - throw new ControlLoopException( - "invalid actor " + policy.getActor() + " on policy"); - } - - } catch (AaiException e) { - throw new ControlLoopException(e.getMessage(), e); - } - } - - private Object startAppcOperation(ControlLoopEvent onset, Operation operation) { - /* - * If the recipe is ModifyConfig, a legacy APPC request is constructed. Otherwise an - * LCMRequest is - * constructed. - */ - this.currentOperation = operation; - if ("ModifyConfig".equalsIgnoreCase(policy.getRecipe())) { - this.operationRequest = - AppcActor.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.targetEntity); - } else { - this.operationRequest = - AppcLcmActor.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.targetEntity); - } - // - // Save the operation - // - - return operationRequest; - } - - private Object startSoOperation(ControlLoopEvent onset, Operation operation) { - SoActor soActorSp = new SoActor(); - this.operationRequest = soActorSp.constructRequestCq((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.aaiCqResponse); - - // Save the operation - this.currentOperation = operation; - - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - - return operationRequest; - } - - private Object startVfcOperation(ControlLoopEvent onset, Operation operation) { - this.operationRequest = - VfcActor.constructRequestCq((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy, this.aaiCqResponse); - this.currentOperation = operation; - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - return operationRequest; - } - - private Object startSdnrOperation(ControlLoopEvent onset, Operation operation) { - /* - * If the recipe is ModifyConfig or ModifyConfigANR, a SDNR request is constructed. - */ - this.currentOperation = operation; - this.operationRequest = SdnrActor - .constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, this.policy); - // - // Save the operation - // - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - - return operationRequest; - } - - private Object startSdncOperation(ControlLoopEvent onset, Operation operation) { - SdncActor provider = new SdncActor(); - this.operationRequest = provider.constructRequest((VirtualControlLoopEvent) onset, - operation.clOperation, this.policy); - this.currentOperation = operation; - if (this.operationRequest == null) { - this.policyResult = PolicyResult.FAILURE; - } - return operationRequest; - } - - private Object startCdsOperation(ControlLoopEvent onset, Operation operation) - throws AaiException { - - CdsActor provider = new CdsActor(); - Optional optionalRequest = - provider.constructRequest((VirtualControlLoopEvent) onset, operation.clOperation, - this.policy, this.buildAaiParams()); - - this.currentOperation = operation; - if (optionalRequest.isPresent()) { - this.operationRequest = optionalRequest.get(); - } else { - this.operationRequest = null; - this.policyResult = PolicyResult.FAILURE; - } - - return this.operationRequest; - } - - /** - * Build AAI parameters for CDS operation. - * - * @return a map containing vnf id key and value for the vnf to apply the action to. - * @throws AaiException if the vnf can not be found. - */ - private Map buildAaiParams() throws AaiException { - - Map result = new HashMap<>(); - - if (TargetType.VNF.equals(policy.getTarget().getType()) - || TargetType.VFMODULE.equals(policy.getTarget().getType())) { - - ServiceInstance serviceInstance = this.aaiCqResponse.getServiceInstance(); - if (serviceInstance == null) { - logger.info("Target entity service instance could not be found"); - throw new AaiException("Target service instance could not be found"); - } - - GenericVnf genericVnf = this.aaiCqResponse - .getGenericVnfByModelInvariantId(policy.getTarget().getResourceID()); - if (genericVnf == null) { - logger.info("Target entity generic vnf could not be found"); - throw new AaiException("Target generic vnf could not be found"); - } - - result.put(AAI_SERVICE_INSTANCE_ID_KEY, serviceInstance.getServiceInstanceId()); - result.put(GENERIC_VNF_VNF_ID, genericVnf.getVnfId()); - - } else if (TargetType.PNF.equals(policy.getTarget().getType())) { - result = this.eventManager.getPnf((VirtualControlLoopEvent) onset); - } - - return result; - - } - - /** - * Handle a response. - * - * @param response the response - * @return a PolicyResult - */ - public PolicyResult onResponse(Object response) { - // - // Which response is it? - // - if (response instanceof Response) { - // - // Cast APPC response and handle it - // - return onResponse((Response) response); - } else if (response instanceof AppcLcmDmaapWrapper) { - // - // Cast LCM response and handle it - // - return onResponse((AppcLcmDmaapWrapper) response); - } else if (response instanceof PciResponseWrapper) { - // - // Cast SDNR response and handle it - // - return onResponse((PciResponseWrapper) response); - } else if (response instanceof SoResponseWrapper) { - // - // Cast SO response and handle it - // - return onResponse((SoResponseWrapper) response); - } else if (response instanceof VfcResponse) { - // - // Cast VFC response and handle it - // - return onResponse((VfcResponse) response); - } else if (response instanceof SdncResponse) { - // - // Cast SDNC response and handle it - // - return onResponse((SdncResponse) response); - } else if (response instanceof CdsResponse) { - // - // Cast CDS response and handle it - // - return onResponse((CdsResponse) response); - } else { - return null; - } - } - - /** - * This method handles operation responses from APPC. - * - * @param appcResponse the APPC response - * @return The result of the response handling - */ - private PolicyResult onResponse(Response appcResponse) { - // - // Determine which subrequestID (ie. attempt) - // - Integer operationAttempt = getSubRequestId(appcResponse); - if (operationAttempt == null) { - this.completeOperation(operationAttempt, - "Policy was unable to parse APP-C SubRequestID (it was null).", - PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - // - // Sanity check the response message - // - if (appcResponse.getStatus() == null) { - // - // We cannot tell what happened if this doesn't exist - // - this.completeOperation(operationAttempt, - "Policy was unable to parse APP-C response status field (it was null).", - PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - // - // Get the Response Code - // - ResponseCode code = ResponseCode.toResponseCode(appcResponse.getStatus().getCode()); - if (code == null) { - // - // We are unaware of this code - // - this.completeOperation(operationAttempt, - "Policy was unable to parse APP-C response status code field.", - PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - - return onResponse(appcResponse, operationAttempt, code); - } - - private PolicyResult onResponse(Response appcResponse, Integer operationAttempt, - ResponseCode code) { - // - // Ok, let's figure out what APP-C's response is - // - switch (code) { - case ACCEPT: - // - // This is good, they got our original message and - // acknowledged it. - // - // Is there any need to track this? - // - return null; - case ERROR: - case REJECT: - // - // We'll consider these two codes as exceptions - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), - PolicyResult.FAILURE_EXCEPTION); - return getTimeoutResult(PolicyResult.FAILURE_EXCEPTION); - case SUCCESS: - // - // - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), - PolicyResult.SUCCESS); - return getTimeoutResult(PolicyResult.SUCCESS); - case FAILURE: - // - // - // - this.completeOperation(operationAttempt, appcResponse.getStatus().getDescription(), - PolicyResult.FAILURE); - return getTimeoutResult(PolicyResult.FAILURE); - default: - return null; - } - } - - /** - * This method handles operation responses from LCM. - * - * @param dmaapResponse the LCM response - * @return The result of the response handling - */ - private PolicyResult onResponse(AppcLcmDmaapWrapper dmaapResponse) { - /* - * Parse out the operation attempt using the subrequestid - */ - Integer operationAttempt = AppcLcmActor.parseOperationAttempt( - dmaapResponse.getBody().getOutput().getCommonHeader().getSubRequestId()); - if (operationAttempt == null) { - this.completeOperation(operationAttempt, - "Policy was unable to parse APP-C SubRequestID (it was null).", - PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - - /* - * Process the APPCLCM response to see what PolicyResult should be returned - */ - AbstractMap.SimpleEntry result = - AppcLcmActor.processResponse(dmaapResponse); - - if (result.getKey() != null) { - this.completeOperation(operationAttempt, result.getValue(), result.getKey()); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - return result.getKey(); - } - return null; - } - - /** - * This method handles operation responses from SDNR. - * - * @param dmaapResponse the SDNR response - * @return the result of the response handling - */ - private PolicyResult onResponse(PciResponseWrapper dmaapResponse) { - /* - * Parse out the operation attempt using the subrequestid - */ - Integer operationAttempt = SdnrActor - .parseOperationAttempt(dmaapResponse.getBody().getCommonHeader().getSubRequestId()); - if (operationAttempt == null) { - this.completeOperation(operationAttempt, - "Policy was unable to parse SDNR SubRequestID.", PolicyResult.FAILURE_EXCEPTION); - return PolicyResult.FAILURE_EXCEPTION; - } - - /* - * Process the SDNR response to see what PolicyResult should be returned - */ - Pair result = - SdnrActor.processResponse(dmaapResponse); - - if (result.getLeft() != null) { - this.completeOperation(operationAttempt, result.getRight(), result.getLeft()); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - return result.getLeft(); - } - return null; - } - - /** - * This method handles operation responses from SO. - * - * @param msoResponse the SO response - * @return The result of the response handling - */ - private PolicyResult onResponse(SoResponseWrapper msoResponse) { - switch (msoResponse.getSoResponse().getHttpResponseCode()) { - case 200: - case 202: - // - // Consider it as success - // - this.completeOperation(this.attempts, - msoResponse.getSoResponse().getHttpResponseCode() + SUCCESS_MSG, - PolicyResult.SUCCESS); - return getTimeoutResult(PolicyResult.SUCCESS); - default: - // - // Consider it as failure - // - this.completeOperation(this.attempts, - msoResponse.getSoResponse().getHttpResponseCode() + FAILED_MSG, - PolicyResult.FAILURE); - return getTimeoutResult(PolicyResult.FAILURE); - } - } - - /** - * This method handles operation responses from VFC. - * - * @param vfcResponse the VFC response - * @return The result of the response handling - */ - private PolicyResult onResponse(VfcResponse vfcResponse) { - if ("finished".equalsIgnoreCase(vfcResponse.getResponseDescriptor().getStatus())) { - // - // Consider it as success - // - this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS); - return getTimeoutResult(PolicyResult.SUCCESS); - } else { - // - // Consider it as failure - // - this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - // increment operation attempts for retries - this.attempts += 1; - return PolicyResult.FAILURE; - } - } - - /** - * This method handles operation responses from SDNC. - * - * @param sdncResponse the VFC response - * @return The result of the response handling - */ - private PolicyResult onResponse(SdncResponse sdncResponse) { - if ("200".equals(sdncResponse.getResponseOutput().getResponseCode())) { - // - // Consider it as success - // - this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS); - return getTimeoutResult(PolicyResult.SUCCESS); - } else { - // - // Consider it as failure - // - this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - // increment operation attempts for retries - this.attempts += 1; - return PolicyResult.FAILURE; - } - } - - /** - * This method handles operation responses from CDS. - * - * @param response the CDS response - * @return The result of the response handling - */ - private PolicyResult onResponse(CdsResponse response) { - if (response != null && CdsActorConstants.SUCCESS.equals(response.getStatus())) { - // - // Consider it as success - // - this.completeOperation(this.attempts, SUCCESS_MSG, PolicyResult.SUCCESS); - return getTimeoutResult(PolicyResult.SUCCESS); - } else { - // - // Consider it as failure - // - this.completeOperation(this.attempts, FAILED_MSG, PolicyResult.FAILURE); - if (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult)) { - return null; - } - // increment operation attempts for retries - this.attempts += 1; - return PolicyResult.FAILURE; - } - } - - private PolicyResult getTimeoutResult(PolicyResult result) { - return (PolicyResult.FAILURE_TIMEOUT.equals(this.policyResult) ? null : result); - } - - private Integer getSubRequestId(Response appcResponse) { - try { - return Integer.valueOf(appcResponse.getCommonHeader().getSubRequestId()); - } catch (NumberFormatException e) { - // - // We cannot tell what happened if this doesn't exist - // - return null; - } - } - - /** - * Get the operation timeout. - * - * @return the timeout - */ - public Integer getOperationTimeout() { - // - // Sanity check - // - if (this.policy == null) { - logger.debug("getOperationTimeout returning 0"); - return 0; - } - logger.debug("getOperationTimeout returning {}", this.policy.getTimeout()); - return this.policy.getTimeout(); - } - - /** - * Get the operation timeout as a String. - * - * @param defaultTimeout the default timeout - * @return the timeout as a String - */ - public String getOperationTimeoutString(int defaultTimeout) { - Integer to = this.getOperationTimeout(); - if (to == null || to == 0) { - return Integer.toString(defaultTimeout) + "s"; - } - return to.toString() + "s"; - } - - public PolicyResult getOperationResult() { - return this.policyResult; - } - - /** - * Get the operation as a message. - * - * @return the operation as a message - */ - public String getOperationMessage() { - if (this.currentOperation != null && this.currentOperation.clOperation != null) { - return this.currentOperation.clOperation.toMessage(); - } - - if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().clOperation.toMessage(); - } - return null; - } - - /** - * Get the operation as a message including the guard result. - * - * @param guardResult the guard result - * @return the operation as a message including the guard result - */ - public String getOperationMessage(String guardResult) { - if (this.currentOperation != null && this.currentOperation.clOperation != null) { - return this.currentOperation.clOperation.toMessage() + ", Guard result: " + guardResult; - } - - if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().clOperation.toMessage() + ", Guard result: " - + guardResult; - } - return null; - } - - /** - * Get the operation history. - * - * @return the operation history - */ - public String getOperationHistory() { - if (this.currentOperation != null && this.currentOperation.clOperation != null) { - return this.currentOperation.clOperation.toHistory(); - } - - if (!this.operationHistory.isEmpty()) { - return this.operationHistory.getLast().clOperation.toHistory(); - } - return null; - } - - /** - * Get the history. - * - * @return the list of control loop operations - */ - public List getHistory() { - LinkedList history = new LinkedList<>(); - for (Operation op : this.operationHistory) { - history.add(new ControlLoopOperation(op.clOperation)); - - } - return history; - } - - /** - * Set the operation has timed out. - */ - public void setOperationHasTimedOut() { - // - // - // - this.completeOperation(this.attempts, "Operation timed out", PolicyResult.FAILURE_TIMEOUT); - } - - /** - * Set the operation has been denied by guard. - */ - public void setOperationHasGuardDeny() { - // - // - // - this.completeOperation(this.attempts, "Operation denied by Guard", - PolicyResult.FAILURE_GUARD); - } - - public void setOperationHasException(String message) { - this.completeOperation(this.attempts, message, PolicyResult.FAILURE_EXCEPTION); - } - - /** - * Is the operation complete. - * - * @return true if the operation is complete, false otherwise - */ - public boolean isOperationComplete() { - // - // Is there currently a result? - // - if (this.policyResult == null) { - // - // either we are in process or we - // haven't started - // - return false; - } - // - // We have some result, check if the operation failed - // - if (this.policyResult.equals(PolicyResult.FAILURE)) { - // - // Check if there were no retries specified - // - if (getMaxRetries() < 1) { - // - // The result is the failure - // - return true; - } - // - // Check retries - // - if (this.attempts > getMaxRetries()) { - // - // No more attempts allowed, reset - // that our actual result is failure due to retries - // - this.policyResult = PolicyResult.FAILURE_RETRIES; - return true; - } else { - // - // There are more attempts available to try the - // policy recipe. - // - return false; - } - } - // - // Other results mean we are done - // - return true; - } - - public boolean isOperationRunning() { - return (this.currentOperation != null); - } - - /** - * This method verifies that the operation manager may run an operation. - * - * @return True if the operation can run, false otherwise - * @throws ControlLoopException if the operation cannot run - */ - private void verifyOperatonCanRun() throws ControlLoopException { - // - // They shouldn't call us if we currently running something - // - if (this.currentOperation != null) { - // - // what do we do if we are already running an operation? - // - throw new ControlLoopException( - "current operation is not null (an operation is already running)"); - } - // - // Check if we have maxed out on retries - // - if (getMaxRetries() < 1) { - // - // No retries are allowed, so check have we even made - // one attempt to execute the operation? - // - if (this.attempts >= 1) { - // - // We have, let's ensure our PolicyResult is set - // - if (this.policyResult == null) { - this.policyResult = PolicyResult.FAILURE_RETRIES; - } - // - // - // - throw new ControlLoopException( - "current operation failed and retries are not allowed"); - } - } else { - // - // Have we maxed out on retries? - // - if (this.attempts > getMaxRetries()) { - if (this.policyResult == null) { - this.policyResult = PolicyResult.FAILURE_RETRIES; - } - throw new ControlLoopException( - "current oepration has failed after " + this.attempts + " retries"); - } - } - } - - /** - * Gets the maximum number of retries. - * - * @return the maximum number of retries, or {@code 0}, if not specified - */ - public int getMaxRetries() { - return (policy.getRetry() != null ? policy.getRetry() : 0); - } - - private void storeOperationInDataBase() { - // Only store in DB if enabled - boolean guardEnabled = "false".equalsIgnoreCase( - PolicyEngineConstants.getManager().getEnvironmentProperty("guard.disabled")); - if (!guardEnabled) { - return; - } - - // DB Properties - Properties props = new Properties(); - if (PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_URL) != null - && PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_USER) != null - && PolicyEngineConstants.getManager() - .getEnvironmentProperty(Util.ONAP_KEY_PASS) != null) { - props.put(Util.ECLIPSE_LINK_KEY_URL, - PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_URL)); - props.put(Util.ECLIPSE_LINK_KEY_USER, - PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_USER)); - props.put(Util.ECLIPSE_LINK_KEY_PASS, - PolicyEngineConstants.getManager().getEnvironmentProperty(Util.ONAP_KEY_PASS)); - props.put(PersistenceUnitProperties.CLASSLOADER, - ControlLoopOperationManager.class.getClassLoader()); - } - - String opsHistPu = System.getProperty("OperationsHistoryPU"); - if (!"OperationsHistoryPUTest".equals(opsHistPu)) { - opsHistPu = "OperationsHistoryPU"; - } else { - props.clear(); - } - EntityManager em; - try { - em = Persistence.createEntityManagerFactory(opsHistPu, props).createEntityManager(); - } catch (Exception e) { - logger.error("storeOperationInDataBase threw: ", e); - return; - } - - OperationsHistory newEntry = new OperationsHistory(); - - newEntry.setClosedLoopName(this.onset.getClosedLoopControlName()); - newEntry.setRequestId(this.onset.getRequestId().toString()); - newEntry.setActor(this.currentOperation.clOperation.getActor()); - newEntry.setOperation(this.currentOperation.clOperation.getOperation()); - newEntry.setTarget(this.targetEntity); - newEntry.setStarttime(Timestamp.from(this.currentOperation.clOperation.getStart())); - newEntry.setSubrequestId(this.currentOperation.clOperation.getSubRequestId()); - newEntry - .setEndtime(new Timestamp(this.currentOperation.clOperation.getEnd().toEpochMilli())); - newEntry.setMessage(this.currentOperation.clOperation.getMessage()); - newEntry.setOutcome(this.currentOperation.clOperation.getOutcome()); - - em.getTransaction().begin(); - em.persist(newEntry); - em.getTransaction().commit(); - - em.close(); - } - - private void completeOperation(Integer attempt, String message, PolicyResult result) { - if (attempt == null) { - logger.debug("attempt cannot be null (i.e. subRequestID)"); - return; - } - if (this.currentOperation != null) { - if (this.currentOperation.attempt == attempt.intValue()) { - this.currentOperation.clOperation.setEnd(Instant.now()); - this.currentOperation.clOperation.setMessage(message); - this.currentOperation.clOperation.setOutcome(result.toString()); - this.currentOperation.policyResult = result; - // - // Save it in history - // - this.operationHistory.add(this.currentOperation); - this.storeOperationInDataBase(); - // - // Set our last result - // - this.policyResult = result; - // - // Clear the current operation field - // - this.currentOperation = null; - return; - } - logger.debug("not current"); - } - for (Operation op : this.operationHistory) { - if (op.attempt == attempt.intValue()) { - op.clOperation.setEnd(Instant.now()); - op.clOperation.setMessage(message); - op.clOperation.setOutcome(result.toString()); - op.policyResult = result; - return; - } - } - logger.debug("Could not find associated operation"); - } - - /** - * Commit the abatement to the history database. - * - * @param message the abatement message - * @param outcome the abatement outcome - */ - public void commitAbatement(String message, String outcome) { - logger.info("commitAbatement: {}. {}", message, outcome); - - if (this.currentOperation == null) { - try { - this.currentOperation = this.operationHistory.getLast(); - } catch (NoSuchElementException e) { - logger.error("{}: commitAbatement threw an exception ", this, e); - return; - } - } - this.currentOperation.clOperation.setEnd(Instant.now()); - this.currentOperation.clOperation.setMessage(message); - this.currentOperation.clOperation.setOutcome(outcome); - // - // Store commit in DB - // - this.storeOperationInDataBase(); - // - // Clear the current operation field - // - this.currentOperation = null; - } - - /** - * Construct a ControlLoopResponse object from actor response and input event. - * - * @param response the response from actor - * @param event the input event - * - * @return a ControlLoopResponse - */ - public ControlLoopResponse getControlLoopResponse(Object response, - VirtualControlLoopEvent event) { - if (response instanceof PciResponseWrapper) { - // - // Cast SDNR response and handle it - // - return SdnrActor.getControlLoopResponse((PciResponseWrapper) response, - event); - } else { - return null; - } - } - -} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemory.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemory.java deleted file mode 100644 index 738d3b922..000000000 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemory.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.controlloop.eventmanager; - -import lombok.Getter; -import org.drools.core.WorkingMemory; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.drools.core.lock.Lock; -import org.onap.policy.drools.core.lock.LockCallback; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Lock call-back that updates working memory. - */ -@Getter -public class LockCallbackWorkingMemory implements LockCallback { - private static final Logger logger = LoggerFactory.getLogger(LockCallbackWorkingMemory.class); - - /** - * Name to be logged when the lock is updated. - */ - private final String name; - - /** - * Working memory to be updated when the lock is notified. - */ - private final WorkingMemory workingMemory; - - - /** - * Constructs the object. - * - * @param name name to be logged when the lock is updated - * @param workingMemory working memory to be updated when the lock is notified - */ - public LockCallbackWorkingMemory(String name, WorkingMemory workingMemory) { - this.name = name; - this.workingMemory = workingMemory; - } - - @Override - public void lockAvailable(Lock lock) { - notifySession(lock); - } - - @Override - public void lockUnavailable(Lock lock) { - notifySession(lock); - } - - /** - * Notifies the session that the lock has been updated. - */ - private void notifySession(Lock lock) { - FactHandle fact = workingMemory.getFactHandle(lock); - if (fact != null) { - logger.debug("{}: updating lock={}", name, lock); - workingMemory.update(fact, lock); - } - } -} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ophistory/OperationHistoryDataManagerImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ophistory/OperationHistoryDataManagerImpl.java index 741ce20f8..f2feef666 100644 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ophistory/OperationHistoryDataManagerImpl.java +++ b/controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ophistory/OperationHistoryDataManagerImpl.java @@ -40,7 +40,6 @@ import org.onap.policy.common.utils.jpa.EntityTransCloser; import org.onap.policy.controlloop.ControlLoopOperation; import org.onap.policy.controlloop.VirtualControlLoopEvent; import org.onap.policy.guard.OperationsHistory; -import org.onap.policy.guard.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -322,9 +321,9 @@ public class OperationHistoryDataManagerImpl implements OperationHistoryDataMana */ private Properties toProperties(OperationHistoryDataManagerParams params) { Properties props = new Properties(); - props.put(Util.ECLIPSE_LINK_KEY_URL, params.getUrl()); - props.put(Util.ECLIPSE_LINK_KEY_USER, params.getUserName()); - props.put(Util.ECLIPSE_LINK_KEY_PASS, params.getPassword()); + props.put(PersistenceUnitProperties.JDBC_URL, params.getUrl()); + props.put(PersistenceUnitProperties.JDBC_USER, params.getUserName()); + props.put(PersistenceUnitProperties.JDBC_PASSWORD, params.getPassword()); props.put(PersistenceUnitProperties.CLASSLOADER, getClass().getClassLoader()); return props; diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java deleted file mode 100644 index 7e4c10749..000000000 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngine.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy engine - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools; - -@FunctionalInterface -public interface PolicyEngine { - public boolean deliver(String busType, String topic, Object obj); -} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java deleted file mode 100644 index 419c31094..000000000 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/PolicyEngineListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy engine - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools; - -@FunctionalInterface -public interface PolicyEngineListener { - /** - * Any class that implements this interface will be notified of a new event on the queue in the - * PolicyEngineJUnitImpl. - * - * @param topic a key to the queue that contains the event - */ - public void newEventNotification(String topic); -} diff --git a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java b/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java deleted file mode 100644 index 85fc13c9e..000000000 --- a/controlloop/common/eventmanager/src/main/java/org/onap/policy/drools/impl/PolicyEngineJUnitImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy engine - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.impl; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import org.onap.policy.appc.Request; -import org.onap.policy.appclcm.AppcLcmDmaapWrapper; -import org.onap.policy.controlloop.ControlLoopNotification; -import org.onap.policy.controlloop.util.Serialization; -import org.onap.policy.drools.PolicyEngine; -import org.onap.policy.drools.PolicyEngineListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PolicyEngineJUnitImpl implements PolicyEngine { - - private static final Logger logger = LoggerFactory.getLogger(PolicyEngineJUnitImpl.class); - private Map>> busMap = new HashMap<>(); - private List listeners = new ArrayList<>(); - - /** - * Adds all objects that implement PolicyEngineListener to the notification list when an event - * occurs. - * - * @param listener an object that is interest in knowing about events published to the - * PolicyEngine - */ - public void addListener(PolicyEngineListener listener) { - listeners.add(listener); - } - - /** - * Notifies all listeners about a new event. - * - * @param topic the topic in which the notification was sent to - */ - public void notifyListeners(String topic) { - for (PolicyEngineListener listener : listeners) { - listener.newEventNotification(topic); - } - } - - @Override - public boolean deliver(String busType, String topic, Object obj) { - if (obj instanceof ControlLoopNotification) { - ControlLoopNotification notification = (ControlLoopNotification) obj; - if (logger.isDebugEnabled()) { - logger.debug(Serialization.gsonPretty.toJson(notification)); - } - } - if (obj instanceof Request) { - Request request = (Request) obj; - logger.debug("Request: {} subrequest {}", request.getAction(), request.getCommonHeader().getSubRequestId()); - } else if (obj instanceof AppcLcmDmaapWrapper) { - AppcLcmDmaapWrapper dmaapRequest = (AppcLcmDmaapWrapper) obj; - logger.debug("Request: {} subrequest {}", dmaapRequest.getBody().getInput().getAction(), - dmaapRequest.getBody().getInput().getCommonHeader().getSubRequestId()); - } - // - // Does the bus exist? - // - if (!busMap.containsKey(busType)) { - logger.debug("creating new bus type {}", busType); - // - // Create the bus - // - busMap.put(busType, new HashMap<>()); - } - // - // Get the bus - // - Map> topicMap = busMap.get(busType); - // - // Does the topic exist? - // - if (!topicMap.containsKey(topic)) { - logger.debug("creating new topic {}", topic); - // - // Create the topic - // - topicMap.put(topic, new LinkedList<>()); - } - // - // Get the topic queue - // - logger.debug("queueing"); - boolean res = topicMap.get(topic).add(obj); - notifyListeners(topic); - return res; - } - - /** - * Subscribe to a topic on a bus. - * - * @param busType the bus type - * @param topic the topic - * @return the head of the queue, or null if the queue or bus does not exist or the - * queue is empty - */ - public Object subscribe(String busType, String topic) { - // - // Does the bus exist? - // - if (busMap.containsKey(busType)) { - // - // Get the bus - // - Map> topicMap = busMap.get(busType); - // - // Does the topic exist? - // - if (topicMap.containsKey(topic)) { - logger.debug("The queue has {}", topicMap.get(topic).size()); - return topicMap.get(topic).poll(); - } else { - logger.error("No topic exists {}", topic); - } - } else { - logger.error("No bus exists {}", busType); - } - return null; - } - -} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java index ab86a5341..aca8d9655 100644 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java +++ b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/ControlLoopExceptionTest.java @@ -3,7 +3,7 @@ * eventmanager * ================================================================================ * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019-2020 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. diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java deleted file mode 100644 index 7479f66b1..000000000 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManagerTest.java +++ /dev/null @@ -1,802 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2017-2020 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.controlloop.eventmanager; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.time.Instant; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.jetbrains.annotations.NotNull; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.common.utils.io.Serializer; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopException; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopTargetType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NewEventStatus; -import org.onap.policy.controlloop.policy.PolicyResult; -import org.onap.policy.drools.core.lock.Lock; -import org.onap.policy.drools.core.lock.LockCallback; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; -import org.powermock.reflect.Whitebox; - -public class ControlLoopEventManagerTest { - private static final String TARGET_LOCK_FIELD = "targetLock"; - private static final String ONSET_ONE = "onsetOne"; - private static final String VSERVER_NAME = "vserver.vserver-name"; - private static final String TEST_YAML = "src/test/resources/test.yaml"; - private static final String VNF_NAME = "generic-vnf.vnf-name"; - private static final String VNF_ID = "generic-vnf.vnf-id"; - private static final String AAI_USERNAME = "aai.username"; - private static final String AAI_URL = "aai.url"; - private static final String AAI_PASS = "aai.password"; - private static final String TWO_ONSET_TEST = "TwoOnsetTest"; - private static final String VNF_UUID = "83f674e8-7555-44d7-9a39-bdc3770b0491"; - - private VirtualControlLoopEvent onset; - private LockCallback callback; - - /** - * Set up test class. - */ - @BeforeClass - public static void setUpSimulator() throws Exception { - org.onap.policy.simulators.Util.buildAaiSim(); - - PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_USERNAME, "AAI"); - PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_PASS, "AAI"); - PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_URL, "http://localhost:6666"); - PolicyEngineConstants.getManager().setEnvironmentProperty("aai.customQuery", "false"); - } - - @AfterClass - public static void tearDownSimulator() { - HttpServletServerFactoryInstance.getServerFactory().destroy(); - } - - /** - * Setup. - */ - @Before - public void setUp() { - callback = mock(LockCallback.class); - - onset = new VirtualControlLoopEvent(); - onset.setClosedLoopControlName("ControlLoop-vUSP"); - onset.setRequestId(UUID.randomUUID()); - onset.setTarget("VM_NAME"); - onset.setClosedLoopAlarmStart(Instant.now()); - onset.setAai(new HashMap<>()); - onset.getAai().put("cloud-region.identity-url", "foo"); - onset.getAai().put("vserver.selflink", "bar"); - onset.getAai().put(VNF_ID, VNF_UUID); - onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onset.setTargetType(ControlLoopTargetType.VNF); - - PolicyEngineConstants.getManager().setEnvironmentProperty(AAI_URL, "http://localhost:6666"); - } - - @Test - public void testMethods() { - UUID requestId = UUID.randomUUID(); - ControlLoopEventManager clem = new ControlLoopEventManager("MyClosedLoopName", requestId); - - assertEquals("MyClosedLoopName", clem.getClosedLoopControlName()); - assertEquals(requestId, clem.getRequestId()); - - clem.setActivated(true); - assertEquals(true, clem.isActivated()); - - clem.setControlLoopResult("SUCCESS"); - assertEquals("SUCCESS", clem.getControlLoopResult()); - - clem.setControlLoopTimedOut(); - assertEquals(true, clem.isControlLoopTimedOut()); - - clem.setNumAbatements(12345); - assertEquals(Integer.valueOf(12345), clem.getNumAbatements()); - - clem.setNumOnsets(54321); - assertEquals(Integer.valueOf(54321), clem.getNumOnsets()); - - assertNull(clem.getOnsetEvent()); - assertNull(clem.getAbatementEvent()); - assertNull(clem.getProcessor()); - - assertEquals(true, clem.isControlLoopTimedOut()); - - assertNull(clem.unlockCurrentOperation()); - } - - @Test - public void testAlreadyActivated() { - VirtualControlLoopEvent event = getOnsetEvent(); - - ControlLoopEventManager manager = makeManager(event); - manager.setActivated(true); - VirtualControlLoopNotification notification = manager.activate(event); - assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification()); - } - - @Test - public void testActivationYaml() throws IOException, CoderException { - - VirtualControlLoopEvent event = getOnsetEvent(); - ControlLoopEventManager manager = makeManager(event); - - // Null YAML should fail - VirtualControlLoopNotification notificationNull = manager.activate((String) null, event); - assertNotNull(notificationNull); - assertEquals(ControlLoopNotificationType.REJECTED, notificationNull.getNotification()); - - // Empty YAML should fail - VirtualControlLoopNotification notificationEmpty = manager.activate("", event); - assertNotNull(notificationEmpty); - assertEquals(ControlLoopNotificationType.REJECTED, notificationEmpty.getNotification()); - - // Bad YAML should fail - InputStream isBad = new FileInputStream(new File("src/test/resources/notutf8.yaml")); - final String yamlStringBad = IOUtils.toString(isBad, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notificationBad = manager.activate(yamlStringBad, event); - assertNotNull(notificationBad); - assertEquals(ControlLoopNotificationType.REJECTED, notificationBad.getNotification()); - - - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - // Another activate should fail - VirtualControlLoopNotification notificationActive = manager.activate(yamlString, event); - assertNotNull(notificationActive); - assertEquals(ControlLoopNotificationType.REJECTED, notificationActive.getNotification()); - } - - @Test - public void testActivateToscaLegacy() throws IOException, CoderException { - String policy = - new String(Files.readAllBytes(Paths.get("src/test/resources/tosca-policy-legacy-vcpe.json"))); - ToscaPolicy toscaPolicy = new StandardCoder().decode(policy, ToscaPolicy.class); - - VirtualControlLoopEvent event = getOnsetEvent(); - ControlLoopEventManager manager = makeManager(event); - - // trigger a reject by passing the wrong policy type - toscaPolicy.setType("onap.policies.controlloop.operational.common.Drools"); - VirtualControlLoopNotification notification = manager.activate(toscaPolicy, event); - assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification()); - - // place back correct policy type - toscaPolicy.setType("onap.policies.controlloop.Operational"); - notification = manager.activate(toscaPolicy, event); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - // another activate should fail - notification = manager.activate(toscaPolicy, event); - assertEquals(ControlLoopNotificationType.REJECTED, notification.getNotification()); - } - - @Test - public void testControlLoopFinal() throws Exception { - VirtualControlLoopEvent event = getOnsetEvent(); - - ControlLoopEventManager manager = makeManager(event); - ControlLoopEventManager manager2 = manager; - assertThatThrownBy(manager2::isControlLoopFinal).isInstanceOf(ControlLoopException.class) - .hasMessage("ControlLoopEventManager MUST be activated first."); - - manager.setActivated(true); - assertThatThrownBy(manager2::isControlLoopFinal).isInstanceOf(ControlLoopException.class) - .hasMessage("No onset event for ControlLoopEventManager."); - - manager.setActivated(false); - - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); - assertNull(clfNotification); - - // serialize and de-serialize manager - manager = Serializer.roundTrip(manager); - - manager.getProcessor().nextPolicyForResult(PolicyResult.SUCCESS); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, clfNotification.getNotification()); - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_EXCEPTION); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - - manager.setControlLoopTimedOut(); - clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - } - - @NotNull - private VirtualControlLoopEvent getOnsetEvent() { - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(TWO_ONSET_TEST); - event.setRequestId(requestId); - event.setTarget(VNF_ID); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAai(new HashMap<>()); - event.getAai().put(VNF_NAME, ONSET_ONE); - event.setTargetType(ControlLoopTargetType.VNF); - return event; - } - - @Test - public void testProcessControlLoop() throws Exception { - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(TWO_ONSET_TEST); - event.setRequestId(requestId); - event.setTarget(VNF_ID); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAai(new HashMap<>()); - event.getAai().put(VNF_NAME, ONSET_ONE); - event.getAai().put(VSERVER_NAME, "testVserverName"); - event.setTargetType(ControlLoopTargetType.VNF); - - ControlLoopEventManager manager = makeManager(event); - ControlLoopEventManager manager2 = manager; - assertThatThrownBy(manager2::processControlLoop).isInstanceOf(ControlLoopException.class) - .hasMessage("ControlLoopEventManager MUST be activated first."); - - manager.setActivated(true); - assertThatThrownBy(manager2::processControlLoop).isInstanceOf(ControlLoopException.class) - .hasMessage("No onset event for ControlLoopEventManager."); - - manager.setActivated(false); - - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - // serialize and de-serialize manager - manager = Serializer.roundTrip(manager); - - // Test operation in progress - ControlLoopEventManager manager3 = manager; - assertThatThrownBy(manager3::processControlLoop).isInstanceOf(ControlLoopException.class) - .hasMessage("Already working an Operation, do not call this method."); - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE_GUARD); - VirtualControlLoopNotification clfNotification = manager.isControlLoopFinal(); - assertNotNull(clfNotification); - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, clfNotification.getNotification()); - - // Test operation completed - ControlLoopEventManager manager4 = manager; - assertThatThrownBy(manager4::processControlLoop).isInstanceOf(ControlLoopException.class) - .hasMessage("Control Loop is in FINAL state, do not call this method."); - - manager = new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); - notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - manager.getProcessor().nextPolicyForResult(PolicyResult.FAILURE); - - // Test operation with no next policy defined - ControlLoopEventManager manager5 = manager; - assertThatThrownBy(manager5::processControlLoop).isInstanceOf(ControlLoopException.class) - .hasMessage("The target type is null"); - } - - @Test - public void testFinishOperation() throws Exception { - InputStream isStd = new FileInputStream(new File(TEST_YAML)); - final String yamlStringStd = IOUtils.toString(isStd, StandardCharsets.UTF_8); - - VirtualControlLoopEvent event = makeEvent(); - - ControlLoopEventManager manager = makeManager(event); - ControlLoopEventManager manager2 = manager; - assertThatThrownBy(() -> manager2.finishOperation(null)).isInstanceOf(ControlLoopException.class) - .hasMessage("No operation to finish."); - - manager.setActivated(true); - assertThatThrownBy(() -> manager2.finishOperation(null)).isInstanceOf(ControlLoopException.class) - .hasMessage("No operation to finish."); - - manager.setActivated(false); - - InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - event.getAai().put(VSERVER_NAME, "testVserverName"); - - // serialize and de-serialize manager - manager = Serializer.roundTrip(manager); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - clom.startOperation(event); - - // This call should be exception free - manager.finishOperation(clom); - - ControlLoopEventManager otherManager = makeManager(event); - VirtualControlLoopNotification otherNotification = otherManager.activate(yamlStringStd, event); - assertNotNull(otherNotification); - assertEquals(ControlLoopNotificationType.ACTIVE, otherNotification.getNotification()); - - ControlLoopOperationManager otherClom = otherManager.processControlLoop(); - assertNotNull(otherClom); - assertNull(otherClom.getOperationResult()); - - otherManager.finishOperation(clom); - } - - @Test - public void testLockCurrentOperation_testUnlockCurrentOperation() throws Exception { - VirtualControlLoopEvent event = makeEvent(); - - ControlLoopEventManager manager = makeManager(event); - - manager.setActivated(false); - - InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager manager2 = manager; - assertThatThrownBy(() -> manager2.lockCurrentOperation(callback)).isInstanceOf(ControlLoopException.class) - .hasMessage("Do not have a current operation."); - - assertNull(manager.unlockCurrentOperation()); - - event.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - Pair lockPair = manager.lockCurrentOperation(callback); - assertNull(lockPair.getLeft()); - assertNotNull(lockPair.getRight()); - - // pseudo lock - session should NOT have been notified of the change - verify(callback, never()).lockAvailable(any()); - verify(callback, never()).lockUnavailable(any()); - - // repeat - should cause an extension - Lock lock = lockPair.getRight(); - lockPair = manager.lockCurrentOperation(callback); - - /* - * even with a pseudo lock, the session should have been notified that it was - * extended - */ - - verify(callback).lockAvailable(lock); - - assertSame(lock, manager.unlockCurrentOperation()); - - assertNull(lockPair.getLeft()); - assertNull(lockPair.getRight()); - - // force it to use a pseudo lock - manager.setUseTargetLock(false); - lockPair = manager.lockCurrentOperation(callback); - assertNull(lockPair.getLeft()); - assertNotNull(lockPair.getRight()); - - lock = lockPair.getRight(); - - lockPair = manager.lockCurrentOperation(callback); - assertNull(lockPair.getLeft()); - assertNull(lockPair.getRight()); - - // first lock uses a pseudo lock, so it will only update when extended - verify(callback).lockAvailable(lock); - - // force it to re-create the lock due to change in resource ID - lock = mock(Lock.class); - when(lock.getResourceId()).thenReturn("different"); - Whitebox.setInternalState(manager, TARGET_LOCK_FIELD, lock); - - lockPair = manager.lockCurrentOperation(callback); - assertSame(lock, lockPair.getLeft()); - assertNotNull(lockPair.getRight()); - - lock = lockPair.getRight(); - - lockPair = manager.lockCurrentOperation(callback); - assertNull(lockPair.getLeft()); - assertNull(lockPair.getRight()); - - // first lock uses a pseudo lock, so it won't do an update - verify(callback).lockAvailable(lock); - - assertSame(lock, manager.unlockCurrentOperation()); - assertNull(manager.unlockCurrentOperation()); - - // try again - this time don't return the fact handle- no change in count - lockPair = manager.lockCurrentOperation(callback); - assertNull(lockPair.getLeft()); - assertNotNull(lockPair.getRight()); - } - - @Test - public void testOnNewEvent() throws Exception { - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - - VirtualControlLoopEvent abatedEvent = new VirtualControlLoopEvent(); - abatedEvent.setClosedLoopControlName(TWO_ONSET_TEST); - abatedEvent.setRequestId(requestId); - abatedEvent.setTarget(VNF_ID); - abatedEvent.setClosedLoopAlarmStart(Instant.now()); - abatedEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ABATED); - abatedEvent.setAai(new HashMap<>()); - abatedEvent.getAai().put(VNF_NAME, ONSET_ONE); - - ControlLoopEventManager manager = makeManager(onsetEvent); - - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - assertEquals(NewEventStatus.FIRST_ONSET, manager.onNewEvent(onsetEvent)); - assertEquals(NewEventStatus.FIRST_ABATEMENT, manager.onNewEvent(abatedEvent)); - assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - - VirtualControlLoopEvent checkSyntaxEvent = new VirtualControlLoopEvent(); - checkSyntaxEvent.setAai(null); - checkSyntaxEvent.setClosedLoopAlarmEnd(null); - checkSyntaxEvent.setClosedLoopAlarmStart(null); - checkSyntaxEvent.setClosedLoopControlName(null); - checkSyntaxEvent.setClosedLoopEventClient(null); - checkSyntaxEvent.setClosedLoopEventStatus(null); - checkSyntaxEvent.setFrom(null); - checkSyntaxEvent.setPolicyName(null); - checkSyntaxEvent.setPolicyScope(null); - checkSyntaxEvent.setPolicyVersion(null); - checkSyntaxEvent.setRequestId(null); - checkSyntaxEvent.setTarget(null); - checkSyntaxEvent.setTargetType(null); - checkSyntaxEvent.setVersion(null); - - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopControlName(null); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopControlName(""); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setClosedLoopControlName(TWO_ONSET_TEST); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setRequestId(null); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setRequestId(requestId); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAai(null); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAai(new HashMap<>()); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTargetType(""); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(""); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(null); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(""); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("OZ"); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("VM_NAME"); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget("VNF_NAME"); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(VSERVER_NAME); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(VNF_ID); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setTarget(VNF_NAME); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAai(null); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.setAai(new HashMap<>()); - assertEquals(NewEventStatus.SYNTAX_ERROR, manager.onNewEvent(checkSyntaxEvent)); - - checkSyntaxEvent.getAai().put(VNF_NAME, ONSET_ONE); - assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - - checkSyntaxEvent.getAai().put(VSERVER_NAME, ONSET_ONE); - assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - - checkSyntaxEvent.getAai().put(VNF_ID, ONSET_ONE); - assertEquals(NewEventStatus.SUBSEQUENT_ABATEMENT, manager.onNewEvent(abatedEvent)); - } - - @Test - public void testControlLoopTimeout() throws IOException { - VirtualControlLoopEvent onsetEvent = getOnsetEvent(); - - ControlLoopEventManager manager = makeManager(onsetEvent); - assertEquals(0, manager.getControlLoopTimeout(null)); - assertEquals(120, manager.getControlLoopTimeout(120)); - - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - assertEquals(60, manager.getControlLoopTimeout(null)); - } - - @Test - public void testControlLoopTimeout_ZeroTimeout() throws IOException { - VirtualControlLoopEvent onsetEvent = getOnsetEvent(); - - ControlLoopEventManager manager = makeManager(onsetEvent); - - InputStream is = new FileInputStream(new File("src/test/resources/test-zero-timeout.yaml")); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - assertEquals(0, manager.getControlLoopTimeout(null)); - assertEquals(120, manager.getControlLoopTimeout(120)); - } - - @Test - public void testControlLoopTimeout_NullTimeout() throws IOException { - VirtualControlLoopEvent onsetEvent = getOnsetEvent(); - - ControlLoopEventManager manager = makeManager(onsetEvent); - - InputStream is = new FileInputStream(new File("src/test/resources/test-null-timeout.yaml")); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - assertEquals(0, manager.getControlLoopTimeout(null)); - assertEquals(120, manager.getControlLoopTimeout(120)); - } - - @Test - public void testIsClosedLoopDisabled() { - Map aai = onset.getAai(); - - // null, null - aai.remove(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED); - aai.remove(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED); - assertFalse(ControlLoopEventManager.isClosedLoopDisabled(onset)); - - // null, false - aai.remove(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED); - aai.put(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString()); - assertFalse(ControlLoopEventManager.isClosedLoopDisabled(onset)); - - // false, null - aai.put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.FALSE.toString()); - aai.remove(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED); - assertFalse(ControlLoopEventManager.isClosedLoopDisabled(onset)); - - // null, true - aai.remove(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED); - aai.put(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString()); - assertTrue(ControlLoopEventManager.isClosedLoopDisabled(onset)); - - // true, null - aai.put(ControlLoopEventManager.GENERIC_VNF_IS_CLOSED_LOOP_DISABLED, Boolean.TRUE.toString()); - aai.remove(ControlLoopEventManager.VSERVER_IS_CLOSED_LOOP_DISABLED); - assertTrue(ControlLoopEventManager.isClosedLoopDisabled(onset)); - } - - @Test - public void testIsProvStatusInactive() { - Map aai = onset.getAai(); - - // null, null - aai.remove(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS); - aai.remove(ControlLoopEventManager.VSERVER_PROV_STATUS); - assertFalse(ControlLoopEventManager.isProvStatusInactive(onset)); - - // null, active - aai.remove(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS); - aai.put(ControlLoopEventManager.VSERVER_PROV_STATUS, ControlLoopEventManager.PROV_STATUS_ACTIVE); - assertFalse(ControlLoopEventManager.isProvStatusInactive(onset)); - - // active, null - aai.put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, ControlLoopEventManager.PROV_STATUS_ACTIVE); - aai.remove(ControlLoopEventManager.VSERVER_PROV_STATUS); - assertFalse(ControlLoopEventManager.isProvStatusInactive(onset)); - - // null, inactive - aai.remove(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS); - aai.put(ControlLoopEventManager.VSERVER_PROV_STATUS, "other1"); - assertTrue(ControlLoopEventManager.isProvStatusInactive(onset)); - - // inactive, null - aai.put(ControlLoopEventManager.GENERIC_VNF_PROV_STATUS, "other2"); - aai.remove(ControlLoopEventManager.VSERVER_PROV_STATUS); - assertTrue(ControlLoopEventManager.isProvStatusInactive(onset)); - } - - @Test - public void testIsAaiTrue() { - assertTrue(ControlLoopEventManager.isAaiTrue("tRuE")); - assertTrue(ControlLoopEventManager.isAaiTrue("T")); - assertTrue(ControlLoopEventManager.isAaiTrue("t")); - assertTrue(ControlLoopEventManager.isAaiTrue("yES")); - assertTrue(ControlLoopEventManager.isAaiTrue("Y")); - assertTrue(ControlLoopEventManager.isAaiTrue("y")); - - assertFalse(ControlLoopEventManager.isAaiTrue("no")); - assertFalse(ControlLoopEventManager.isAaiTrue(null)); - } - - - private VirtualControlLoopEvent makeEvent() { - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(TWO_ONSET_TEST); - event.setRequestId(requestId); - event.setTarget(VNF_ID); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAai(new HashMap<>()); - event.getAai().put(VNF_ID, ONSET_ONE); - event.getAai().put(VSERVER_NAME, "test-vserver"); - event.setTargetType(ControlLoopTargetType.VNF); - return event; - } - - private ControlLoopEventManager makeManager(VirtualControlLoopEvent event) { - return new MyManager(event.getClosedLoopControlName(), event.getRequestId()); - } - - private static class MyManager extends ControlLoopEventManager implements Serializable { - private static final long serialVersionUID = 1L; - - public MyManager(String closedLoopControlName, UUID requestId) { - super(closedLoopControlName, requestId); - } - - @Override - protected Lock createRealLock(String targetEntity, UUID requestId, int holdSec, LockCallback callback) { - return createPseudoLock(targetEntity, requestId, holdSec, callback); - } - } -} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java deleted file mode 100644 index b64d9484e..000000000 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManagerTest.java +++ /dev/null @@ -1,929 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * unit test - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Bell Canada. - * ================================================================================ - * 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.controlloop.eventmanager; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.util.HashMap; -import java.util.UUID; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.Query; -import org.apache.commons.io.IOUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.policy.aai.util.AaiException; -import org.onap.policy.appc.CommonHeader; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.ResponseCode; -import org.onap.policy.appc.ResponseStatus; -import org.onap.policy.appclcm.AppcLcmBody; -import org.onap.policy.appclcm.AppcLcmCommonHeader; -import org.onap.policy.appclcm.AppcLcmDmaapWrapper; -import org.onap.policy.appclcm.AppcLcmInput; -import org.onap.policy.appclcm.AppcLcmOutput; -import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.common.utils.io.Serializer; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopException; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopTargetType; -import org.onap.policy.controlloop.SupportUtil; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.controlloop.policy.Policy; -import org.onap.policy.controlloop.policy.PolicyResult; -import org.onap.policy.controlloop.policy.Target; -import org.onap.policy.controlloop.policy.TargetType; -import org.onap.policy.controlloop.processor.ControlLoopProcessor; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.onap.policy.so.SoResponse; -import org.onap.policy.so.SoResponseWrapper; -import org.onap.policy.vfc.VfcResponse; -import org.onap.policy.vfc.VfcResponseDescriptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ControlLoopOperationManagerTest { - private static final String VSERVER_NAME = "vserver.vserver-name"; - private static final String TEST_YAML = "src/test/resources/test.yaml"; - private static final String TEST_CDS_YAML = "src/test/resources/test-cds.yaml"; - private static final String ONSET_ONE = "onsetOne"; - private static final String VNF_NAME = "generic-vnf.vnf-name"; - private static final String VNF_ID = "generic-vnf.vnf-id"; - private static final String TWO_ONSET_TEST = "TwoOnsetTest"; - private static final String OPER_MSG = "The Wizard Escaped"; - private static final String OZ_VNF = "OzVNF"; - private static final String OPERATIONS_HISTORY_PU_TEST = "OperationsHistoryPUTest"; - private static final String OPERATIONS_HISTORY_PU = "OperationsHistoryPU"; - private static final String DOROTHY = "Dorothy"; - private static final String APPC_FAILURE_REASON = "AppC failed for some reason"; - private static final String ACCEPT = "ACCEPT"; - - private static final Logger logger = - LoggerFactory.getLogger(ControlLoopOperationManagerTest.class); - - private static VirtualControlLoopEvent onset; - - static { - onset = new VirtualControlLoopEvent(); - onset.setRequestId(UUID.randomUUID()); - onset.setTarget(VNF_NAME); - onset.setTargetType(ControlLoopTargetType.VNF); - onset.setClosedLoopAlarmStart(Instant.now()); - onset.setAai(new HashMap<>()); - onset.getAai().put(VNF_NAME, "testTriggerSource"); - onset.getAai().put(VSERVER_NAME, "testVserverName"); - onset.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onset.setTargetType(ControlLoopTargetType.VNF); - - /* Set environment properties */ - PolicyEngineConstants.getManager().setEnvironmentProperty("aai.url", - "http://localhost:6666"); - PolicyEngineConstants.getManager().setEnvironmentProperty("aai.username", "AAI"); - PolicyEngineConstants.getManager().setEnvironmentProperty("aai.password", "AAI"); - PolicyEngineConstants.getManager().setEnvironmentProperty("aai.customQuery", "false"); - } - - private static EntityManagerFactory emf; - private static EntityManager em; - - private static int getCount() { - // Create a query for number of items in DB - String sql = "select count(*) as count from operationshistory"; - Query nq = em.createNativeQuery(sql); - - return ((Number) nq.getSingleResult()).intValue(); - } - - /** - * Set up test class. - */ - @BeforeClass - public static void setUp() throws Exception { - - org.onap.policy.simulators.Util.buildAaiSim(); - - // Set PU - System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST); - - // Enter dummy props to avoid nullPointerException - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_URL, "a"); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, "b"); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "c"); - - // Connect to in-mem db - emf = Persistence.createEntityManagerFactory(OPERATIONS_HISTORY_PU_TEST); - em = emf.createEntityManager(); - } - - /** - * Clean up test class. - */ - @AfterClass - public static void tearDown() { - em.close(); - emf.close(); - HttpServletServerFactoryInstance.getServerFactory().destroy(); - } - - @Test - public void testRetriesFail() throws Exception { - // - // Load up the policy - // - final SupportUtil.Pair pair = SupportUtil.loadYaml(TEST_YAML); - onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - onset.getAai().put(VSERVER_NAME, "testVserverName"); - - // - // Create a processor - // - final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); - // - // create the manager - // - ControlLoopEventManager eventManager = - new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NewEventStatus status = eventManager.onNewEvent(onset); - assertNotNull(status); - assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); - - ControlLoopOperationManager manager = - new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); - logger.debug("{}", manager); - // - // - // - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Start - // - Object request = manager.startOperation(onset); - logger.debug("{}", manager); - assertNotNull(request); - assertTrue(request instanceof AppcLcmDmaapWrapper); - AppcLcmDmaapWrapper dmaapRequest = (AppcLcmDmaapWrapper) request; - AppcLcmInput appcRequest = dmaapRequest.getBody().getInput(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("1")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Accept - // - AppcLcmOutput appcResponse = new AppcLcmOutput(appcRequest); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage(ACCEPT); - AppcLcmBody outputBody = new AppcLcmBody(); - outputBody.setOutput(appcResponse); - AppcLcmDmaapWrapper dmaapResponse = new AppcLcmDmaapWrapper(); - dmaapResponse.setBody(outputBody); - // - // - // - PolicyResult result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertNull(result); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to Fail it - // - appcResponse = new AppcLcmOutput(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage(APPC_FAILURE_REASON); - outputBody.setOutput(appcResponse); - dmaapResponse.setBody(outputBody); - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertEquals(PolicyResult.FAILURE, result); - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Retry it - // - request = manager.startOperation(onset); - logger.debug("{}", manager); - assertNotNull(request); - assertTrue(request instanceof AppcLcmDmaapWrapper); - dmaapRequest = (AppcLcmDmaapWrapper) request; - appcRequest = dmaapRequest.getBody().getInput(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().contentEquals("2")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // - // - appcResponse = new AppcLcmOutput(appcRequest); - logger.debug("{}", manager); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage(ACCEPT); - outputBody.setOutput(appcResponse); - dmaapResponse.setBody(outputBody); - // - // - // - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertNull(result); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to Fail it - // - appcResponse = new AppcLcmOutput(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage(APPC_FAILURE_REASON); - outputBody.setOutput(appcResponse); - dmaapResponse.setBody(outputBody); - result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertEquals(PolicyResult.FAILURE, result); - // - // Should be complete now - // - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertNotNull(manager.getOperationResult()); - assertEquals(PolicyResult.FAILURE_RETRIES, manager.getOperationResult()); - assertEquals(2, manager.getHistory().size()); - } - - @Test - public void testTimeout() throws Exception { - // - // Load up the policy - // - final SupportUtil.Pair pair = SupportUtil.loadYaml(TEST_YAML); - onset.setClosedLoopControlName(pair.key.getControlLoop().getControlLoopName()); - onset.getAai().put(VSERVER_NAME, "OzVServer"); - - // - // Create a processor - // - final ControlLoopProcessor processor = new ControlLoopProcessor(pair.value); - // - // create the manager - // - ControlLoopEventManager eventManager = - new ControlLoopEventManager(onset.getClosedLoopControlName(), onset.getRequestId()); - VirtualControlLoopNotification notification = eventManager.activate(onset); - - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopEventManager.NewEventStatus status = eventManager.onNewEvent(onset); - assertNotNull(status); - assertEquals(ControlLoopEventManager.NewEventStatus.FIRST_ONSET, status); - - ControlLoopOperationManager manager = - new ControlLoopOperationManager(onset, processor.getCurrentPolicy(), eventManager); - // - // - // - logger.debug("{}", manager); - assertFalse(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - // - // Start - // - Object request = manager.startOperation(onset); - logger.debug("{}", manager); - assertNotNull(request); - assertTrue((request) instanceof AppcLcmDmaapWrapper); - AppcLcmDmaapWrapper dmaapRequest = (AppcLcmDmaapWrapper) request; - AppcLcmInput appcRequest = dmaapRequest.getBody().getInput(); - assertTrue((appcRequest).getCommonHeader().getSubRequestId().contentEquals("1")); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Accept - // - AppcLcmDmaapWrapper dmaapResponse = new AppcLcmDmaapWrapper(); - AppcLcmOutput appcResponse = new AppcLcmOutput(appcRequest); - AppcLcmBody outputBody = new AppcLcmBody(); - outputBody.setOutput(appcResponse); - dmaapResponse.setBody(outputBody); - appcResponse.getStatus().setCode(100); - appcResponse.getStatus().setMessage(ACCEPT); - // - // - // - PolicyResult result = manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - assertNull(result); - assertFalse(manager.isOperationComplete()); - assertTrue(manager.isOperationRunning()); - // - // Now we are going to simulate Timeout - // - manager.setOperationHasTimedOut(); - logger.debug("{}", manager); - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertEquals(1, manager.getHistory().size()); - assertEquals(PolicyResult.FAILURE_TIMEOUT, manager.getOperationResult()); - // - // Now we are going to Fail the previous request - // - appcResponse = new AppcLcmOutput(appcRequest); - appcResponse.getStatus().setCode(401); - appcResponse.getStatus().setMessage(APPC_FAILURE_REASON); - outputBody.setOutput(appcResponse); - dmaapResponse.setBody(outputBody); - manager.onResponse(dmaapResponse); - logger.debug("{}", manager); - // - // - // - assertTrue(manager.isOperationComplete()); - assertFalse(manager.isOperationRunning()); - assertEquals(1, manager.getHistory().size()); - assertEquals(PolicyResult.FAILURE_TIMEOUT, manager.getOperationResult()); - } - - @Test - public void testMethods() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File("src/test/resources/testSOactor.yaml")); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - ControlLoopOperationManager clom = manager.processControlLoop(); - assertNotNull(clom); - assertNull(clom.getOperationResult()); - - clom.setEventManager(manager); - assertEquals(manager, clom.getEventManager()); - - assertNull(clom.getTargetEntity()); - - clom.setGuardApprovalStatus("WizardOKedIt"); - assertEquals("WizardOKedIt", clom.getGuardApprovalStatus()); - - assertNull(clom.getOperationResult()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - clom.getTarget(policy); - - final Target savedTarget = policy.getTarget(); - policy.setTarget(null); - assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target is null"); - - policy.setTarget(new Target()); - assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage("The target type is null"); - - policy.setTarget(savedTarget); - - policy.getTarget().setType(TargetType.PNF); - assertThatThrownBy(() -> clom.getTarget(policy)).hasMessage( - "Target in the onset event is either null or does not match target key expected in AAI section."); - - onsetEvent.setTarget("Oz"); - onsetEvent.getAai().remove(VNF_NAME); - onsetEvent.getAai().remove(VNF_ID); - onsetEvent.getAai().remove(VSERVER_NAME); - - policy.getTarget().setType(TargetType.VNF); - assertThatThrownBy(() -> clom.getTarget(policy)) - .hasMessage("Target does not match target type"); - - onsetEvent.setTarget(VSERVER_NAME); - onsetEvent.getAai().put(VSERVER_NAME, "OzVServer"); - assertEquals("OzVServer", clom.getTarget(policy)); - - onsetEvent.getAai().remove(VSERVER_NAME); - onsetEvent.setTarget(VNF_ID); - onsetEvent.getAai().put(VNF_ID, OZ_VNF); - assertEquals(OZ_VNF, clom.getTarget(policy)); - - onsetEvent.setTarget(VNF_NAME); - assertEquals(OZ_VNF, clom.getTarget(policy)); - - manager.onNewEvent(onsetEvent); - - policy.getTarget().setType(TargetType.VFC); - assertThatThrownBy(() -> clom.getTarget(policy)) - .hasMessage("The target type is not supported"); - - assertEquals(Integer.valueOf(20), clom.getOperationTimeout()); - - assertEquals("20s", clom.getOperationTimeoutString(100)); - - assertEquals(null, clom.getOperationMessage()); - assertEquals(null, clom.getOperationMessage(OPER_MSG)); - - clom.startOperation(onsetEvent); - - assertEquals( - "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1", - clom.getOperationMessage()); - assertEquals( - "actor=SO,operation=Restart,target=Target [type=VFC, resourceId=null],subRequestId=1, Guard result: " - + OPER_MSG, - clom.getOperationMessage(OPER_MSG)); - - assertEquals("actor=SO,operation=Restart,tar", clom.getOperationHistory().substring(0, 30)); - - clom.setOperationHasException("The Wizard is gone"); - clom.setOperationHasGuardDeny(); - } - - @Test - public void testConstructor() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "OzVServer"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = - new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setRecipe("ModifyConfig"); - onsetEvent.getAai().put(VSERVER_NAME, "NonExistentVserver"); - policy.getTarget().setResourceID(UUID.randomUUID().toString()); - assertThatThrownBy(() -> new ControlLoopOperationManager(onsetEvent, policy, manager)) - .hasMessage("Target vnf-id could not be found"); - - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - policy.getTarget().setResourceID("bbb3cefd-01c8-413c-9bdd-2b92f9ca3d38"); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setActor("SO"); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setActor("VFC"); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - policy.setActor(DOROTHY); - assertThatThrownBy(() -> new ControlLoopOperationManager(onsetEvent, policy, manager)) - .hasMessage("ControlLoopEventManager: policy has an unknown actor."); - } - - @Test - public void testStartOperation() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = - new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - clom.startOperation(onsetEvent); - ControlLoopOperationManager clom2 = clom; - assertThatThrownBy(() -> clom2.startOperation(onsetEvent)) - .hasMessage("current operation is not null (an operation is already running)"); - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - final String savedRecipe = policy.getRecipe(); - policy.setRecipe("ModifyConfig"); - policy.getTarget().setResourceID(UUID.randomUUID().toString()); - clom.startOperation(onsetEvent); - policy.setRecipe(savedRecipe); - - policy.setRetry(null); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - assertTrue(clom.isOperationComplete()); - ControlLoopOperationManager clom3 = clom; - assertThatThrownBy(() -> clom3.startOperation(onsetEvent)) - .hasMessage("current operation failed and retries are not allowed"); - - policy.setRetry(0); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - assertTrue(clom.isOperationComplete()); - ControlLoopOperationManager clom4 = clom; - assertThatThrownBy(() -> clom4.startOperation(onsetEvent)) - .hasMessage("current operation failed and retries are not allowed"); - - policy.setRetry(1); - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - clom.startOperation(onsetEvent); - clom.setOperationHasTimedOut(); - assertTrue(clom.isOperationComplete()); - ControlLoopOperationManager clom5 = clom; - assertThatThrownBy(() -> clom5.startOperation(onsetEvent)) - .hasMessage("current oepration has failed after 2 retries"); - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - policy.setActor("SO"); - clom.startOperation(onsetEvent); - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - policy.setActor("VFC"); - clom.startOperation(onsetEvent); - - clom = new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - policy.setActor("Oz"); - ControlLoopOperationManager clom6 = clom; - assertThatThrownBy(() -> clom6.startOperation(onsetEvent)) - .hasMessage("invalid actor Oz on policy"); - } - - @Test - public void testOnResponse() throws IOException, ControlLoopException, AaiException { - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = - new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - assertNull(clom.onResponse(null)); - - Response appcResponse = new Response(); - CommonHeader commonHeader = new CommonHeader(); - appcResponse.setCommonHeader(commonHeader); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - commonHeader.setSubRequestId("12345"); - appcResponse.setStatus(null); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - ResponseStatus responseStatus = new ResponseStatus(); - appcResponse.setStatus(responseStatus); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(0); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.ACCEPT.getValue()); - assertEquals(null, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.ERROR.getValue()); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.FAILURE.getValue()); - assertEquals(PolicyResult.FAILURE, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.REJECT.getValue()); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(appcResponse)); - - responseStatus.setCode(ResponseCode.SUCCESS.getValue()); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(appcResponse)); - - AppcLcmDmaapWrapper dmaapWrapper = new AppcLcmDmaapWrapper(); - AppcLcmBody body = new AppcLcmBody(); - AppcLcmOutput output = new AppcLcmOutput(); - AppcLcmCommonHeader lcmCh = new AppcLcmCommonHeader(); - output.setCommonHeader(lcmCh); - body.setOutput(output); - dmaapWrapper.setBody(body); - - lcmCh.setSubRequestId("NotANumber"); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(dmaapWrapper)); - - lcmCh.setSubRequestId("12345"); - assertEquals(PolicyResult.FAILURE_EXCEPTION, clom.onResponse(dmaapWrapper)); - - SoResponse soResponse = new SoResponse(); - SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null); - - soResponse.setHttpResponseCode(200); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw)); - - soResponse.setHttpResponseCode(202); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(soRw)); - - soResponse.setHttpResponseCode(500); - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - - VfcResponse vfcResponse = new VfcResponse(); - VfcResponseDescriptor responseDescriptor = new VfcResponseDescriptor(); - vfcResponse.setResponseDescriptor(responseDescriptor); - - responseDescriptor.setStatus("finished"); - assertEquals(PolicyResult.SUCCESS, clom.onResponse(vfcResponse)); - - responseDescriptor.setStatus("unfinished"); - assertEquals(PolicyResult.FAILURE, clom.onResponse(vfcResponse)); - } - - @Test - public void testCompleteOperation() throws ControlLoopException, AaiException, IOException { - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = - new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - clom.startOperation(onsetEvent); - - SoResponse soResponse = new SoResponse(); - final SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null); - - PolicyEngineConstants.getManager().setEnvironmentProperty("guard.disabled", "false"); - PolicyEngineConstants.getManager().setEnvironmentProperty( - org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow"); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, DOROTHY); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); - - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - - System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST); - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - } - - @Test - public void testStartCdsOperation() throws ControlLoopException, IOException { - - // Prepare - String yamlString; - try (InputStream is = new FileInputStream(new File(TEST_CDS_YAML))) { - yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - } - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(TWO_ONSET_TEST); - event.setRequestId(requestId); - event.setTarget(VNF_ID); - event.setTargetType(ControlLoopTargetType.VNF); - event.setClosedLoopAlarmStart(Instant.now()); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - event.setAai(new HashMap<>()); - event.getAai().put(VNF_NAME, ONSET_ONE); - event.getAai().put(VSERVER_NAME, "OzVServer"); - - ControlLoopEventManager eventManager = - new ControlLoopEventManager(event.getClosedLoopControlName(), event.getRequestId()); - VirtualControlLoopNotification notification = eventManager.activate(yamlString, event); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = eventManager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager operationManager = - new ControlLoopOperationManager(event, policy, eventManager); - - // Run - Object result = operationManager.startOperation(event); - - // Verify - assertNotNull(result); - assertTrue(result instanceof ExecutionServiceInput); - ExecutionServiceInput request = (ExecutionServiceInput) result; - logger.debug("request: " + request); - - } - - @Test - public void testCommitAbatement() throws Exception { - - String yamlString; - try (InputStream is = new FileInputStream(new File(TEST_YAML))) { - yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - } - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = - new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - clom.startOperation(onsetEvent); - - int numEventsBefore = getCount(); - logger.info("numEventsBefore={}", numEventsBefore); - - clom.commitAbatement("Test message", "TEST_RESULT"); - - int numEventsAfter = getCount(); - logger.info("numEventsAfter={}", numEventsAfter); - - int diff = numEventsAfter - numEventsBefore; - assertEquals(1, diff); - } - - @Test - public void testSerialization() throws Exception { - InputStream is = new FileInputStream(new File(TEST_YAML)); - final String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8); - - UUID requestId = UUID.randomUUID(); - VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent(); - onsetEvent.setClosedLoopControlName(TWO_ONSET_TEST); - onsetEvent.setRequestId(requestId); - onsetEvent.setTarget(VNF_ID); - onsetEvent.setTargetType(ControlLoopTargetType.VNF); - onsetEvent.setClosedLoopAlarmStart(Instant.now()); - onsetEvent.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - onsetEvent.setAai(new HashMap<>()); - onsetEvent.getAai().put(VNF_NAME, ONSET_ONE); - onsetEvent.getAai().put(VSERVER_NAME, "testVserverName"); - - ControlLoopEventManager manager = new ControlLoopEventManager( - onsetEvent.getClosedLoopControlName(), onsetEvent.getRequestId()); - VirtualControlLoopNotification notification = manager.activate(yamlString, onsetEvent); - assertNotNull(notification); - assertEquals(ControlLoopNotificationType.ACTIVE, notification.getNotification()); - - Policy policy = manager.getProcessor().getCurrentPolicy(); - ControlLoopOperationManager clom = - new ControlLoopOperationManager(onsetEvent, policy, manager); - assertNotNull(clom); - - clom.startOperation(onsetEvent); - assertTrue(clom.isOperationRunning()); - - clom = Serializer.roundTrip(clom); - assertNotNull(clom); - assertTrue(clom.isOperationRunning()); - - SoResponse soResponse = new SoResponse(); - final SoResponseWrapper soRw = new SoResponseWrapper(soResponse, null); - - PolicyEngineConstants.getManager().setEnvironmentProperty("guard.disabled", "false"); - PolicyEngineConstants.getManager().setEnvironmentProperty( - org.onap.policy.guard.Util.ONAP_KEY_URL, "http://somewhere.over.the.rainbow"); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_USER, DOROTHY); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(org.onap.policy.guard.Util.ONAP_KEY_PASS, "Toto"); - - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - assertFalse(clom.isOperationRunning()); - assertEquals(1, clom.getHistory().size()); - - clom = Serializer.roundTrip(clom); - assertNotNull(clom); - assertFalse(clom.isOperationRunning()); - assertEquals(1, clom.getHistory().size()); - - System.setProperty(OPERATIONS_HISTORY_PU, OPERATIONS_HISTORY_PU_TEST); - assertEquals(PolicyResult.FAILURE, clom.onResponse(soRw)); - - clom = Serializer.roundTrip(clom); - assertNotNull(clom); - assertFalse(clom.isOperationRunning()); - assertEquals(1, clom.getHistory().size()); - } -} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemoryTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemoryTest.java deleted file mode 100644 index 18ab15b5a..000000000 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/LockCallbackWorkingMemoryTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.controlloop.eventmanager; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.drools.core.WorkingMemory; -import org.junit.Before; -import org.junit.Test; -import org.kie.api.runtime.rule.FactHandle; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.policy.drools.core.lock.Lock; - -public class LockCallbackWorkingMemoryTest { - private static final String MY_NAME = "my-name"; - - @Mock - private WorkingMemory workingMemory; - - @Mock - private Lock lock; - - @Mock - private FactHandle fact; - - private LockCallbackWorkingMemory callback; - - - /** - * Initializes mocks and creates a call-back. - */ - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - - when(workingMemory.getFactHandle(lock)).thenReturn(fact); - - callback = new LockCallbackWorkingMemory(MY_NAME, workingMemory); - } - - @Test - public void testLockCallbackWorkingMemory() { - assertEquals(MY_NAME, callback.getName()); - assertSame(workingMemory, callback.getWorkingMemory()); - } - - @Test - public void testLockAvailable() { - callback.lockAvailable(lock); - verify(workingMemory).update(fact, lock); - - // "remove" from working memory - when(workingMemory.getFactHandle(lock)).thenReturn(null); - callback.lockAvailable(lock); - - // should be no additional calls - verify(workingMemory).update(any(), any()); - } - - @Test - public void testLockUnavailable() { - callback.lockUnavailable(lock); - verify(workingMemory).update(fact, lock); - - // "remove" from working memory - when(workingMemory.getFactHandle(lock)).thenReturn(null); - callback.lockUnavailable(lock); - - // should be no additional calls - verify(workingMemory).update(any(), any()); - } - -} diff --git a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java b/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java deleted file mode 100644 index 3b61faaf2..000000000 --- a/controlloop/common/eventmanager/src/test/java/org/onap/policy/drools/DroolsPolicyEngineTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * eventmanager - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.onap.policy.appc.CommonHeader; -import org.onap.policy.appc.Request; -import org.onap.policy.appclcm.AppcLcmBody; -import org.onap.policy.appclcm.AppcLcmCommonHeader; -import org.onap.policy.appclcm.AppcLcmDmaapWrapper; -import org.onap.policy.appclcm.AppcLcmInput; -import org.onap.policy.controlloop.ControlLoopNotification; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.drools.impl.PolicyEngineJUnitImpl; - -public class DroolsPolicyEngineTest { - private static final String TOPIC = "TheWizardOfOz"; - private static final String OMNI_BUS = "OmniBus"; - - @Test - public void testDroolsPolicyEngine() { - PolicyEngineJUnitImpl pe = new PolicyEngineJUnitImpl(); - assertNotNull(pe); - - pe.addListener(new TestPolicyEngineListener()); - pe.notifyListeners(TOPIC); - - pe.subscribe(OMNI_BUS, TOPIC); - - pe.deliver(OMNI_BUS, TOPIC, "Dorothy"); - - pe.subscribe(OMNI_BUS, TOPIC); - pe.subscribe(OMNI_BUS, "ThisTopicDoesNotExist"); - - ControlLoopNotification notification = new VirtualControlLoopNotification(); - pe.deliver(OMNI_BUS, TOPIC, notification); - - Request request = new Request(); - request.setCommonHeader(new CommonHeader()); - request.getCommonHeader().setSubRequestId("12321"); - pe.deliver(OMNI_BUS, TOPIC, request); - - AppcLcmDmaapWrapper lcmRw = new AppcLcmDmaapWrapper(); - lcmRw.setBody(new AppcLcmBody()); - lcmRw.getBody().setInput(new AppcLcmInput()); - lcmRw.getBody().getInput().setCommonHeader(new AppcLcmCommonHeader()); - lcmRw.getBody().getInput().getCommonHeader().setSubRequestId("54321"); - pe.deliver(OMNI_BUS, TOPIC, lcmRw); - } - - private class TestPolicyEngineListener implements PolicyEngineListener { - @Override - public void newEventNotification(String topic) { - assertEquals(TOPIC, topic); - } - } -} diff --git a/controlloop/common/feature-controlloop-management/pom.xml b/controlloop/common/feature-controlloop-management/pom.xml index 965e38d7c..2fcb0dee5 100644 --- a/controlloop/common/feature-controlloop-management/pom.xml +++ b/controlloop/common/feature-controlloop-management/pom.xml @@ -154,11 +154,6 @@ eventmanager ${project.version} - - org.onap.policy.drools-applications.controlloop.common - guard - ${project.version} - org.onap.policy.models.policy-models-interactions.model-actors actorServiceProvider diff --git a/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/server/restful/RestControlLoopManager.java b/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/server/restful/RestControlLoopManager.java index b733b01ba..ba7885678 100644 --- a/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/server/restful/RestControlLoopManager.java +++ b/controlloop/common/feature-controlloop-management/src/main/java/org/onap/policy/drools/server/restful/RestControlLoopManager.java @@ -38,8 +38,8 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.onap.policy.aai.AaiManager; import org.onap.policy.controlloop.drl.legacy.ControlLoopParams; -import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; import org.onap.policy.drools.apps.controlloop.feature.management.ControlLoopManagementFeature; +import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.drools.system.PolicyEngineConstants; import org.onap.policy.rest.RestManager; import org.slf4j.Logger; @@ -124,16 +124,15 @@ public class RestControlLoopManager { @Path("engine/tools/controlloops/aai/customQuery/{vserverId}") @ApiOperation(value = "AAI Custom Query") public Response aaiCustomQuery(@ApiParam(value = "vserver Identifier") String vserverId) { + PolicyEngine mgr = PolicyEngineConstants.getManager(); + return Response .status(Status.OK) .entity(new AaiManager(new RestManager()) .getCustomQueryResponse( - PolicyEngineConstants.getManager() - .getEnvironmentProperty(ControlLoopEventManager.AAI_URL), - PolicyEngineConstants.getManager().getEnvironmentProperty( - ControlLoopEventManager.AAI_USERNAME_PROPERTY), - PolicyEngineConstants.getManager().getEnvironmentProperty( - ControlLoopEventManager.AAI_PASS_PROPERTY), + mgr.getEnvironmentProperty("aai.url"), + mgr.getEnvironmentProperty("aai.username"), + mgr.getEnvironmentProperty("aai.password"), UUID.randomUUID(), vserverId)) .build(); diff --git a/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java b/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java index 2a5bffc7f..94aa22485 100644 --- a/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java +++ b/controlloop/common/feature-controlloop-management/src/test/java/org/onap/policy/drools/server/restful/RestControlLoopManagerTest.java @@ -39,10 +39,10 @@ import org.kie.api.builder.ReleaseId; import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.network.NetworkUtil; -import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; import org.onap.policy.drools.persistence.SystemPersistenceConstants; import org.onap.policy.drools.properties.DroolsPropertyConstants; import org.onap.policy.drools.system.PolicyControllerConstants; +import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.drools.system.PolicyEngineConstants; import org.onap.policy.drools.util.KieUtils; import org.onap.policy.drools.utils.logging.LoggerUtil; @@ -122,12 +122,10 @@ public class RestControlLoopManagerTest { await().atMost(1, TimeUnit.MINUTES).until(isContainerAlive()); - PolicyEngineConstants.getManager().setEnvironmentProperty(ControlLoopEventManager.AAI_URL, - "http://localhost:6666"); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(ControlLoopEventManager.AAI_USERNAME_PROPERTY, "AAI"); - PolicyEngineConstants.getManager() - .setEnvironmentProperty(ControlLoopEventManager.AAI_PASS_PROPERTY, "AAI"); + PolicyEngine mgr = PolicyEngineConstants.getManager(); + mgr.setEnvironmentProperty("aai.url", "http://localhost:6666"); + mgr.setEnvironmentProperty("aai.username", "AAI"); + mgr.setEnvironmentProperty("aai.password", "AAI"); Util.buildAaiSim(); } diff --git a/controlloop/common/feature-controlloop-usecases/pom.xml b/controlloop/common/feature-controlloop-usecases/pom.xml deleted file mode 100644 index b8351d6b6..000000000 --- a/controlloop/common/feature-controlloop-usecases/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - 4.0.0 - - - org.onap.policy.drools-applications.controlloop.common - drools-applications-common - 1.7.1-SNAPSHOT - - - feature-controlloop-usecases - - - Load Experimental Usecases Control Loop Use Cases Controller as a feature. - - - - - - src/main/feature - true - - - src/main/resources - - - - - maven-assembly-plugin - - - zipfile - - single - - package - - true - ${project.artifactId}-${project.version} - - src/assembly/assemble_zip.xml - - false - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-dependencies - - copy-dependencies - - prepare-package - - ${project.build.directory}/assembly/lib - false - true - true - false - false - false - runtime - true - - - - - - - - - - org.onap.policy.drools-applications.controlloop.common - controller-usecases - ${project.version} - - - org.onap.policy.drools-pdp - policy-management - ${version.policy.drools-pdp} - provided - - - junit - junit - test - - - diff --git a/controlloop/common/feature-controlloop-usecases/src/assembly/assemble_zip.xml b/controlloop/common/feature-controlloop-usecases/src/assembly/assemble_zip.xml deleted file mode 100644 index c284ede07..000000000 --- a/controlloop/common/feature-controlloop-usecases/src/assembly/assemble_zip.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - feature-controlloop-usecases-package - - zip - - - false - - - - target - lib/feature - - feature-controlloop-usecases-${project.version}.jar - - - - target/assembly/lib - artifacts - - controller-usecases-${project.version}.jar - - - - target/assembly/lib - lib/dependencies - - *.jar - - - controller-usecases-${project.version}.jar - - - - target/classes/config - config - 0644 - - - - src/main/feature/bin - bin - 0755 - - - - src/main/feature/db - db - 0744 - - - - src/main/feature/install - install - 0755 - - - - - diff --git a/controlloop/common/feature-controlloop-usecases/src/main/feature/config/logback-include-usecases.xml b/controlloop/common/feature-controlloop-usecases/src/main/feature/config/logback-include-usecases.xml deleted file mode 100644 index 46f2f0c4f..000000000 --- a/controlloop/common/feature-controlloop-usecases/src/main/feature/config/logback-include-usecases.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - - - - - - - - ${logDir}/${usecasesLog}.log - - ${logDir}/${usecasesLog}.%d{yyyy-MM-dd}.%i.log.zip - 50MB - 30 - 10GB - - - ${networkPattern} - - - - - - - - - - - - \ No newline at end of file diff --git a/controlloop/common/feature-controlloop-usecases/src/main/feature/config/usecases-controller.properties b/controlloop/common/feature-controlloop-usecases/src/main/feature/config/usecases-controller.properties deleted file mode 100644 index 048130d87..000000000 --- a/controlloop/common/feature-controlloop-usecases/src/main/feature/config/usecases-controller.properties +++ /dev/null @@ -1,64 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ONAP -# ================================================================================ -# Copyright (C) 2018-2020 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========================================================= -### - -controller.name=usecases - -dmaap.source.topics=DCAE_TOPIC,APPC-CL,APPC-LCM-WRITE,SDNR-CL-RSP -dmaap.sink.topics=APPC-CL,APPC-LCM-READ,POLICY-CL-MGT,SDNR-CL,DCAE_CL_RSP - -dmaap.source.topics.DCAE_TOPIC.events=\ - org.onap.policy.controlloop.CanonicalOnset,org.onap.policy.controlloop.CanonicalAbated -dmaap.source.topics.DCAE_TOPIC.events.org.onap.policy.controlloop.CanonicalOnset.\ - filter=[?($.closedLoopEventStatus == 'ONSET')] -dmaap.source.topics.DCAE_TOPIC.events.org.onap.policy.controlloop.CanonicalAbated.\ - filter=[?($.closedLoopEventStatus == 'ABATED')] -dmaap.source.topics.DCAE_TOPIC.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gson - -dmaap.source.topics.APPC-CL.events=org.onap.policy.appc.Response -dmaap.source.topics.APPC-CL.events.org.onap.policy.appc.Response.filter=[?($.CommonHeader && $.Status)] -dmaap.source.topics.APPC-CL.events.custom.gson=org.onap.policy.appc.util.Serialization,gsonPretty - -dmaap.source.topics.APPC-LCM-WRITE.events=org.onap.policy.appclcm.AppcLcmDmaapWrapper -dmaap.source.topics.APPC-LCM-WRITE.events.org.onap.policy.appclcm.AppcLcmDmaapWrapper.filter=[?($.type == 'response')] -dmaap.source.topics.APPC-LCM-WRITE.events.custom.gson=org.onap.policy.appclcm.util.Serialization,gson - -dmaap.sink.topics.APPC-CL.events=org.onap.policy.appc.Request -dmaap.sink.topics.APPC-CL.events.custom.gson=org.onap.policy.appc.util.Serialization,gsonPretty - -dmaap.sink.topics.APPC-LCM-READ.events=org.onap.policy.appclcm.AppcLcmDmaapWrapper -dmaap.sink.topics.APPC-LCM-READ.events.custom.gson=org.onap.policy.appclcm.util.Serialization,gson - -dmaap.sink.topics.POLICY-CL-MGT.events=org.onap.policy.controlloop.VirtualControlLoopNotification -dmaap.sink.topics.POLICY-CL-MGT.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gsonPretty - -dmaap.sink.topics.SDNR-CL.events=org.onap.policy.sdnr.PciRequestWrapper -dmaap.sink.topics.SDNR-CL.events.custom.gson=org.onap.policy.sdnr.util.Serialization,gson - -dmaap.sink.topics.DCAE_CL_RSP.events=org.onap.policy.controlloop.ControlLoopResponse -dmaap.sink.topics.DCAE_CL_RSP.events.custom.gson=org.onap.policy.controlloop.util.Serialization,gsonPretty - -dmaap.source.topics.SDNR-CL-RSP.events=org.onap.policy.sdnr.PciResponseWrapper -dmaap.source.topics.SDNR-CL-RSP.events.org.onap.policy.sdnr.PciResponseWrapper.filter=[?($.type == 'response')] -dmaap.source.topics.SDNR-CL-RSP.events.custom.gson=org.onap.policy.sdnr.util.Serialization,gson - -rules.groupId=${project.groupId} -rules.artifactId=controller-usecases -rules.version=${project.version} - diff --git a/controlloop/common/feature-controlloop-usecases/src/main/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeature.java b/controlloop/common/feature-controlloop-usecases/src/main/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeature.java deleted file mode 100644 index 12c496f8c..000000000 --- a/controlloop/common/feature-controlloop-usecases/src/main/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeature.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.apps.controlloop.feature.usecases; - -import org.onap.policy.drools.features.PolicyEngineFeatureApi; - -/** - * Usecases installation as a feature saves time - * loading the Usecases controller at runtime over the - * usual installation from nexus. It also reduces - * potential for errors in the pom.xml generated in - * the brmsgw side. - * - *

There is no impact on other components as the brmsgw - * etc .. they will continue operating as usual. - * - *

This class will be expanded in the future for additional - * functionality - * - */ -public class UsecasesFeature implements PolicyEngineFeatureApi { - - public static final int SEQNO = 1000; - - @Override - public int getSequenceNumber() { - return SEQNO; - } - -} diff --git a/controlloop/common/feature-controlloop-usecases/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi b/controlloop/common/feature-controlloop-usecases/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi deleted file mode 100644 index 3a8263942..000000000 --- a/controlloop/common/feature-controlloop-usecases/src/main/resources/META-INF/services/org.onap.policy.drools.features.PolicyEngineFeatureApi +++ /dev/null @@ -1 +0,0 @@ -org.onap.policy.drools.apps.controlloop.feature.usecases.UsecasesFeature diff --git a/controlloop/common/feature-controlloop-usecases/src/test/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeatureTest.java b/controlloop/common/feature-controlloop-usecases/src/test/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeatureTest.java deleted file mode 100644 index ed1bba23d..000000000 --- a/controlloop/common/feature-controlloop-usecases/src/test/java/org/onap/policy/drools/apps/controlloop/feature/usecases/UsecasesFeatureTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.apps.controlloop.feature.usecases; - -import static org.junit.Assert.assertEquals; - -public class UsecasesFeatureTest { - - @org.junit.Test - public void getSequenceNumber() { - assertEquals(UsecasesFeature.SEQNO, new UsecasesFeature().getSequenceNumber()); - } -} diff --git a/controlloop/common/guard/pom.xml b/controlloop/common/guard/pom.xml deleted file mode 100644 index 146e43bec..000000000 --- a/controlloop/common/guard/pom.xml +++ /dev/null @@ -1,177 +0,0 @@ - - - 4.0.0 - - - org.onap.policy.drools-applications.controlloop.common - drools-applications-common - 1.7.1-SNAPSHOT - - - guard - - - - org.onap.policy.models.policy-models-interactions - model-yaml - ${policy.models.version} - provided - - - com.att.research.xacml - xacml-pdp - 2.2.0 - - - - commons-codec - commons-codec - - - commons-logging - commons-logging - - - guava - com.google.guava - - - commons-lang3 - org.apache.commons - - - jackson-databind - com.fasterxml.jackson.core - - - commons-collections - commons-collections - - - commons-lang - commons-lang - - - - - commons-io - commons-io - provided - - - org.apache.httpcomponents - httpclient - provided - - - org.drools - drools-core - provided - - - org.eclipse.persistence - org.eclipse.persistence.jpa - provided - - - org.onap.policy.common - policy-endpoints - ${version.policy.common} - provided - - - org.onap.policy.drools-pdp - policy-management - ${version.policy.drools-pdp} - provided - - - org.onap.policy.models.policy-models-interactions - simulators - ${policy.models.version} - test - - - org.onap.policy.models - policy-models-decisions - ${policy.models.version} - - - org.onap.policy.models.policy-models-interactions.model-impl - rest - ${policy.models.version} - - - org.mockito - mockito-core - test - - - com.h2database - h2 - test - - - - - - maven-checkstyle-plugin - - - onap-java-style - - check - - process-sources - - - onap-checkstyle/onap-java-style.xml - - ${project.build.sourceDirectory} - true - true - true - - - true - true - warning - - - - - - org.onap.oparent - checkstyle - ${oparent.version} - compile - - - - - - diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java deleted file mode 100644 index 0331b7aab..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java +++ /dev/null @@ -1,155 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2020 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.guard; - -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; -import java.util.function.Supplier; -import org.drools.core.WorkingMemory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class CallGuardTask implements Runnable { - - private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class); - - /** - * Actor/recipe pairs whose guard requests need a VF Module count. Each element is of - * the form "<actor>:<recipe>". - */ - private static final Set NEEDS_VF_COUNT = new HashSet<>(); - - /** - * Actor/recipe pairs whose guard requests need the VF Module count to be incremented - * (i.e., because a module is being added). Each element is of the form - * "<actor>:<recipe>". - */ - private static final Set INCR_VF_COUNT = new HashSet<>(); - - static { - INCR_VF_COUNT.add("SO:VF Module Create"); - NEEDS_VF_COUNT.addAll(INCR_VF_COUNT); - } - - private WorkingMemory workingMemory; - private String clname; - private String actor; - private String recipe; - private String target; - private String requestId; - private Integer vfCount; - - /** - * Populated once the response has been determined, which may happen during the - * constructor or later, during {@link #run()}. - */ - private PolicyGuardResponse guardResponse; - - /** - * Guard url is grabbed from PolicyEngine manager properties. - */ - public CallGuardTask(WorkingMemory wm, String cl, String act, - String rec, String tar, String reqId, Supplier vfcnt) { - workingMemory = wm; - clname = cl; - actor = act; - recipe = rec; - requestId = reqId; - target = tar; - - vfCount = null; - - String key = act + ":" + rec; - - if (NEEDS_VF_COUNT.contains(key)) { - // this actor/recipe needs the count - get it - if ((vfCount = vfcnt.get()) == null) { - /* - * The count is missing - create an artificial Deny, which will be - * inserted into working memory when "run()" is called. - */ - guardResponse = new PolicyGuardResponse(Util.DENY, UUID.fromString(requestId), recipe); - logger.error("CallGuardTask.run missing VF Module count; requestId={}", requestId); - return; - } - - if (INCR_VF_COUNT.contains(key)) { - // this actor/recipe needs the count to be incremented - ++vfCount; - } - } - } - - @Override - public void run() { - if (guardResponse != null) { - // already have a response - just insert it - workingMemory.insert(guardResponse); - return; - } - - final long startTime = System.nanoTime(); - - PolicyGuardXacmlRequestAttributes xacmlReq = - new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId, vfCount); - - logger.debug("\n********** XACML REQUEST START ********"); - logger.debug("{}", xacmlReq); - logger.debug("********** XACML REQUEST END ********\n"); - - String guardDecision = null; - - // - // Make guard request - // - guardDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); - - logger.debug("\n********** XACML RESPONSE START ********"); - logger.debug("{}", guardDecision); - logger.debug("********** XACML RESPONSE END ********\n"); - - // - // Check if the restful call was unsuccessful or property doesn't exist - // - if (guardDecision == null) { - logger.error("********** XACML FAILED TO CONNECT ********"); - guardDecision = Util.INDETERMINATE; - } - - guardResponse = new PolicyGuardResponse(guardDecision, UUID.fromString(this.requestId), this.recipe); - - // - // Create an artificial Guard response in case we didn't get a clear Permit or Deny - // - if ("Indeterminate".equals(guardResponse.getResult())) { - guardResponse.setOperation(recipe); - guardResponse.setRequestId(UUID.fromString(requestId)); - } - - long estimatedTime = System.nanoTime() - startTime; - logger.debug("\n\n============ Guard inserted with decision {} !!! =========== time took: {} mili sec \n\n", - guardResponse.getResult(), (double) estimatedTime / 1000 / 1000); - workingMemory.insert(guardResponse); - - } - -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java deleted file mode 100644 index 6b11c1afa..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/GuardResult.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -public enum GuardResult { - LOCK_ACQUIRED, LOCK_DENIED, LOCK_EXCEPTION; -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java deleted file mode 100644 index 8887e00b7..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import java.util.UUID; - -public class PolicyGuardRequest { - private String actor; - private String target; - private UUID requestId; - private String operation; - - /** - * Construct an instance. - * - * @param actor the actor - * @param target the target - * @param requestId the request Id - * @param operation the operation - */ - public PolicyGuardRequest(String actor, String target, UUID requestId, String operation) { - super(); - this.actor = actor; - this.target = target; - this.requestId = requestId; - this.operation = operation; - } - - @Override - public String toString() { - return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestId=" + requestId + ", operation=" - + operation + "]"; - } - - public String getActor() { - return actor; - } - - public void setActor(String actor) { - this.actor = actor; - } - - public String getTarget() { - return target; - } - - public void setTarget(String target) { - this.target = target; - } - - public UUID getRequestId() { - return requestId; - } - - public void setRequestId(UUID requestId) { - this.requestId = requestId; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java deleted file mode 100644 index 574c50b79..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import java.util.UUID; - -public class PolicyGuardResponse { - private UUID requestId; - private String operation; - private String result; - - /** - * Create an instance. - * - * @param result the result - * @param req the request Id - * @param op the operation - */ - public PolicyGuardResponse(String result, UUID req, String op) { - this.result = result; - this.requestId = req; - this.operation = op; - } - - @Override - public String toString() { - return "PolicyGuardResponse [requestId=" + requestId + ", operation=" + operation + ", result=" + result + "]"; - } - - public UUID getRequestId() { - return requestId; - } - - public void setRequestId(UUID requestId) { - this.requestId = requestId; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java deleted file mode 100644 index d9ace1d83..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd. - * ================================================================================ - * 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.guard; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.onap.policy.models.decisions.concepts.DecisionRequest; -import org.onap.policy.models.decisions.concepts.DecisionResponse; -import org.onap.policy.rest.RestManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class PolicyGuardXacmlHelper { - private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class); - - private String url; - private String user; - private String pwd; - - /** - * Constructor. - */ - public PolicyGuardXacmlHelper() { - this.url = PolicyEngineConstants.getManager().getEnvironmentProperty("guard.url"); - this.user = PolicyEngineConstants.getManager().getEnvironmentProperty("pdpx.username"); - this.pwd = PolicyEngineConstants.getManager().getEnvironmentProperty("pdpx.password"); - } - - /** - * Call PDP. - * - * @param xacmlReq the XACML request - * @return the response - */ - public String callPdp(PolicyGuardXacmlRequestAttributes xacmlReq) { - // - // Create a request suitable for API - // - DecisionRequest decisionRequest = new DecisionRequest(); - decisionRequest.setOnapName("Policy"); - decisionRequest.setOnapComponent("Drools PDP"); - decisionRequest.setOnapInstance("usecase template"); - decisionRequest.setRequestId(UUID.randomUUID().toString()); - decisionRequest.setAction("guard"); - Map guard = new HashMap<>(); - guard.put("actor", xacmlReq.getActorId()); - guard.put("operation", xacmlReq.getOperationId()); - guard.put("target", xacmlReq.getTargetId()); - if (xacmlReq.getClnameId() != null) { - guard.put("clname", xacmlReq.getClnameId()); - } - if (xacmlReq.getVfCount() != null) { - guard.put("vfCount", Integer.toString(xacmlReq.getVfCount())); - } - Map resources = new HashMap<>(); - resources.put("guard", guard); - decisionRequest.setResource(resources); - - try { - // - // Call RESTful PDP - // - NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, this.url, decisionRequest.toString()); - String response = callRestfulPdp(decisionRequest); - NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, this.url, response); - - return response; - } catch (Exception e) { - logger.error("Exception in sending RESTful request: ", e); - } - - return Util.DENY; - } - - /** - * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. - * - * @param decisionRequest The Decision request - * @return response from guard which contains "Permit" or "Deny" - * @throws CoderException Exception when converting to/from JSON the message body - */ - private String callRestfulPdp(DecisionRequest decisionRequest) throws CoderException { - StandardCoder coder = new StandardCoder(); - - String jsonBody = coder.encode(decisionRequest); - RestManager restManager = new RestManager(); - - Map headers = new HashMap<>(); - headers.put("Accepts", "application/json"); - - logger.info("Guard Decision Request: {}", jsonBody); - - Pair httpDetails = restManager.post(url, user, pwd, headers, "application/json", jsonBody); - - if (httpDetails == null) { - logger.error("Guard rest call returned a null pair - defaulting to DENY"); - return Util.DENY; - } - - logger.info("Guard Decision REST Response {} {}", httpDetails.getLeft(), httpDetails.getRight()); - - if (httpDetails.getLeft() == 200) { - DecisionResponse decision = coder.decode(httpDetails.getRight(), DecisionResponse.class); - logger.info("Guard Decision {}", decision); - return decision.getStatus(); - } - - return Util.DENY; - } - -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java deleted file mode 100644 index c888f94c1..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import com.att.research.xacml.std.annotations.XACMLAction; -import com.att.research.xacml.std.annotations.XACMLRequest; -import com.att.research.xacml.std.annotations.XACMLResource; -import com.att.research.xacml.std.annotations.XACMLSubject; - -@XACMLRequest(ReturnPolicyIdList = true, CombinedDecision = true) -public class PolicyGuardXacmlRequestAttributes { - - @XACMLSubject(includeInResults = true, attributeId = "urn:org:onap:guard:clname:clname-id") - String clnameId; - - @XACMLSubject(includeInResults = true, attributeId = "urn:org:onap:guard:actor:actor-id") - String actorId; - - @XACMLAction(includeInResults = true, attributeId = "urn:org:onap:guard:operation:operation-id") - String operationId; - - @XACMLResource(includeInResults = true, attributeId = "urn:org:onap:guard:target:target-id") - String targetId; - - @XACMLResource(includeInResults = true, attributeId = "urn:org:onap:guard:request:request-id") - String requestId; - - @XACMLResource(includeInResults = true, attributeId = "urn:org:onap:guard:request:vf-count") - Integer vfCount; - - /** - * Construct an instance. - * - * @param clnameId the control loop Id - * @param actorId the actor Id - * @param operationId the operation Id - * @param targetId the target Id - * @param requestId the request Id - * @param vfCount the new number of VF Modules - */ - public PolicyGuardXacmlRequestAttributes(String clnameId, String actorId, String operationId, String targetId, - String requestId, Integer vfCount) { - super(); - this.clnameId = clnameId; - this.actorId = actorId; - this.operationId = operationId; - this.targetId = targetId; - this.requestId = requestId; - this.vfCount = vfCount; - } - - @Override - public String toString() { - return "PolicyGuardXacmlRequestAttributes [actorId=" + actorId + ", operationId=" + operationId + ", targetId=" - + targetId + ", requestId=" + requestId + "]"; - } - - public String getActorId() { - return actorId; - } - - public void setActorId(String actorId) { - this.actorId = actorId; - } - - public String getOperationId() { - return operationId; - } - - public void setOperationId(String operationId) { - this.operationId = operationId; - } - - public String getTargetId() { - return targetId; - } - - public void setTargetId(String targetId) { - this.targetId = targetId; - } - - public String getRequestId() { - return requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getClnameId() { - return clnameId; - } - - public void setClnameId(String clnameId) { - this.clnameId = clnameId; - } - - public Integer getVfCount() { - return vfCount; - } - - public void setVfCount(Integer vfCount) { - this.vfCount = vfCount; - } -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java deleted file mode 100644 index 60ccce05d..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.List; -import java.util.function.Consumer; -import org.onap.policy.controlloop.policy.guard.Constraint; -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.controlloop.policy.guard.GuardPolicy; -import org.onap.policy.controlloop.policy.guard.MatchParameters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class PolicyGuardYamlToXacml { - private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class); - - private PolicyGuardYamlToXacml() { - // Construction of this static class is not allowed - } - - /** - * Convert from Yaml to Xacml. - * - * @param yamlFile the Yaml file - * @param xacmlTemplate the Xacml template - * @param xacmlPolicyOutput the Xacml output - */ - public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { - fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput, PolicyGuardYamlToXacml::generateXacmlGuard, - constraint -> { - logger.debug("num: {}", constraint.getFreq_limit_per_target()); - logger.debug("duration: {}", constraint.getTime_window()); - logger.debug("time_in_range: {}", constraint.getActive_time_range()); - }); - } - - /** - * Convert from Yaml to Xacml. - * - * @param yamlFile the Yaml file - * @param xacmlTemplate the Xacml template - * @param xacmlPolicyOutput the Xacml output - * @param generator function to generate the yaml from the xacml - * @param logConstraint function to log relevant fields of the constraint - */ - public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput, - Generator generator, Consumer logConstraint) { - - ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); - GuardPolicy guardPolicy = yamlGuardObject.getGuards().get(0); - logger.debug("clname: {}", guardPolicy.getMatch_parameters().getControlLoopName()); - logger.debug("actor: {}", guardPolicy.getMatch_parameters().getActor()); - logger.debug("recipe: {}", guardPolicy.getMatch_parameters().getRecipe()); - Constraint constraint = guardPolicy.getLimit_constraints().get(0); - logConstraint.accept(constraint); - - Path xacmlTemplatePath = Paths.get(xacmlTemplate); - String xacmlTemplateContent; - - try { - xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - - String xacmlPolicyContent = generator.apply(xacmlTemplateContent, - guardPolicy.getMatch_parameters(), constraint); - - Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); - - } catch (IOException e) { - logger.error("fromYamlToXacml threw: ", e); - } - } - - /** - * Generate a Xacml guard. - * - * @param xacmlTemplateContent the Xacml template content - * @param matchParameters the paremeters to use - * @param constraint the constraint to use - * @return the guard - */ - private static String generateXacmlGuard(String xacmlTemplateContent, MatchParameters matchParameters, - Constraint constraint) { - - xacmlTemplateContent = doCommonReplacements(xacmlTemplateContent, matchParameters, constraint); - - String targetsRegex = ""; - if (isNullOrEmptyList(matchParameters.getTargets())) { - targetsRegex = ".*"; - } else { - StringBuilder targetsRegexSb = new StringBuilder(); - boolean addBarChar = false; - for (String t : matchParameters.getTargets()) { - targetsRegexSb.append(t); - if (addBarChar) { - targetsRegexSb.append("|"); - } else { - addBarChar = true; - } - } - targetsRegex = targetsRegexSb.toString(); - } - xacmlTemplateContent = xacmlTemplateContent.replace("${targets}", targetsRegex); - - xacmlTemplateContent = xacmlTemplateContent.replace("${limit}", - constraint.getFreq_limit_per_target().toString()); - - xacmlTemplateContent = xacmlTemplateContent.replace("${twValue}", constraint.getTime_window().get("value")); - - xacmlTemplateContent = xacmlTemplateContent.replace("${twUnits}", constraint.getTime_window().get("units")); - - logger.debug(xacmlTemplateContent); - - return xacmlTemplateContent; - } - - private static String doCommonReplacements(String xacmlTemplateContent, MatchParameters matchParameters, - Constraint constraint) { - - replaceNullOrEmpty(matchParameters.getControlLoopName(), matchParameters::setControlLoopName, ".*"); - xacmlTemplateContent = xacmlTemplateContent.replace("${clname}", matchParameters.getControlLoopName()); - - replaceNullOrEmpty(matchParameters.getActor(), matchParameters::setActor, ".*"); - xacmlTemplateContent = xacmlTemplateContent.replace("${actor}", matchParameters.getActor()); - - replaceNullOrEmpty(matchParameters.getRecipe(), matchParameters::setRecipe, ".*"); - xacmlTemplateContent = xacmlTemplateContent.replace("${recipe}", matchParameters.getRecipe()); - - xacmlTemplateContent = xacmlTemplateContent.replace("${guardActiveStart}", - constraint.getActive_time_range().get("start")); - - xacmlTemplateContent = xacmlTemplateContent.replace("${guardActiveEnd}", - constraint.getActive_time_range().get("end")); - - return xacmlTemplateContent; - } - - private static void replaceNullOrEmpty(String text, Consumer replacer, String newValue) { - if (isNullOrEmpty(text)) { - replacer.accept(newValue); - } - } - - public static boolean isNullOrEmpty(String string) { - return string == null || string.trim().isEmpty(); - } - - public static boolean isNullOrEmptyList(List list) { - return list == null || list.isEmpty(); - } - - /** - * Convert from Yaml to Xacml blacklist. - * - * @param yamlFile the Yaml file - * @param xacmlTemplate the Xacml template - * @param xacmlPolicyOutput the Xacml output - */ - public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { - fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput, PolicyGuardYamlToXacml::generateXacmlGuardBlacklist, - constraint -> { - logger.debug("freq_limit_per_target: {}", constraint.getFreq_limit_per_target()); - logger.debug("time_window: {}", constraint.getTime_window()); - logger.debug("active_time_range: {}", constraint.getActive_time_range()); - }); - } - - private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters, - Constraint constraint) { - - String result = doCommonReplacements(xacmlTemplateContent, matchParameters, constraint); - - for (String target : constraint.getBlacklist()) { - result = result.replace("${blackListElement}", - "" + target - + "" + "\n\t\t\t\t\t\t\\${blackListElement}\n"); - } - - result = result.replace("\t\t\t\t\t\t\\${blackListElement}\n", ""); - - return result; - } - - @FunctionalInterface - private static interface Generator { - public String apply(String xacmlTemplateContent, MatchParameters matchParameters, - Constraint constraint); - } -} diff --git a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java b/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java deleted file mode 100644 index 717ca3f45..000000000 --- a/controlloop/common/guard/src/main/java/org/onap/policy/guard/Util.java +++ /dev/null @@ -1,149 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import org.apache.commons.io.IOUtils; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -public final class Util { - /* - * Keys for guard properties - */ - public static final String PROP_GUARD_URL = "guard.url"; - public static final String PROP_GUARD_USER = "pdpx.username"; - public static final String PROP_GUARD_PASS = "pdpx.password"; - public static final String PROP_GUARD_DISABLED = "guard.disabled"; - - /* - * Keys for eclipse link and ONAP properties - */ - public static final String ECLIPSE_LINK_KEY_URL = "javax.persistence.jdbc.url"; - public static final String ECLIPSE_LINK_KEY_USER = "javax.persistence.jdbc.user"; - public static final String ECLIPSE_LINK_KEY_PASS = "javax.persistence.jdbc.password"; - - public static final String ONAP_KEY_URL = "guard.jdbc.url"; - public static final String ONAP_KEY_USER = "sql.db.username"; - public static final String ONAP_KEY_PASS = "sql.db.password"; - - /* - * Guard responses - */ - public static final String INDETERMINATE = "Indeterminate"; - public static final String PERMIT = "Permit"; - public static final String DENY = "Deny"; - - /* - * Junit props - */ - protected static final String PU_KEY = "OperationsHistoryPU"; - protected static final String JUNITPU = "OperationsHistoryPUTest"; - - private static final Logger logger = LoggerFactory.getLogger(Util.class); - - public static class Pair { - public final A parameterA; - public final B parameterB; - - public Pair(A parameterA, B parameterB) { - this.parameterA = parameterA; - this.parameterB = parameterB; - } - } - - private Util() { - // This static class cannot be instantiated - } - - /** - * Load a Yaml file. - * - * @param testFile the Yaml file - * @return the policies - */ - public static Pair loadYaml(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(contents); - - logger.debug(contents); - - return new Pair<>((ControlLoopPolicy) obj, contents); - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - return null; - } - - /** - * Load a Yaml guard. - * - * @param testFile the Yaml file - * @return the guard - */ - public static ControlLoopGuard loadYamlGuard(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - String contents = IOUtils.toString(is, StandardCharsets.UTF_8); - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(contents); - return (ControlLoopGuard) obj; - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - return null; - } - - /** - * Sets Guard Properties. - * - *

see /guard/src/test/java/org/onap/policy/guard/UtilTest.java for setting test properties - */ - public static void setGuardEnvProps(String url, String username, String password) { - PolicyEngineConstants.getManager().setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, url); - PolicyEngineConstants.getManager().setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, username); - PolicyEngineConstants.getManager().setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, password); - } - - public static void setGuardEnvProp(String key, String value) { - PolicyEngineConstants.getManager().setEnvironmentProperty(key, value); - } - - public static String getGuardProp(String propName) { - return PolicyEngineConstants.getManager().getEnvironmentProperty(propName); - } -} diff --git a/controlloop/common/guard/src/main/resources/META-INF/persistence.xml b/controlloop/common/guard/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index cf7e28190..000000000 --- a/controlloop/common/guard/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - - org.onap.policy.guard.OperationsHistory - - - - - - - - - - - - - - diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java deleted file mode 100644 index 3a647b130..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.isNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.function.Supplier; -import org.drools.core.WorkingMemory; -import org.junit.Test; - -public class CallGuardTaskTest { - - private static final String REQ_ID = "1-2-3-4-5"; - private static final String REQ_MATCHER = "0+1-0+2-0+3-0+4-0+5"; - private static final String VF_COUNT_ACTOR = "SO"; - private static final String INCR_VF_COUNT_RECIPE = "VF Module Create"; - - /** - * Tests that "run" works, and inserts guard response into working memory. - */ - @Test - public void testRun() { - // plain - doesn't need VF module count - //doTestRun(Util.INDETERMINATE, "act", "rec", () -> null); - - // SO actor, but plain recipe - doesn't need VF module count - //doTestRun(Util.INDETERMINATE, VF_COUNT_ACTOR, "rec", () -> null); - - // plain actor, but scale-out recipe - doesn't need VF module count - //doTestRun(Util.INDETERMINATE, "act", "VF Module Create", () -> null); - - // needs VF count - //doTestRun(Util.INDETERMINATE, VF_COUNT_ACTOR, INCR_VF_COUNT_RECIPE, () -> 22); - - // needs VF count, but it's missing ==> DENY - doTestRun(Util.DENY, VF_COUNT_ACTOR, INCR_VF_COUNT_RECIPE, () -> null); - } - - private void doTestRun(String status, String actor, String recipe, Supplier vfCount) { - WorkingMemory mockWorkingSession = mock(WorkingMemory.class); - when(mockWorkingSession.insert(isNotNull())).thenReturn(null); - // Create CallGuardTask and run - CallGuardTask cgt = new CallGuardTask(mockWorkingSession, "cl", actor, recipe, "tar", REQ_ID, vfCount); - cgt.run(); - verify(mockWorkingSession).insert(argThat((Object obj) -> { - if (!(obj instanceof PolicyGuardResponse)) { - return false; - } - // Check if the inserted response is PolicyGuardResponse, is Indeterminate, - // and has same reqID - PolicyGuardResponse response = (PolicyGuardResponse) obj; - // req ID has form 00000001-0002-0003-0004-000000000005 - return status.equals(response.getResult()) && response.getRequestId().toString().matches(REQ_MATCHER); - })); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java deleted file mode 100644 index 6fe0f2b50..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 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.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -public class GuardResultTest { - - @Test - public void testGuardResult() { - assertEquals(3, GuardResult.values().length); - assertNotNull(GuardResult.LOCK_ACQUIRED); - assertNotNull(GuardResult.LOCK_DENIED); - assertNotNull(GuardResult.LOCK_EXCEPTION); - - assertEquals(GuardResult.LOCK_ACQUIRED, GuardResult.valueOf("LOCK_ACQUIRED")); - assertEquals(GuardResult.LOCK_DENIED, GuardResult.valueOf("LOCK_DENIED")); - assertEquals(GuardResult.LOCK_EXCEPTION, GuardResult.valueOf("LOCK_EXCEPTION")); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java deleted file mode 100644 index e17207634..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import com.google.common.io.Files; -import java.io.File; -import java.io.IOException; -import org.junit.Test; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.guard.Util.Pair; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -public class GuardUtilTest { - @Test - public void testLoadYamlOk() throws IOException { - File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); - tempYamlFile.deleteOnExit(); - - ControlLoopPolicy clPolicy = new ControlLoopPolicy(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - String clYamlString = clYaml.dump(clPolicy); - - SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); - - Pair result = Util.loadYaml(tempYamlFile.getCanonicalPath()); - - assertEquals(clPolicy, result.parameterA); - assertEquals(clYamlString, result.parameterB); - } - - @Test - public void testLoadYamlError() throws IOException { - File tempDir = Files.createTempDir(); - tempDir.deleteOnExit(); - - // Read from a directory forces an IO exception - assertNull(Util.loadYaml(tempDir.getCanonicalPath())); - } - - @Test - public void testLoadGuardYamlOk() throws IOException { - File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); - tempYamlFile.deleteOnExit(); - - ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - String clYamlString = clYaml.dump(clGuardPolicy); - - SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); - - ControlLoopGuard result = Util.loadYamlGuard(tempYamlFile.getCanonicalPath()); - - assertEquals(clGuardPolicy, result); - } - - @Test - public void testLoadGuardYamlError() throws IOException { - File tempDir = Files.createTempDir(); - tempDir.deleteOnExit(); - - // Read from a directory forces an IO exception - assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); - } - - @Test - public void testMisc() { - Util.setGuardEnvProp("Actor", "Judy Garland"); - assertEquals("Judy Garland", Util.getGuardProp("Actor")); - - Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto"); - - assertEquals("http://somewhere.over.the.rainbow", Util.getGuardProp(Util.PROP_GUARD_URL)); - assertEquals("Dorothy", Util.getGuardProp(Util.PROP_GUARD_USER)); - assertEquals("Toto", Util.getGuardProp(Util.PROP_GUARD_PASS)); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java deleted file mode 100644 index cdc862acb..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2019-2020 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.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.UUID; -import org.junit.Test; - -public class PolicyGuardRequestTest { - - private static final String KANSAS = "Kansas"; - private static final String GET_BACK_HOME = "GetBackHome"; - private static final String DOROTHY = "Dorothy"; - - @Test - public void testPolicyGuardRequest() { - UUID requestId = UUID.randomUUID(); - - assertNotNull(new PolicyGuardRequest(null, null, null, null)); - - PolicyGuardRequest request = new PolicyGuardRequest(DOROTHY, KANSAS, requestId, GET_BACK_HOME); - - request.setRequestId(requestId); - assertEquals(requestId, request.getRequestId()); - - request.setActor(DOROTHY); - assertEquals(DOROTHY, request.getActor()); - - request.setTarget(KANSAS); - assertEquals(KANSAS, request.getTarget()); - - request.setOperation(GET_BACK_HOME); - assertEquals(GET_BACK_HOME, request.getOperation()); - - assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java deleted file mode 100644 index 629555297..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2019-2020 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.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.UUID; -import org.junit.Test; - -public class PolicyGuardResponseTest { - - private static final String GET_BACK_HOME = "GetBackHome"; - private static final String BACK_HOME = "BackHome"; - - @Test - public void testPolicyGuardResponse() { - UUID requestId = UUID.randomUUID(); - - assertNotNull(new PolicyGuardResponse(null, null, null)); - - PolicyGuardResponse response = new PolicyGuardResponse(BACK_HOME, requestId, GET_BACK_HOME); - - response.setRequestId(requestId); - assertEquals(requestId, response.getRequestId()); - - response.setResult(BACK_HOME); - assertEquals(BACK_HOME, response.getResult()); - - response.setOperation(GET_BACK_HOME); - assertEquals(GET_BACK_HOME, response.getOperation()); - - assertEquals("PolicyGuardResponse [requestId=", response.toString().substring(0, 31)); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java deleted file mode 100644 index 47af1fbc6..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.Properties; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; -import org.onap.policy.drools.system.PolicyEngineConstants; -import org.onap.policy.drools.utils.logging.LoggerUtil; - -public class PolicyGuardXacmlHelperTest { - - private static final String TARGET = "target"; - private static final String REQUEST_ID = "requestId"; - private static final String RECIPE = "recipe"; - private static final String GUARD_URL = "guard.url"; - private static final String ACTOR = "actor"; - private static final Integer VF_COUNT = 100; - - /** - * Set up test class. - */ - @BeforeClass - public static void setupSimulator() throws Exception { - LoggerUtil.setLevel("ROOT", "INFO"); - LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); - - HttpServletServerFactoryInstance.getServerFactory().destroy(); - org.onap.policy.simulators.Util.buildGuardSim(); - - // - // Set guard properties - // - org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/policy/pdpx/v1/decision", "python", "test"); - } - - /** - * Shuts down simulator and performs 1 more test for the case where the connection fails. - */ - @AfterClass - public static void tearDownSimulator() { - HttpServletServerFactoryInstance.getServerFactory().destroy(); - - // Null/ Bad Connection Case - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, - REQUEST_ID, VF_COUNT); - String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); - assertNotNull(rawDecision); - assertEquals(Util.DENY, rawDecision); - } - - @Test - public void testSimulator() { - PolicyGuardXacmlRequestAttributes request = new PolicyGuardXacmlRequestAttributes("clname_id", "actor_id", - "operation_id", "target_id", "request_id", VF_COUNT); - String xacmlResponse = new PolicyGuardXacmlHelper().callPdp(request); - assertNotNull(xacmlResponse); - } - - @Test - /* - * Tests PolicyGuardXacmlHelper.callPdp method to determine if it returns DENY, PERMIT, or - * INDETERMINATE as expected. - */ - public void testCallPdp() { - // Deny Case - PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( - org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, - REQUEST_ID, VF_COUNT); - String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); - assertNotNull(rawDecision); - assertEquals(Util.DENY, rawDecision); - - // Permit Case - xacmlReq = new PolicyGuardXacmlRequestAttributes("clname", ACTOR, RECIPE, TARGET, REQUEST_ID, VF_COUNT); - rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); - assertNotNull(rawDecision); - assertEquals(Util.PERMIT, rawDecision); - - // Indeterminate case is in tearDown for efficiency - } - - @Test - public void testInit() { - final Properties savedEnvironment = (Properties) PolicyEngineConstants.getManager().getEnvironment().clone(); - - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, - "http://localhost:6669/pdp/api/getDecision,Dorothy"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, - "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, - "http://localhost:6969/policy/pdpx/v1/decision"); - - PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.timeout", "1000"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().remove("pdpx.password"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.username", "python"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, "///"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty("guard.disabled", ""); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().setProperty("guard.disabled", "true"); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().getEnvironment().clear(); - assertNotNull(new PolicyGuardXacmlHelper()); - - PolicyEngineConstants.getManager().setEnvironment(savedEnvironment); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java deleted file mode 100644 index 3d49d99c1..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018-2020 AT&T. 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.guard; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.UUID; -import org.junit.Test; - -public class PolicyGuardXacmlRequestAttributesTest { - - @Test - public void testPolicyGuardXacmlRequestAttributes() { - PolicyGuardXacmlRequestAttributes attributes = - new PolicyGuardXacmlRequestAttributes(null, null, null, null, null, null); - assertNotNull(attributes); - - UUID requestId = UUID.randomUUID(); - attributes.setRequestId(requestId.toString()); - assertEquals(requestId.toString(), attributes.getRequestId()); - - UUID operationId = UUID.randomUUID(); - attributes.setOperationId(operationId.toString()); - assertEquals(operationId.toString(), attributes.getOperationId()); - - UUID actorId = UUID.randomUUID(); - attributes.setActorId(actorId.toString()); - assertEquals(actorId.toString(), attributes.getActorId()); - - UUID targetId = UUID.randomUUID(); - attributes.setTargetId(targetId.toString()); - assertEquals(targetId.toString(), attributes.getTargetId()); - - attributes.setTargetId(targetId.toString()); - assertEquals(targetId.toString(), attributes.getTargetId()); - - UUID controlLoopId = UUID.randomUUID(); - attributes.setClnameId(controlLoopId.toString()); - assertEquals(controlLoopId.toString(), attributes.getClnameId()); - - attributes.setClnameId(null); - assertEquals(null, attributes.getClnameId()); - - Integer vfCount = 20; - attributes.setVfCount(vfCount); - assertEquals(vfCount, attributes.getVfCount()); - - attributes.setVfCount(null); - assertEquals(null, attributes.getVfCount()); - - assertEquals("PolicyGuardXacmlRequestAttributes [actorId=", attributes.toString().substring(0, 43)); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java deleted file mode 100644 index a8110ed04..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.controlloop.policy.guard.Constraint; -import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.controlloop.policy.guard.GuardPolicy; -import org.onap.policy.controlloop.policy.guard.MatchParameters; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -public class PolicyGuardYamlToXacmlTest { - private static final String SOME_START_TIME = "someStartTime"; - private static final String SOME_END_TIME = "someEndTime"; - private static final String HOURS = "hours"; - private static final String TARGET2 = "WickedWitchOfTheWest"; - private static final String TARGET1 = "Wizard"; - private static final String ONAPPF_FILE = "ONAPPF"; - private static final String RECIPE = "GoToOz"; - private static final String TEXT1 = "WestWitches"; - private static final String TEXT2 = "EastWitches"; - private static final String OUT_XACML = ".out.xacml"; - private ControlLoopGuard clGuard; - - /** - * Set up test cases. - */ - @Before - public void createControlLoopGuard() { - clGuard = new ControlLoopGuard(); - MatchParameters matchParameters = new MatchParameters(); - matchParameters.setControlLoopName("WizardOfOz"); - matchParameters.setActor("Dorothy"); - matchParameters.setRecipe(RECIPE); - List targets = new ArrayList<>(); - targets.add(TARGET1); - targets.add(TARGET2); - matchParameters.setTargets(targets); - GuardPolicy guardPolicy = new GuardPolicy(); - guardPolicy.setMatch_parameters(matchParameters); - Constraint limitConstraint = new Constraint(); - limitConstraint.setFreq_limit_per_target(5); - Map timeWindow = new HashMap<>(); - timeWindow.put("value", "10"); - timeWindow.put("units", HOURS); - limitConstraint.setTime_window(timeWindow); - Map activeTimeRange = new HashMap<>(); - activeTimeRange.put("start", SOME_START_TIME); - activeTimeRange.put("end", SOME_END_TIME); - limitConstraint.setActive_time_range(activeTimeRange); - LinkedList limitConstraints = new LinkedList<>(); - limitConstraints.add(limitConstraint); - guardPolicy.setLimit_constraints(limitConstraints); - LinkedList guardList = new LinkedList<>(); - guardList.add(guardPolicy); - clGuard.setGuards(guardList); - } - - @Test - public void testGenerateXacmlGuardFull() throws IOException { - File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); - tempYamlFile.deleteOnExit(); - - File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - - File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); - tempXacmlOutputFile.deleteOnExit(); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); - PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), - tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); - - String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); - - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("cl")); - assertTrue(result.contains("actor")); - assertTrue(result.contains(RECIPE)); - assertTrue(result.contains(TARGET1)); - assertTrue(result.contains(TARGET2)); - assertTrue(result.contains("10")); - assertTrue(result.contains(HOURS)); - assertTrue(result.contains(SOME_START_TIME)); - assertTrue(result.contains(SOME_END_TIME)); - } - - @Test - public void testGenerateXacmlGuardPartial() throws IOException { - final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); - tempYamlFile.deleteOnExit(); - - final File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); - - final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); - tempXacmlOutputFile.deleteOnExit(); - - MatchParameters matchParameters = clGuard.getGuards().get(0).getMatch_parameters(); - matchParameters.setControlLoopName(null); - matchParameters.setActor(null); - matchParameters.setRecipe(null); - matchParameters.setTargets(null); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); - PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), - tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); - - String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); - - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains("cl")); - assertTrue(result.contains("actor")); - assertFalse(result.contains(RECIPE)); - assertFalse(result.contains(TARGET1)); - assertFalse(result.contains(TARGET2)); - assertTrue(result.contains("10")); - assertTrue(result.contains(HOURS)); - assertTrue(result.contains(SOME_START_TIME)); - assertTrue(result.contains(SOME_END_TIME)); - } - - @Test - public void testIsNullOrEmpty() { - assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty("")); - assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(null)); - assertFalse(PolicyGuardYamlToXacml.isNullOrEmpty("hello")); - } - - @Test - public void testIsNullOrEmptyList() { - List list = new ArrayList<>(); - assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(null)); - assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); - - list.add("hello"); - assertFalse(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); - } - - @Test - public void testGenerateXacmlGuardBlacklist() throws IOException { - final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); - tempYamlFile.deleteOnExit(); - - final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); - - final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); - tempXacmlOutputFile.deleteOnExit(); - - List blacklist = new ArrayList<>(); - blacklist.add(TEXT1); - blacklist.add(TEXT2); - clGuard.getGuards().get(0).getLimit_constraints().get(0).setBlacklist(blacklist); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), - tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); - - String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains(TEXT1)); - assertTrue(result.contains(TEXT2)); - } - - @Test - public void testGenerateXacmlGuardBlacklistPartial() throws IOException { - final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); - tempYamlFile.deleteOnExit(); - - final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); - - final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); - tempXacmlOutputFile.deleteOnExit(); - - List blacklist = new ArrayList<>(); - blacklist.add(TEXT1); - blacklist.add(TEXT2); - GuardPolicy guardPolicy = clGuard.getGuards().get(0); - guardPolicy.getLimit_constraints().get(0).setBlacklist(blacklist); - - MatchParameters matchParameters = guardPolicy.getMatch_parameters(); - matchParameters.setControlLoopName(null); - matchParameters.setActor(null); - matchParameters.setRecipe(null); - matchParameters.setTargets(null); - - Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); - String clYamlString = clYaml.dump(clGuard); - - SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), - tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); - - String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); - // Assert no mote "${}" are left - assertFalse(result.contains("${")); - assertFalse(result.contains("}")); - // Assert all substitutions are made - assertTrue(result.contains(TEXT1)); - assertTrue(result.contains(TEXT2)); - } -} diff --git a/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java b/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java deleted file mode 100644 index 98c33c761..000000000 --- a/controlloop/common/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * guard - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.guard; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import org.drools.core.util.IoUtils; - -/** - * The Class TextFileUtils is class that provides useful functions for handling text files. - * Functions to read and wrtie text files to strings and strings are provided. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class SupportTextFileUtils { - - private SupportTextFileUtils() { - // do nothing - } - - /** - * Method to return the contents of a text file as a string. - * - * @param textFilePath The path to the file as a string - * @return A string containing the contents of the file - * @throws IOException on errors reading text from the file - */ - public static String getTextFileAsString(final String textFilePath) { - return IoUtils.readFileAsString(new File(textFilePath)); - } - - /** - * Method to write contents of a string to a text file. - * - * @param outString The string to write - * @param textFile The file to write the string to - * @throws IOException on errors reading text from the file - */ - public static void putStringAsFile(final String outString, final File textFile) throws IOException { - try (final FileOutputStream textFileOutputStream = new FileOutputStream(textFile)) { - textFileOutputStream.write(outString.getBytes(StandardCharsets.UTF_8)); - } - } -} diff --git a/controlloop/common/guard/src/test/resources/META-INF/persistence.xml b/controlloop/common/guard/src/test/resources/META-INF/persistence.xml deleted file mode 100644 index 8e8be4ed2..000000000 --- a/controlloop/common/guard/src/test/resources/META-INF/persistence.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - - org.onap.policy.guard.OperationsHistory - - - - - - - - - - - - - - - diff --git a/controlloop/common/guard/src/test/resources/blacklist_template.xml b/controlloop/common/guard/src/test/resources/blacklist_template.xml deleted file mode 100644 index 1563e4a7d..000000000 --- a/controlloop/common/guard/src/test/resources/blacklist_template.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - Policy for frequency limiter. - - - - - - ${clname} - - - - - - ${actor} - - - - ${recipe} - - - - - - - DENY - only if target is in black list and guard is - active. - - - - - - - - - - - - - - - ${blackListElement} - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - diff --git a/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml b/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml deleted file mode 100644 index d26432f86..000000000 --- a/controlloop/common/guard/src/test/resources/frequency_limiter_template.xml +++ /dev/null @@ -1,127 +0,0 @@ - - - - Policy for frequency limiter. - - - - - - - ${clname} - - - - - - ${actor} - - - - ${recipe} - - - - - ${targets} - - - - - - - - DENY - only if number of operations performed in - the past is larger than the limit and the Guard is active. - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - ${limit} - - - diff --git a/controlloop/common/pom.xml b/controlloop/common/pom.xml index 64f99bf64..5350d7f9e 100644 --- a/controlloop/common/pom.xml +++ b/controlloop/common/pom.xml @@ -33,17 +33,14 @@ drools-applications-common - guard coordination eventmanager rules-test controller-frankfurt - controller-usecases feature-controlloop-utils feature-controlloop-trans feature-controlloop-management feature-controlloop-frankfurt - feature-controlloop-usecases diff --git a/controlloop/common/rules-test/src/main/java/org/onap/policy/controlloop/common/rules/test/Rules.java b/controlloop/common/rules-test/src/main/java/org/onap/policy/controlloop/common/rules/test/Rules.java index 2e15895bc..62632e9d2 100644 --- a/controlloop/common/rules-test/src/main/java/org/onap/policy/controlloop/common/rules/test/Rules.java +++ b/controlloop/common/rules-test/src/main/java/org/onap/policy/controlloop/common/rules/test/Rules.java @@ -51,7 +51,6 @@ import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.controlloop.ControlLoopEvent; import org.onap.policy.controlloop.drl.legacy.ControlLoopParams; -import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager; import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager2; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.persistence.SystemPersistence; @@ -165,14 +164,6 @@ public class Rules { await(clazz.getSimpleName()).atMost(5, TimeUnit.SECONDS) .until(() -> drools.facts(controllerName, clazz).isEmpty()); } - - /* - * We can't delete this class directly; we have to wait for the rules to clean it - * up, because the rule also cleans up a number of other associated objects. - */ - Class clazz = ControlLoopEventManager.class; - await(clazz.getSimpleName()).atMost(5, TimeUnit.SECONDS) - .until(() -> drools.facts(controllerName, clazz).isEmpty()); } /** diff --git a/controlloop/m2/guard/pom.xml b/controlloop/m2/guard/pom.xml index 566761e8e..7a4993a40 100644 --- a/controlloop/m2/guard/pom.xml +++ b/controlloop/m2/guard/pom.xml @@ -37,6 +37,13 @@ ${project.version} + + org.onap.policy.models.policy-models-interactions + model-yaml + ${policy.models.version} + provided + + org.onap.policy.drools-pdp policy-core @@ -51,21 +58,74 @@ provided - - org.onap.policy.drools-applications.controlloop.common - guard - ${project.version} - - org.onap.policy.models.policy-models-interactions.model-impl guard ${policy.models.version} + + org.onap.policy.models + policy-models-decisions + ${policy.models.version} + + + + org.onap.policy.models.policy-models-interactions.model-impl + rest + ${policy.models.version} + + + + com.att.research.xacml + xacml-pdp + 1.0.2 + + + + commons-codec + commons-codec + + + commons-logging + commons-logging + + + guava + com.google.guava + + + commons-lang3 + org.apache.commons + + + jackson-databind + com.fasterxml.jackson.core + + + commons-collections + commons-collections + + + commons-lang + commons-lang + + + + + + org.onap.policy.models.policy-models-interactions + simulators + ${policy.models.version} + test + + com.h2database h2 + test diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java new file mode 100644 index 000000000..0331b7aab --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2020 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.guard; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; +import java.util.function.Supplier; +import org.drools.core.WorkingMemory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CallGuardTask implements Runnable { + + private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class); + + /** + * Actor/recipe pairs whose guard requests need a VF Module count. Each element is of + * the form "<actor>:<recipe>". + */ + private static final Set NEEDS_VF_COUNT = new HashSet<>(); + + /** + * Actor/recipe pairs whose guard requests need the VF Module count to be incremented + * (i.e., because a module is being added). Each element is of the form + * "<actor>:<recipe>". + */ + private static final Set INCR_VF_COUNT = new HashSet<>(); + + static { + INCR_VF_COUNT.add("SO:VF Module Create"); + NEEDS_VF_COUNT.addAll(INCR_VF_COUNT); + } + + private WorkingMemory workingMemory; + private String clname; + private String actor; + private String recipe; + private String target; + private String requestId; + private Integer vfCount; + + /** + * Populated once the response has been determined, which may happen during the + * constructor or later, during {@link #run()}. + */ + private PolicyGuardResponse guardResponse; + + /** + * Guard url is grabbed from PolicyEngine manager properties. + */ + public CallGuardTask(WorkingMemory wm, String cl, String act, + String rec, String tar, String reqId, Supplier vfcnt) { + workingMemory = wm; + clname = cl; + actor = act; + recipe = rec; + requestId = reqId; + target = tar; + + vfCount = null; + + String key = act + ":" + rec; + + if (NEEDS_VF_COUNT.contains(key)) { + // this actor/recipe needs the count - get it + if ((vfCount = vfcnt.get()) == null) { + /* + * The count is missing - create an artificial Deny, which will be + * inserted into working memory when "run()" is called. + */ + guardResponse = new PolicyGuardResponse(Util.DENY, UUID.fromString(requestId), recipe); + logger.error("CallGuardTask.run missing VF Module count; requestId={}", requestId); + return; + } + + if (INCR_VF_COUNT.contains(key)) { + // this actor/recipe needs the count to be incremented + ++vfCount; + } + } + } + + @Override + public void run() { + if (guardResponse != null) { + // already have a response - just insert it + workingMemory.insert(guardResponse); + return; + } + + final long startTime = System.nanoTime(); + + PolicyGuardXacmlRequestAttributes xacmlReq = + new PolicyGuardXacmlRequestAttributes(clname, actor, recipe, target, requestId, vfCount); + + logger.debug("\n********** XACML REQUEST START ********"); + logger.debug("{}", xacmlReq); + logger.debug("********** XACML REQUEST END ********\n"); + + String guardDecision = null; + + // + // Make guard request + // + guardDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + + logger.debug("\n********** XACML RESPONSE START ********"); + logger.debug("{}", guardDecision); + logger.debug("********** XACML RESPONSE END ********\n"); + + // + // Check if the restful call was unsuccessful or property doesn't exist + // + if (guardDecision == null) { + logger.error("********** XACML FAILED TO CONNECT ********"); + guardDecision = Util.INDETERMINATE; + } + + guardResponse = new PolicyGuardResponse(guardDecision, UUID.fromString(this.requestId), this.recipe); + + // + // Create an artificial Guard response in case we didn't get a clear Permit or Deny + // + if ("Indeterminate".equals(guardResponse.getResult())) { + guardResponse.setOperation(recipe); + guardResponse.setRequestId(UUID.fromString(requestId)); + } + + long estimatedTime = System.nanoTime() - startTime; + logger.debug("\n\n============ Guard inserted with decision {} !!! =========== time took: {} mili sec \n\n", + guardResponse.getResult(), (double) estimatedTime / 1000 / 1000); + workingMemory.insert(guardResponse); + + } + +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardContext.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardContext.java index d41e30cb6..75163e24e 100644 --- a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardContext.java +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardContext.java @@ -31,6 +31,7 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.drools.core.WorkingMemory; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.system.PolicyControllerConstants; @@ -48,8 +49,6 @@ import org.slf4j.LoggerFactory; public class GuardContext implements Serializable { private static final long serialVersionUID = 1L; - private static final String ECLIPSE_LINK_KEY_DRIVER = "javax.persistence.jdbc.driver"; - private static Logger logger = LoggerFactory.getLogger(GuardContext.class); // object that should be serialized @@ -158,13 +157,15 @@ public class GuardContext implements Serializable { // extract 'guard.java.persistence.jdbc.*' parameters, // which are all mandatory dbProperties = new Properties(); - setProperty(dbProperties, Util.ONAP_KEY_URL, Util.ECLIPSE_LINK_KEY_URL, sb); - setProperty(dbProperties, Util.ONAP_KEY_USER, Util.ECLIPSE_LINK_KEY_USER, sb); - setProperty(dbProperties, Util.ONAP_KEY_PASS, Util.ECLIPSE_LINK_KEY_PASS, sb); - String driver = properties.getProperty("guard." + ECLIPSE_LINK_KEY_DRIVER); + setProperty(dbProperties, Util.ONAP_KEY_URL, PersistenceUnitProperties.JDBC_URL, sb); + setProperty(dbProperties, Util.ONAP_KEY_USER, PersistenceUnitProperties.JDBC_USER, sb); + setProperty(dbProperties, Util.ONAP_KEY_PASS, PersistenceUnitProperties.JDBC_PASSWORD, sb); + String driver = properties.getProperty("guard." + PersistenceUnitProperties.JDBC_DRIVER); if (driver != null) { - dbProperties.setProperty(ECLIPSE_LINK_KEY_DRIVER, driver); + dbProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, driver); } + dbProperties.setProperty(Util.PROP_GUARD_PERSISTENCE_UNIT, + properties.getProperty(Util.PROP_GUARD_PERSISTENCE_UNIT, Util.PU_KEY)); // if there are any errors, update 'errorMessage' & disable guard queries if (sb.length() != 0) { @@ -266,7 +267,8 @@ public class GuardContext implements Serializable { propertiesMap.put("eclipselink.ddl-generation", "create-tables"); // create entity manager factory - emf = Persistence.createEntityManagerFactory("OperationsHistoryPU", propertiesMap); + String persistenceUnit = dbProperties.getProperty(Util.PROP_GUARD_PERSISTENCE_UNIT); + emf = Persistence.createEntityManagerFactory(persistenceUnit, propertiesMap); } // create and return the 'EntityManager' diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardResult.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardResult.java new file mode 100644 index 000000000..6b11c1afa --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/GuardResult.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +public enum GuardResult { + LOCK_ACQUIRED, LOCK_DENIED, LOCK_EXCEPTION; +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java new file mode 100644 index 000000000..8887e00b7 --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardRequest.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +public class PolicyGuardRequest { + private String actor; + private String target; + private UUID requestId; + private String operation; + + /** + * Construct an instance. + * + * @param actor the actor + * @param target the target + * @param requestId the request Id + * @param operation the operation + */ + public PolicyGuardRequest(String actor, String target, UUID requestId, String operation) { + super(); + this.actor = actor; + this.target = target; + this.requestId = requestId; + this.operation = operation; + } + + @Override + public String toString() { + return "PolicyGuardRequest [actor=" + actor + ", target=" + target + ", requestId=" + requestId + ", operation=" + + operation + "]"; + } + + public String getActor() { + return actor; + } + + public void setActor(String actor) { + this.actor = actor; + } + + public String getTarget() { + return target; + } + + public void setTarget(String target) { + this.target = target; + } + + public UUID getRequestId() { + return requestId; + } + + public void setRequestId(UUID requestId) { + this.requestId = requestId; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java new file mode 100644 index 000000000..574c50b79 --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardResponse.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.util.UUID; + +public class PolicyGuardResponse { + private UUID requestId; + private String operation; + private String result; + + /** + * Create an instance. + * + * @param result the result + * @param req the request Id + * @param op the operation + */ + public PolicyGuardResponse(String result, UUID req, String op) { + this.result = result; + this.requestId = req; + this.operation = op; + } + + @Override + public String toString() { + return "PolicyGuardResponse [requestId=" + requestId + ", operation=" + operation + ", result=" + result + "]"; + } + + public UUID getRequestId() { + return requestId; + } + + public void setRequestId(UUID requestId) { + this.requestId = requestId; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java new file mode 100644 index 000000000..d9ace1d83 --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd. + * ================================================================================ + * 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.guard; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.utils.NetLoggerUtil; +import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.drools.system.PolicyEngineConstants; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; +import org.onap.policy.rest.RestManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class PolicyGuardXacmlHelper { + private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class); + + private String url; + private String user; + private String pwd; + + /** + * Constructor. + */ + public PolicyGuardXacmlHelper() { + this.url = PolicyEngineConstants.getManager().getEnvironmentProperty("guard.url"); + this.user = PolicyEngineConstants.getManager().getEnvironmentProperty("pdpx.username"); + this.pwd = PolicyEngineConstants.getManager().getEnvironmentProperty("pdpx.password"); + } + + /** + * Call PDP. + * + * @param xacmlReq the XACML request + * @return the response + */ + public String callPdp(PolicyGuardXacmlRequestAttributes xacmlReq) { + // + // Create a request suitable for API + // + DecisionRequest decisionRequest = new DecisionRequest(); + decisionRequest.setOnapName("Policy"); + decisionRequest.setOnapComponent("Drools PDP"); + decisionRequest.setOnapInstance("usecase template"); + decisionRequest.setRequestId(UUID.randomUUID().toString()); + decisionRequest.setAction("guard"); + Map guard = new HashMap<>(); + guard.put("actor", xacmlReq.getActorId()); + guard.put("operation", xacmlReq.getOperationId()); + guard.put("target", xacmlReq.getTargetId()); + if (xacmlReq.getClnameId() != null) { + guard.put("clname", xacmlReq.getClnameId()); + } + if (xacmlReq.getVfCount() != null) { + guard.put("vfCount", Integer.toString(xacmlReq.getVfCount())); + } + Map resources = new HashMap<>(); + resources.put("guard", guard); + decisionRequest.setResource(resources); + + try { + // + // Call RESTful PDP + // + NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, this.url, decisionRequest.toString()); + String response = callRestfulPdp(decisionRequest); + NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, this.url, response); + + return response; + } catch (Exception e) { + logger.error("Exception in sending RESTful request: ", e); + } + + return Util.DENY; + } + + /** + * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. + * + * @param decisionRequest The Decision request + * @return response from guard which contains "Permit" or "Deny" + * @throws CoderException Exception when converting to/from JSON the message body + */ + private String callRestfulPdp(DecisionRequest decisionRequest) throws CoderException { + StandardCoder coder = new StandardCoder(); + + String jsonBody = coder.encode(decisionRequest); + RestManager restManager = new RestManager(); + + Map headers = new HashMap<>(); + headers.put("Accepts", "application/json"); + + logger.info("Guard Decision Request: {}", jsonBody); + + Pair httpDetails = restManager.post(url, user, pwd, headers, "application/json", jsonBody); + + if (httpDetails == null) { + logger.error("Guard rest call returned a null pair - defaulting to DENY"); + return Util.DENY; + } + + logger.info("Guard Decision REST Response {} {}", httpDetails.getLeft(), httpDetails.getRight()); + + if (httpDetails.getLeft() == 200) { + DecisionResponse decision = coder.decode(httpDetails.getRight(), DecisionResponse.class); + logger.info("Guard Decision {}", decision); + return decision.getStatus(); + } + + return Util.DENY; + } + +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java new file mode 100644 index 000000000..c888f94c1 --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributes.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import com.att.research.xacml.std.annotations.XACMLAction; +import com.att.research.xacml.std.annotations.XACMLRequest; +import com.att.research.xacml.std.annotations.XACMLResource; +import com.att.research.xacml.std.annotations.XACMLSubject; + +@XACMLRequest(ReturnPolicyIdList = true, CombinedDecision = true) +public class PolicyGuardXacmlRequestAttributes { + + @XACMLSubject(includeInResults = true, attributeId = "urn:org:onap:guard:clname:clname-id") + String clnameId; + + @XACMLSubject(includeInResults = true, attributeId = "urn:org:onap:guard:actor:actor-id") + String actorId; + + @XACMLAction(includeInResults = true, attributeId = "urn:org:onap:guard:operation:operation-id") + String operationId; + + @XACMLResource(includeInResults = true, attributeId = "urn:org:onap:guard:target:target-id") + String targetId; + + @XACMLResource(includeInResults = true, attributeId = "urn:org:onap:guard:request:request-id") + String requestId; + + @XACMLResource(includeInResults = true, attributeId = "urn:org:onap:guard:request:vf-count") + Integer vfCount; + + /** + * Construct an instance. + * + * @param clnameId the control loop Id + * @param actorId the actor Id + * @param operationId the operation Id + * @param targetId the target Id + * @param requestId the request Id + * @param vfCount the new number of VF Modules + */ + public PolicyGuardXacmlRequestAttributes(String clnameId, String actorId, String operationId, String targetId, + String requestId, Integer vfCount) { + super(); + this.clnameId = clnameId; + this.actorId = actorId; + this.operationId = operationId; + this.targetId = targetId; + this.requestId = requestId; + this.vfCount = vfCount; + } + + @Override + public String toString() { + return "PolicyGuardXacmlRequestAttributes [actorId=" + actorId + ", operationId=" + operationId + ", targetId=" + + targetId + ", requestId=" + requestId + "]"; + } + + public String getActorId() { + return actorId; + } + + public void setActorId(String actorId) { + this.actorId = actorId; + } + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + public String getTargetId() { + return targetId; + } + + public void setTargetId(String targetId) { + this.targetId = targetId; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getClnameId() { + return clnameId; + } + + public void setClnameId(String clnameId) { + this.clnameId = clnameId; + } + + public Integer getVfCount() { + return vfCount; + } + + public void setVfCount(Integer vfCount) { + this.vfCount = vfCount; + } +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java new file mode 100644 index 000000000..60ccce05d --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.function.Consumer; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.MatchParameters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PolicyGuardYamlToXacml { + private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class); + + private PolicyGuardYamlToXacml() { + // Construction of this static class is not allowed + } + + /** + * Convert from Yaml to Xacml. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + */ + public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { + fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput, PolicyGuardYamlToXacml::generateXacmlGuard, + constraint -> { + logger.debug("num: {}", constraint.getFreq_limit_per_target()); + logger.debug("duration: {}", constraint.getTime_window()); + logger.debug("time_in_range: {}", constraint.getActive_time_range()); + }); + } + + /** + * Convert from Yaml to Xacml. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + * @param generator function to generate the yaml from the xacml + * @param logConstraint function to log relevant fields of the constraint + */ + public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput, + Generator generator, Consumer logConstraint) { + + ControlLoopGuard yamlGuardObject = Util.loadYamlGuard(yamlFile); + GuardPolicy guardPolicy = yamlGuardObject.getGuards().get(0); + logger.debug("clname: {}", guardPolicy.getMatch_parameters().getControlLoopName()); + logger.debug("actor: {}", guardPolicy.getMatch_parameters().getActor()); + logger.debug("recipe: {}", guardPolicy.getMatch_parameters().getRecipe()); + Constraint constraint = guardPolicy.getLimit_constraints().get(0); + logConstraint.accept(constraint); + + Path xacmlTemplatePath = Paths.get(xacmlTemplate); + String xacmlTemplateContent; + + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + + String xacmlPolicyContent = generator.apply(xacmlTemplateContent, + guardPolicy.getMatch_parameters(), constraint); + + Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes()); + + } catch (IOException e) { + logger.error("fromYamlToXacml threw: ", e); + } + } + + /** + * Generate a Xacml guard. + * + * @param xacmlTemplateContent the Xacml template content + * @param matchParameters the paremeters to use + * @param constraint the constraint to use + * @return the guard + */ + private static String generateXacmlGuard(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + + xacmlTemplateContent = doCommonReplacements(xacmlTemplateContent, matchParameters, constraint); + + String targetsRegex = ""; + if (isNullOrEmptyList(matchParameters.getTargets())) { + targetsRegex = ".*"; + } else { + StringBuilder targetsRegexSb = new StringBuilder(); + boolean addBarChar = false; + for (String t : matchParameters.getTargets()) { + targetsRegexSb.append(t); + if (addBarChar) { + targetsRegexSb.append("|"); + } else { + addBarChar = true; + } + } + targetsRegex = targetsRegexSb.toString(); + } + xacmlTemplateContent = xacmlTemplateContent.replace("${targets}", targetsRegex); + + xacmlTemplateContent = xacmlTemplateContent.replace("${limit}", + constraint.getFreq_limit_per_target().toString()); + + xacmlTemplateContent = xacmlTemplateContent.replace("${twValue}", constraint.getTime_window().get("value")); + + xacmlTemplateContent = xacmlTemplateContent.replace("${twUnits}", constraint.getTime_window().get("units")); + + logger.debug(xacmlTemplateContent); + + return xacmlTemplateContent; + } + + private static String doCommonReplacements(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + + replaceNullOrEmpty(matchParameters.getControlLoopName(), matchParameters::setControlLoopName, ".*"); + xacmlTemplateContent = xacmlTemplateContent.replace("${clname}", matchParameters.getControlLoopName()); + + replaceNullOrEmpty(matchParameters.getActor(), matchParameters::setActor, ".*"); + xacmlTemplateContent = xacmlTemplateContent.replace("${actor}", matchParameters.getActor()); + + replaceNullOrEmpty(matchParameters.getRecipe(), matchParameters::setRecipe, ".*"); + xacmlTemplateContent = xacmlTemplateContent.replace("${recipe}", matchParameters.getRecipe()); + + xacmlTemplateContent = xacmlTemplateContent.replace("${guardActiveStart}", + constraint.getActive_time_range().get("start")); + + xacmlTemplateContent = xacmlTemplateContent.replace("${guardActiveEnd}", + constraint.getActive_time_range().get("end")); + + return xacmlTemplateContent; + } + + private static void replaceNullOrEmpty(String text, Consumer replacer, String newValue) { + if (isNullOrEmpty(text)) { + replacer.accept(newValue); + } + } + + public static boolean isNullOrEmpty(String string) { + return string == null || string.trim().isEmpty(); + } + + public static boolean isNullOrEmptyList(List list) { + return list == null || list.isEmpty(); + } + + /** + * Convert from Yaml to Xacml blacklist. + * + * @param yamlFile the Yaml file + * @param xacmlTemplate the Xacml template + * @param xacmlPolicyOutput the Xacml output + */ + public static void fromYamlToXacmlBlacklist(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput) { + fromYamlToXacml(yamlFile, xacmlTemplate, xacmlPolicyOutput, PolicyGuardYamlToXacml::generateXacmlGuardBlacklist, + constraint -> { + logger.debug("freq_limit_per_target: {}", constraint.getFreq_limit_per_target()); + logger.debug("time_window: {}", constraint.getTime_window()); + logger.debug("active_time_range: {}", constraint.getActive_time_range()); + }); + } + + private static String generateXacmlGuardBlacklist(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint) { + + String result = doCommonReplacements(xacmlTemplateContent, matchParameters, constraint); + + for (String target : constraint.getBlacklist()) { + result = result.replace("${blackListElement}", + "" + target + + "" + "\n\t\t\t\t\t\t\\${blackListElement}\n"); + } + + result = result.replace("\t\t\t\t\t\t\\${blackListElement}\n", ""); + + return result; + } + + @FunctionalInterface + private static interface Generator { + public String apply(String xacmlTemplateContent, MatchParameters matchParameters, + Constraint constraint); + } +} diff --git a/controlloop/m2/guard/src/main/java/org/onap/policy/guard/Util.java b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/Util.java new file mode 100644 index 000000000..d1eed1bb4 --- /dev/null +++ b/controlloop/m2/guard/src/main/java/org/onap/policy/guard/Util.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2020 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.guard; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.apache.commons.io.IOUtils; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.drools.system.PolicyEngineConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public final class Util { + /* + * Keys for guard properties + */ + public static final String PROP_GUARD_URL = "guard.url"; + public static final String PROP_GUARD_USER = "pdpx.username"; + public static final String PROP_GUARD_PASS = "pdpx.password"; + public static final String PROP_GUARD_DISABLED = "guard.disabled"; + public static final String PROP_GUARD_PERSISTENCE_UNIT = "guard.persistenceUnit"; + + /* + * Keys for ONAP properties + */ + public static final String ONAP_KEY_URL = "guard.jdbc.url"; + public static final String ONAP_KEY_USER = "sql.db.username"; + public static final String ONAP_KEY_PASS = "sql.db.password"; + + /* + * Guard responses + */ + public static final String INDETERMINATE = "Indeterminate"; + public static final String PERMIT = "Permit"; + public static final String DENY = "Deny"; + + /* + * Junit props + */ + protected static final String PU_KEY = "OperationsHistoryPU"; + protected static final String JUNITPU = "OperationsHistoryPUTest"; + + private static final Logger logger = LoggerFactory.getLogger(Util.class); + + public static class Pair { + public final A parameterA; + public final B parameterB; + + public Pair(A parameterA, B parameterB) { + this.parameterA = parameterA; + this.parameterB = parameterB; + } + } + + private Util() { + // This static class cannot be instantiated + } + + /** + * Load a Yaml file. + * + * @param testFile the Yaml file + * @return the policies + */ + public static Pair loadYaml(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(contents); + + logger.debug(contents); + + return new Pair<>((ControlLoopPolicy) obj, contents); + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + return null; + } + + /** + * Load a Yaml guard. + * + * @param testFile the Yaml file + * @return the guard + */ + public static ControlLoopGuard loadYamlGuard(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + String contents = IOUtils.toString(is, StandardCharsets.UTF_8); + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(contents); + return (ControlLoopGuard) obj; + } catch (IOException e) { + logger.error(e.getLocalizedMessage(), e); + } + return null; + } + + /** + * Sets Guard Properties. + * + *

see /guard/src/test/java/org/onap/policy/guard/UtilTest.java for setting test properties + */ + public static void setGuardEnvProps(String url, String username, String password) { + PolicyEngineConstants.getManager().setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, url); + PolicyEngineConstants.getManager().setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, username); + PolicyEngineConstants.getManager().setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, password); + } + + public static void setGuardEnvProp(String key, String value) { + PolicyEngineConstants.getManager().setEnvironmentProperty(key, value); + } + + public static String getGuardProp(String propName) { + return PolicyEngineConstants.getManager().getEnvironmentProperty(propName); + } +} diff --git a/controlloop/m2/guard/src/main/resources/META-INF/persistence.xml b/controlloop/m2/guard/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..cf7e28190 --- /dev/null +++ b/controlloop/m2/guard/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,43 @@ + + + + + + org.eclipse.persistence.jpa.PersistenceProvider + + org.onap.policy.guard.OperationsHistory + + + + + + + + + + + + + + diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java new file mode 100644 index 000000000..3a647b130 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/CallGuardTaskTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.isNotNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.function.Supplier; +import org.drools.core.WorkingMemory; +import org.junit.Test; + +public class CallGuardTaskTest { + + private static final String REQ_ID = "1-2-3-4-5"; + private static final String REQ_MATCHER = "0+1-0+2-0+3-0+4-0+5"; + private static final String VF_COUNT_ACTOR = "SO"; + private static final String INCR_VF_COUNT_RECIPE = "VF Module Create"; + + /** + * Tests that "run" works, and inserts guard response into working memory. + */ + @Test + public void testRun() { + // plain - doesn't need VF module count + //doTestRun(Util.INDETERMINATE, "act", "rec", () -> null); + + // SO actor, but plain recipe - doesn't need VF module count + //doTestRun(Util.INDETERMINATE, VF_COUNT_ACTOR, "rec", () -> null); + + // plain actor, but scale-out recipe - doesn't need VF module count + //doTestRun(Util.INDETERMINATE, "act", "VF Module Create", () -> null); + + // needs VF count + //doTestRun(Util.INDETERMINATE, VF_COUNT_ACTOR, INCR_VF_COUNT_RECIPE, () -> 22); + + // needs VF count, but it's missing ==> DENY + doTestRun(Util.DENY, VF_COUNT_ACTOR, INCR_VF_COUNT_RECIPE, () -> null); + } + + private void doTestRun(String status, String actor, String recipe, Supplier vfCount) { + WorkingMemory mockWorkingSession = mock(WorkingMemory.class); + when(mockWorkingSession.insert(isNotNull())).thenReturn(null); + // Create CallGuardTask and run + CallGuardTask cgt = new CallGuardTask(mockWorkingSession, "cl", actor, recipe, "tar", REQ_ID, vfCount); + cgt.run(); + verify(mockWorkingSession).insert(argThat((Object obj) -> { + if (!(obj instanceof PolicyGuardResponse)) { + return false; + } + // Check if the inserted response is PolicyGuardResponse, is Indeterminate, + // and has same reqID + PolicyGuardResponse response = (PolicyGuardResponse) obj; + // req ID has form 00000001-0002-0003-0004-000000000005 + return status.equals(response.getResult()) && response.getRequestId().toString().matches(REQ_MATCHER); + })); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java index 54fd323c2..1b375cf21 100644 --- a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardContextTest.java @@ -84,11 +84,12 @@ public class GuardContextTest { @Test public void testGuardDbResponse() throws InterruptedException { Properties props = new Properties(prop); + props.setProperty(Util.PROP_GUARD_PERSISTENCE_UNIT, Util.JUNITPU); props.setProperty("guard.disabled", "false"); props.setProperty("guard.javax.persistence.jdbc.user", "user"); props.setProperty("guard.javax.persistence.jdbc.password", "secret"); props.setProperty("guard.javax.persistence.jdbc.driver", "org.h2.Driver"); - props.setProperty("guard.javax.persistence.jdbc.url", "jdbc:h2:file:./H2DB"); + props.setProperty("guard.javax.persistence.jdbc.url", "jdbc:h2:mem:testGuardDbResponse"); guardContext = new GuardContext(props); assertNotNull(guardContext); @@ -167,11 +168,12 @@ public class GuardContextTest { @Test public void testCreateDbEntry() { - Properties mockProperties = Mockito.mock(Properties.class); + Properties props = new Properties(); + props.setProperty(Util.PROP_GUARD_PERSISTENCE_UNIT, Util.JUNITPU); Instant startTime = Instant.now(); Instant endTime = Instant.now(); - guardContext = new GuardContext(mockProperties); + guardContext = new GuardContext(props); assertFalse(guardContext.createDbEntry(startTime, endTime, "testClosedLoopControlName", "testActor", "testRecipe", "testTarget", "testRequestId", "testSubRequestId", "testMessage", "testOutcome")); @@ -180,10 +182,10 @@ public class GuardContextTest { "testRecipe", "testTarget", "testRequestId", "testSubRequestId", "testMessage", "testOutcome")); PolicyEngineConstants.getManager().setEnvironmentProperty("guard.disabled", ""); - PolicyEngineConstants.getManager().setEnvironmentProperty("guard.jdbc.url", "jdbc:h2:file:./H2DB"); + PolicyEngineConstants.getManager().setEnvironmentProperty("guard.jdbc.url", "jdbc:h2:mem:testCreateDbEntry"); PolicyEngineConstants.getManager().setEnvironmentProperty("sql.db.username", "user"); PolicyEngineConstants.getManager().setEnvironmentProperty("sql.db.password", "secret"); - guardContext = new GuardContext(mockProperties); + guardContext = new GuardContext(props); assertTrue(guardContext.createDbEntry(startTime, endTime, "testClosedLoopControlName", "testActor", "testRecipe", "testTarget", "testRequestId", "testSubRequestId", "testMessage", "testOutcome")); diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java new file mode 100644 index 000000000..6fe0f2b50 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardResultTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 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.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +public class GuardResultTest { + + @Test + public void testGuardResult() { + assertEquals(3, GuardResult.values().length); + assertNotNull(GuardResult.LOCK_ACQUIRED); + assertNotNull(GuardResult.LOCK_DENIED); + assertNotNull(GuardResult.LOCK_EXCEPTION); + + assertEquals(GuardResult.LOCK_ACQUIRED, GuardResult.valueOf("LOCK_ACQUIRED")); + assertEquals(GuardResult.LOCK_DENIED, GuardResult.valueOf("LOCK_DENIED")); + assertEquals(GuardResult.LOCK_EXCEPTION, GuardResult.valueOf("LOCK_EXCEPTION")); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java new file mode 100644 index 000000000..e17207634 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/GuardUtilTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.google.common.io.Files; +import java.io.File; +import java.io.IOException; +import org.junit.Test; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.guard.Util.Pair; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class GuardUtilTest { + @Test + public void testLoadYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + tempYamlFile.deleteOnExit(); + + ControlLoopPolicy clPolicy = new ControlLoopPolicy(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clPolicy); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + Pair result = Util.loadYaml(tempYamlFile.getCanonicalPath()); + + assertEquals(clPolicy, result.parameterA); + assertEquals(clYamlString, result.parameterB); + } + + @Test + public void testLoadYamlError() throws IOException { + File tempDir = Files.createTempDir(); + tempDir.deleteOnExit(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYaml(tempDir.getCanonicalPath())); + } + + @Test + public void testLoadGuardYamlOk() throws IOException { + File tempYamlFile = File.createTempFile("ONAPPF", "yaml"); + tempYamlFile.deleteOnExit(); + + ControlLoopGuard clGuardPolicy = new ControlLoopGuard(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + String clYamlString = clYaml.dump(clGuardPolicy); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + + ControlLoopGuard result = Util.loadYamlGuard(tempYamlFile.getCanonicalPath()); + + assertEquals(clGuardPolicy, result); + } + + @Test + public void testLoadGuardYamlError() throws IOException { + File tempDir = Files.createTempDir(); + tempDir.deleteOnExit(); + + // Read from a directory forces an IO exception + assertNull(Util.loadYamlGuard(tempDir.getCanonicalPath())); + } + + @Test + public void testMisc() { + Util.setGuardEnvProp("Actor", "Judy Garland"); + assertEquals("Judy Garland", Util.getGuardProp("Actor")); + + Util.setGuardEnvProps("http://somewhere.over.the.rainbow", "Dorothy", "Toto"); + + assertEquals("http://somewhere.over.the.rainbow", Util.getGuardProp(Util.PROP_GUARD_URL)); + assertEquals("Dorothy", Util.getGuardProp(Util.PROP_GUARD_USER)); + assertEquals("Toto", Util.getGuardProp(Util.PROP_GUARD_PASS)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java new file mode 100644 index 000000000..cdc862acb --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardRequestTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2019-2020 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.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import org.junit.Test; + +public class PolicyGuardRequestTest { + + private static final String KANSAS = "Kansas"; + private static final String GET_BACK_HOME = "GetBackHome"; + private static final String DOROTHY = "Dorothy"; + + @Test + public void testPolicyGuardRequest() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardRequest(null, null, null, null)); + + PolicyGuardRequest request = new PolicyGuardRequest(DOROTHY, KANSAS, requestId, GET_BACK_HOME); + + request.setRequestId(requestId); + assertEquals(requestId, request.getRequestId()); + + request.setActor(DOROTHY); + assertEquals(DOROTHY, request.getActor()); + + request.setTarget(KANSAS); + assertEquals(KANSAS, request.getTarget()); + + request.setOperation(GET_BACK_HOME); + assertEquals(GET_BACK_HOME, request.getOperation()); + + assertEquals("PolicyGuardRequest [actor=Dorothy", request.toString().substring(0, 33)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java new file mode 100644 index 000000000..629555297 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardResponseTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2019-2020 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.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import org.junit.Test; + +public class PolicyGuardResponseTest { + + private static final String GET_BACK_HOME = "GetBackHome"; + private static final String BACK_HOME = "BackHome"; + + @Test + public void testPolicyGuardResponse() { + UUID requestId = UUID.randomUUID(); + + assertNotNull(new PolicyGuardResponse(null, null, null)); + + PolicyGuardResponse response = new PolicyGuardResponse(BACK_HOME, requestId, GET_BACK_HOME); + + response.setRequestId(requestId); + assertEquals(requestId, response.getRequestId()); + + response.setResult(BACK_HOME); + assertEquals(BACK_HOME, response.getResult()); + + response.setOperation(GET_BACK_HOME); + assertEquals(GET_BACK_HOME, response.getOperation()); + + assertEquals("PolicyGuardResponse [requestId=", response.toString().substring(0, 31)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java new file mode 100644 index 000000000..47af1fbc6 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlHelperTest.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Properties; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; +import org.onap.policy.drools.system.PolicyEngineConstants; +import org.onap.policy.drools.utils.logging.LoggerUtil; + +public class PolicyGuardXacmlHelperTest { + + private static final String TARGET = "target"; + private static final String REQUEST_ID = "requestId"; + private static final String RECIPE = "recipe"; + private static final String GUARD_URL = "guard.url"; + private static final String ACTOR = "actor"; + private static final Integer VF_COUNT = 100; + + /** + * Set up test class. + */ + @BeforeClass + public static void setupSimulator() throws Exception { + LoggerUtil.setLevel("ROOT", "INFO"); + LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); + + HttpServletServerFactoryInstance.getServerFactory().destroy(); + org.onap.policy.simulators.Util.buildGuardSim(); + + // + // Set guard properties + // + org.onap.policy.guard.Util.setGuardEnvProps("http://localhost:6669/policy/pdpx/v1/decision", "python", "test"); + } + + /** + * Shuts down simulator and performs 1 more test for the case where the connection fails. + */ + @AfterClass + public static void tearDownSimulator() { + HttpServletServerFactoryInstance.getServerFactory().destroy(); + + // Null/ Bad Connection Case + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, + REQUEST_ID, VF_COUNT); + String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + assertNotNull(rawDecision); + assertEquals(Util.DENY, rawDecision); + } + + @Test + public void testSimulator() { + PolicyGuardXacmlRequestAttributes request = new PolicyGuardXacmlRequestAttributes("clname_id", "actor_id", + "operation_id", "target_id", "request_id", VF_COUNT); + String xacmlResponse = new PolicyGuardXacmlHelper().callPdp(request); + assertNotNull(xacmlResponse); + } + + @Test + /* + * Tests PolicyGuardXacmlHelper.callPdp method to determine if it returns DENY, PERMIT, or + * INDETERMINATE as expected. + */ + public void testCallPdp() { + // Deny Case + PolicyGuardXacmlRequestAttributes xacmlReq = new PolicyGuardXacmlRequestAttributes( + org.onap.policy.simulators.GuardSimulatorJaxRs.DENY_CLNAME, ACTOR, RECIPE, TARGET, + REQUEST_ID, VF_COUNT); + String rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + assertNotNull(rawDecision); + assertEquals(Util.DENY, rawDecision); + + // Permit Case + xacmlReq = new PolicyGuardXacmlRequestAttributes("clname", ACTOR, RECIPE, TARGET, REQUEST_ID, VF_COUNT); + rawDecision = new PolicyGuardXacmlHelper().callPdp(xacmlReq); + assertNotNull(rawDecision); + assertEquals(Util.PERMIT, rawDecision); + + // Indeterminate case is in tearDown for efficiency + } + + @Test + public void testInit() { + final Properties savedEnvironment = (Properties) PolicyEngineConstants.getManager().getEnvironment().clone(); + + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, + "http://localhost:6669/pdp/api/getDecision,Dorothy"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, + "http://localhost:6669/pdp/api/getDecision,Dorothy,Toto"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, + "http://localhost:6969/policy/pdpx/v1/decision"); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.timeout", "thisIsNotANumber"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.timeout", "1000"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().remove("pdpx.password"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("pdpx.username", "python"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty(GUARD_URL, "///"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("guard.disabled", ""); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().setProperty("guard.disabled", "true"); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().getEnvironment().clear(); + assertNotNull(new PolicyGuardXacmlHelper()); + + PolicyEngineConstants.getManager().setEnvironment(savedEnvironment); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java new file mode 100644 index 000000000..3d49d99c1 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardXacmlRequestAttributesTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Modifications Copyright (C) 2018-2020 AT&T. 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.guard; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import org.junit.Test; + +public class PolicyGuardXacmlRequestAttributesTest { + + @Test + public void testPolicyGuardXacmlRequestAttributes() { + PolicyGuardXacmlRequestAttributes attributes = + new PolicyGuardXacmlRequestAttributes(null, null, null, null, null, null); + assertNotNull(attributes); + + UUID requestId = UUID.randomUUID(); + attributes.setRequestId(requestId.toString()); + assertEquals(requestId.toString(), attributes.getRequestId()); + + UUID operationId = UUID.randomUUID(); + attributes.setOperationId(operationId.toString()); + assertEquals(operationId.toString(), attributes.getOperationId()); + + UUID actorId = UUID.randomUUID(); + attributes.setActorId(actorId.toString()); + assertEquals(actorId.toString(), attributes.getActorId()); + + UUID targetId = UUID.randomUUID(); + attributes.setTargetId(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetId()); + + attributes.setTargetId(targetId.toString()); + assertEquals(targetId.toString(), attributes.getTargetId()); + + UUID controlLoopId = UUID.randomUUID(); + attributes.setClnameId(controlLoopId.toString()); + assertEquals(controlLoopId.toString(), attributes.getClnameId()); + + attributes.setClnameId(null); + assertEquals(null, attributes.getClnameId()); + + Integer vfCount = 20; + attributes.setVfCount(vfCount); + assertEquals(vfCount, attributes.getVfCount()); + + attributes.setVfCount(null); + assertEquals(null, attributes.getVfCount()); + + assertEquals("PolicyGuardXacmlRequestAttributes [actorId=", attributes.toString().substring(0, 43)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java new file mode 100644 index 000000000..a8110ed04 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/PolicyGuardYamlToXacmlTest.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.MatchParameters; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class PolicyGuardYamlToXacmlTest { + private static final String SOME_START_TIME = "someStartTime"; + private static final String SOME_END_TIME = "someEndTime"; + private static final String HOURS = "hours"; + private static final String TARGET2 = "WickedWitchOfTheWest"; + private static final String TARGET1 = "Wizard"; + private static final String ONAPPF_FILE = "ONAPPF"; + private static final String RECIPE = "GoToOz"; + private static final String TEXT1 = "WestWitches"; + private static final String TEXT2 = "EastWitches"; + private static final String OUT_XACML = ".out.xacml"; + private ControlLoopGuard clGuard; + + /** + * Set up test cases. + */ + @Before + public void createControlLoopGuard() { + clGuard = new ControlLoopGuard(); + MatchParameters matchParameters = new MatchParameters(); + matchParameters.setControlLoopName("WizardOfOz"); + matchParameters.setActor("Dorothy"); + matchParameters.setRecipe(RECIPE); + List targets = new ArrayList<>(); + targets.add(TARGET1); + targets.add(TARGET2); + matchParameters.setTargets(targets); + GuardPolicy guardPolicy = new GuardPolicy(); + guardPolicy.setMatch_parameters(matchParameters); + Constraint limitConstraint = new Constraint(); + limitConstraint.setFreq_limit_per_target(5); + Map timeWindow = new HashMap<>(); + timeWindow.put("value", "10"); + timeWindow.put("units", HOURS); + limitConstraint.setTime_window(timeWindow); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("start", SOME_START_TIME); + activeTimeRange.put("end", SOME_END_TIME); + limitConstraint.setActive_time_range(activeTimeRange); + LinkedList limitConstraints = new LinkedList<>(); + limitConstraints.add(limitConstraint); + guardPolicy.setLimit_constraints(limitConstraints); + LinkedList guardList = new LinkedList<>(); + guardList.add(guardPolicy); + clGuard.setGuards(guardList); + } + + @Test + public void testGenerateXacmlGuardFull() throws IOException { + File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + + File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("cl")); + assertTrue(result.contains("actor")); + assertTrue(result.contains(RECIPE)); + assertTrue(result.contains(TARGET1)); + assertTrue(result.contains(TARGET2)); + assertTrue(result.contains("10")); + assertTrue(result.contains(HOURS)); + assertTrue(result.contains(SOME_START_TIME)); + assertTrue(result.contains(SOME_END_TIME)); + } + + @Test + public void testGenerateXacmlGuardPartial() throws IOException { + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + final File tempXacmlTemplateFile = new File("src/test/resources/frequency_limiter_template.xml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + MatchParameters matchParameters = clGuard.getGuards().get(0).getMatch_parameters(); + matchParameters.setControlLoopName(null); + matchParameters.setActor(null); + matchParameters.setRecipe(null); + matchParameters.setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacml(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains("cl")); + assertTrue(result.contains("actor")); + assertFalse(result.contains(RECIPE)); + assertFalse(result.contains(TARGET1)); + assertFalse(result.contains(TARGET2)); + assertTrue(result.contains("10")); + assertTrue(result.contains(HOURS)); + assertTrue(result.contains(SOME_START_TIME)); + assertTrue(result.contains(SOME_END_TIME)); + } + + @Test + public void testIsNullOrEmpty() { + assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty("")); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmpty(null)); + assertFalse(PolicyGuardYamlToXacml.isNullOrEmpty("hello")); + } + + @Test + public void testIsNullOrEmptyList() { + List list = new ArrayList<>(); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(null)); + assertTrue(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); + + list.add("hello"); + assertFalse(PolicyGuardYamlToXacml.isNullOrEmptyList(list)); + } + + @Test + public void testGenerateXacmlGuardBlacklist() throws IOException { + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + List blacklist = new ArrayList<>(); + blacklist.add(TEXT1); + blacklist.add(TEXT2); + clGuard.getGuards().get(0).getLimit_constraints().get(0).setBlacklist(blacklist); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains(TEXT1)); + assertTrue(result.contains(TEXT2)); + } + + @Test + public void testGenerateXacmlGuardBlacklistPartial() throws IOException { + final File tempYamlFile = File.createTempFile(ONAPPF_FILE, "yaml"); + tempYamlFile.deleteOnExit(); + + final File tempXacmlTemplateFile = new File("src/test/resources/blacklist_template.xml"); + + final File tempXacmlOutputFile = File.createTempFile(ONAPPF_FILE, OUT_XACML); + tempXacmlOutputFile.deleteOnExit(); + + List blacklist = new ArrayList<>(); + blacklist.add(TEXT1); + blacklist.add(TEXT2); + GuardPolicy guardPolicy = clGuard.getGuards().get(0); + guardPolicy.getLimit_constraints().get(0).setBlacklist(blacklist); + + MatchParameters matchParameters = guardPolicy.getMatch_parameters(); + matchParameters.setControlLoopName(null); + matchParameters.setActor(null); + matchParameters.setRecipe(null); + matchParameters.setTargets(null); + + Yaml clYaml = new Yaml(new Constructor(ControlLoopGuard.class)); + String clYamlString = clYaml.dump(clGuard); + + SupportTextFileUtils.putStringAsFile(clYamlString, tempYamlFile); + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist(tempYamlFile.getCanonicalPath(), + tempXacmlTemplateFile.getCanonicalPath(), tempXacmlOutputFile.getCanonicalPath()); + + String result = SupportTextFileUtils.getTextFileAsString(tempXacmlOutputFile.getCanonicalPath()); + // Assert no mote "${}" are left + assertFalse(result.contains("${")); + assertFalse(result.contains("}")); + // Assert all substitutions are made + assertTrue(result.contains(TEXT1)); + assertTrue(result.contains(TEXT2)); + } +} diff --git a/controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java new file mode 100644 index 000000000..98c33c761 --- /dev/null +++ b/controlloop/m2/guard/src/test/java/org/onap/policy/guard/SupportTextFileUtils.java @@ -0,0 +1,65 @@ +/*- + * ============LICENSE_START======================================================= + * guard + * ================================================================================ + * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.guard; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.drools.core.util.IoUtils; + +/** + * The Class TextFileUtils is class that provides useful functions for handling text files. + * Functions to read and wrtie text files to strings and strings are provided. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class SupportTextFileUtils { + + private SupportTextFileUtils() { + // do nothing + } + + /** + * Method to return the contents of a text file as a string. + * + * @param textFilePath The path to the file as a string + * @return A string containing the contents of the file + * @throws IOException on errors reading text from the file + */ + public static String getTextFileAsString(final String textFilePath) { + return IoUtils.readFileAsString(new File(textFilePath)); + } + + /** + * Method to write contents of a string to a text file. + * + * @param outString The string to write + * @param textFile The file to write the string to + * @throws IOException on errors reading text from the file + */ + public static void putStringAsFile(final String outString, final File textFile) throws IOException { + try (final FileOutputStream textFileOutputStream = new FileOutputStream(textFile)) { + textFileOutputStream.write(outString.getBytes(StandardCharsets.UTF_8)); + } + } +} diff --git a/controlloop/m2/guard/src/test/resources/META-INF/persistence.xml b/controlloop/m2/guard/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..8e8be4ed2 --- /dev/null +++ b/controlloop/m2/guard/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,43 @@ + + + + + + + org.eclipse.persistence.jpa.PersistenceProvider + + org.onap.policy.guard.OperationsHistory + + + + + + + + + + + + + + + diff --git a/controlloop/m2/guard/src/test/resources/blacklist_template.xml b/controlloop/m2/guard/src/test/resources/blacklist_template.xml new file mode 100644 index 000000000..1563e4a7d --- /dev/null +++ b/controlloop/m2/guard/src/test/resources/blacklist_template.xml @@ -0,0 +1,117 @@ + + + + Policy for frequency limiter. + + + + + + ${clname} + + + + + + ${actor} + + + + ${recipe} + + + + + + + DENY - only if target is in black list and guard is + active. + + + + + + + + + + + + + + + ${blackListElement} + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + diff --git a/controlloop/m2/guard/src/test/resources/frequency_limiter_template.xml b/controlloop/m2/guard/src/test/resources/frequency_limiter_template.xml new file mode 100644 index 000000000..d26432f86 --- /dev/null +++ b/controlloop/m2/guard/src/test/resources/frequency_limiter_template.xml @@ -0,0 +1,127 @@ + + + + Policy for frequency limiter. + + + + + + + ${clname} + + + + + + ${actor} + + + + ${recipe} + + + + + ${targets} + + + + + + + + DENY - only if number of operations performed in + the past is larger than the limit and the Guard is active. + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + ${limit} + + + diff --git a/controlloop/packages/docker-controlloop/src/main/docker/Dockerfile b/controlloop/packages/docker-controlloop/src/main/docker/Dockerfile index 8dc334f21..3e60c9597 100644 --- a/controlloop/packages/docker-controlloop/src/main/docker/Dockerfile +++ b/controlloop/packages/docker-controlloop/src/main/docker/Dockerfile @@ -12,14 +12,12 @@ RUN unzip apps-controlloop.zip && \ chmod 600 $POLICY_HOME/config/* && \ . $POLICY_HOME/etc/profile.d/env.sh && \ $POLICY_HOME/bin/features install controlloop-utils controlloop-trans controlloop-management && \ - $POLICY_HOME/bin/features install controlloop-frankfurt controlloop-usecases && \ + $POLICY_HOME/bin/features install controlloop-frankfurt && \ $POLICY_HOME/bin/features enable healthcheck distributed-locking lifecycle && \ $POLICY_HOME/bin/features enable controlloop-trans controlloop-management && \ $POLICY_HOME/bin/features enable controlloop-frankfurt && \ $POLICY_HOME/bin/deploy-artifact -l -d -s $POLICY_HOME/etc/m2/standalone-settings.xml \ -a $POLICY_HOME/features/controlloop-management/lib/feature/feature-controlloop-management-$BUILD_VERSION_APP_CL.jar && \ - $POLICY_HOME/bin/deploy-artifact -l -d -s $POLICY_HOME/etc/m2/standalone-settings.xml \ - -a $POLICY_HOME/features/controlloop-usecases/artifacts/controller-usecases-$BUILD_VERSION_APP_CL.jar && \ $POLICY_HOME/bin/deploy-artifact -l -d -s $POLICY_HOME/etc/m2/standalone-settings.xml \ -a $POLICY_HOME/features/controlloop-frankfurt/artifacts/controller-frankfurt-$BUILD_VERSION_APP_CL.jar && \ find $HOME/.m2/ -name _maven.repositories -exec rm -v {} \; && \ -- cgit 1.2.3-korg