From 8279af376b435e1d7dd118a1955c5681edf3b847 Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Wed, 29 Aug 2018 07:58:53 -0400 Subject: Fix remaining checkstyle Lots of formatting, missing javadoc, distance from use, imports must be explicit, ordering of methods. Fixed some abbreviation problems in classes and renamed JUnit tests to fix this. Issue-ID: POLICY-883 Change-Id: I8494f63d88d63c0232aca97f7bcc848816228fb1 Signed-off-by: Pamela Dragosh --- .../src/main/resources/blacklist_template.xml | 145 ++++--- .../main/resources/frequency_limiter_template.xml | 158 +++++--- .../resources/frequency_limiter_template_old.xml | 122 ++++-- .../template/demo/ControlLoopFailureTest.java | 48 ++- .../java/org/onap/policy/template/demo/Util.java | 439 +++++++++++---------- .../policy/template/demo/VCPEControlLoopTest.java | 399 ------------------- .../policy/template/demo/VDNSControlLoopTest.java | 403 ------------------- .../policy/template/demo/VFCControlLoopTest.java | 362 ----------------- .../policy/template/demo/VFWControlLoopTest.java | 427 -------------------- .../policy/template/demo/VcpeControlLoopTest.java | 407 +++++++++++++++++++ .../policy/template/demo/VdnsControlLoopTest.java | 411 +++++++++++++++++++ .../policy/template/demo/VfcControlLoopTest.java | 376 ++++++++++++++++++ .../policy/template/demo/VfwControlLoopTest.java | 435 ++++++++++++++++++++ .../src/test/resources/META-INF/persistence.xml | 39 +- 14 files changed, 2199 insertions(+), 1972 deletions(-) delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java delete mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java create mode 100644 controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java (limited to 'controlloop/templates') diff --git a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml index c27ced3ac..590b19d25 100644 --- a/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml +++ b/controlloop/templates/template.demo/src/main/resources/blacklist_template.xml @@ -18,57 +18,100 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - + + Policy for frequency limiter. + + + + - ${clname} - - + ${clname} + + - - - ${actor} - - - - ${recipe} - - - - - - - DENY - only if target is in black list and guard is active. - - - - - - - - - - - - - - - ${blackListElement} - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - + + + ${actor} + + + + ${recipe} + + + + + + + DENY - only if target is in black list and guard is + active. + + + + + + + + + + + + + + + ${blackListElement} + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + diff --git a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml index 9e44ae846..34aa1af69 100644 --- a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template.xml @@ -18,60 +18,110 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - - + + Policy for frequency limiter. + + + + + - ${clname} - - + ${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} - - + + + ${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/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml index 0bc182e71..b41fdb3f2 100644 --- a/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml +++ b/controlloop/templates/template.demo/src/main/resources/frequency_limiter_template_old.xml @@ -18,46 +18,84 @@ limitations under the License. ============LICENSE_END========================================================= --> - - Policy for frequency limiter. - - - - - ${actor} - - - - ${recipe} - - - - - - - DENY - only if number of operations performed in the past is larger than the limit and the Guard is active. - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - ${limit} - - + + Policy for frequency limiter. + + + + + ${actor} + + + + ${recipe} + + + + + + + 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/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java index 584a8e349..31b6b2e30 100644 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/ControlLoopFailureTest.java @@ -62,7 +62,7 @@ import org.slf4j.LoggerFactory; public class ControlLoopFailureTest implements TopicListener { - private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class); + private static final Logger logger = LoggerFactory.getLogger(ControlLoopFailureTest.class); private static List noopTopics; @@ -75,11 +75,14 @@ public class ControlLoopFailureTest implements TopicListener { static { /* Set environment properties */ - Util.setAAIProps(); + Util.setAaiProps(); Util.setGuardProps(); - Util.setPUProp(); + Util.setPuProp(); } + /** + * Setup simulator. + */ @BeforeClass public static void setUpSimulator() { PolicyEngine.manager.configure(new Properties()); @@ -112,7 +115,8 @@ public class ControlLoopFailureTest implements TopicListener { */ try { kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", + "../archetype-cl-amsterdam/src/main/resources/archetype-resources" + + "/src/main/resources/__closedLoopControlName__.drl", "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml", "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE", "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); @@ -123,6 +127,9 @@ public class ControlLoopFailureTest implements TopicListener { } } + /** + * Tear down simulator. + */ @AfterClass public static void tearDownSimulator() { /* @@ -176,12 +183,12 @@ public class ControlLoopFailureTest implements TopicListener { * Simulate an onset event the policy engine will receive from DCAE to kick off processing * through the rules */ - sendEvent(pair.a, requestId, ControlLoopEventStatus.ONSET, "vnf01"); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vnf01"); /* * Send a second event requesting an action for a different target entity */ - sendEvent(pair.a, requestId2, ControlLoopEventStatus.ONSET, "vnf02"); + sendEvent(pair.first, requestId2, ControlLoopEventStatus.ONSET, "vnf02"); /* * Send a second event for a different target to ensure there are no problems with obtaining @@ -210,7 +217,7 @@ public class ControlLoopFailureTest implements TopicListener { * @param policyName name of the policy * @param policyVersion version of the policy * @return the kieSession to be used to insert facts - * @throws IOException + * @throws IOException throws IO exception */ private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, String policyName, String policyVersion) throws IOException { @@ -220,23 +227,24 @@ public class ControlLoopFailureTest implements TopicListener { */ pair = Util.loadYaml(yamlFile); assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); /* * Construct a kie session */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); /* * Retrieve the Policy Engine */ logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); logger.debug("============"); return kieSession; @@ -294,9 +302,9 @@ public class ControlLoopFailureTest implements TopicListener { assertNotNull(notification.getMessage()); assertTrue(notification.getMessage().startsWith("actor=APPC")); if (requestId.equals(notification.getRequestId())) { - sendEvent(pair.a, requestId, ControlLoopEventStatus.ABATED, "vnf01"); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED, "vnf01"); } else if (requestId2.equals(notification.getRequestId())) { - sendEvent(pair.a, requestId2, ControlLoopEventStatus.ABATED, "vnf02"); + sendEvent(pair.first, requestId2, ControlLoopEventStatus.ABATED, "vnf02"); } } else if (policyName.endsWith("EVENT.MANAGER")) { logger.debug("Rule Fired: " + notification.getPolicyName()); @@ -341,7 +349,7 @@ public class ControlLoopFailureTest implements TopicListener { * will be denied */ if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) { - sendEvent(pair.a, requestId3, ControlLoopEventStatus.ONSET, "vnf01"); + sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01"); } kieSession.insert(dmaapResponse); } @@ -354,12 +362,12 @@ public class ControlLoopFailureTest implements TopicListener { * @param policy the controlLoopName comes from the policy * @param requestID the requestId for this event * @param status could be onset or abated - * @param target, the target entity to take an action on + * @param target the target entity to take an action on */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String target) { + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String target) { VirtualControlLoopEvent event = new VirtualControlLoopEvent(); event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); + event.setRequestId(requestId); event.setTarget("generic-vnf.vnf-id"); event.setClosedLoopAlarmStart(Instant.now()); event.setAai(new HashMap<>()); diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java index b69369181..4ec51772f 100644 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/Util.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * demo * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -22,6 +22,8 @@ package org.onap.policy.template.demo; import static org.junit.Assert.fail; +import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -44,9 +46,9 @@ import org.kie.api.builder.Results; import org.kie.api.builder.model.KieModuleModel; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.controlloop.policy.ControlLoopPolicy; import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; import org.onap.policy.drools.system.PolicyEngine; import org.onap.policy.guard.PolicyGuardYamlToXacml; import org.slf4j.Logger; @@ -54,135 +56,159 @@ import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; -import com.att.research.xacml.util.XACMLProperties; public final class Util { - private static final String OPSHISTPUPROP = "OperationsHistoryPU"; - private static final Logger logger = LoggerFactory.getLogger(Util.class); - - public static class Pair { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } - - 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); - - //String ttt = ((ControlLoopPolicy)obj).policies.getFirst().payload.get("asdas"); - logger.debug(contents); - //for(Policy policy : ((ControlLoopPolicy)obj).policies){ - - return new Pair((ControlLoopPolicy) obj, contents); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - return null; - } - - 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 (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - return null; - } - - public static HttpServletServer buildAaiSim() throws InterruptedException, IOException { - return org.onap.policy.simulators.Util.buildAaiSim(); - } - - public static HttpServletServer buildSoSim() throws InterruptedException, IOException { - return org.onap.policy.simulators.Util.buildSoSim(); - } - - public static HttpServletServer buildVfcSim() throws InterruptedException, IOException { - return org.onap.policy.simulators.Util.buildVfcSim(); - } - - public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { + private static final String OPSHISTPUPROP = "OperationsHistoryPU"; + private static final Logger logger = LoggerFactory.getLogger(Util.class); + + public static class Pair { + public final A first; + public final B second; + + public Pair(A first, B second) { + this.first = first; + this.second = second; + } + } + + /** + * Load YAML. + * + * @param testFile test file to load + * @return the Pair of a policy and the yaml contents + */ + 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 (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + + /** + * Load the YAML guard policy. + * + * @param testFile the test file to load + * @return return the guard object + */ + 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 (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + return null; + } + + public static HttpServletServer buildAaiSim() throws InterruptedException, IOException { + return org.onap.policy.simulators.Util.buildAaiSim(); + } + + public static HttpServletServer buildSoSim() throws InterruptedException, IOException { + return org.onap.policy.simulators.Util.buildSoSim(); + } + + public static HttpServletServer buildVfcSim() throws InterruptedException, IOException { + return org.onap.policy.simulators.Util.buildVfcSim(); + } + + public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { return org.onap.policy.simulators.Util.buildGuardSim(); } - - private static String generatePolicy(String ruleContents, - String closedLoopControlName, - String policyScope, - String policyName, - String policyVersion, - String controlLoopYaml) { - - Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}"); - Matcher m = p.matcher(ruleContents); - ruleContents = m.replaceAll(closedLoopControlName); - - p = Pattern.compile("\\$\\{policyScope\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyScope); - - p = Pattern.compile("\\$\\{policyName\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyName); - - p = Pattern.compile("\\$\\{policyVersion\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(policyVersion); - - p = Pattern.compile("\\$\\{controlLoopYaml\\}"); - m = p.matcher(ruleContents); - ruleContents = m.replaceAll(controlLoopYaml); - - return ruleContents; - } - - public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, String policyScope, String policyName, String policyVersion, String yamlSpecification) throws IOException { - // - // Get our Drools Kie factory - // + + private static String generatePolicy(String ruleContents, + String closedLoopControlName, + String policyScope, + String policyName, + String policyVersion, + String controlLoopYaml) { + + Pattern pattern = Pattern.compile("\\$\\{closedLoopControlName\\}"); + Matcher matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(closedLoopControlName); + + pattern = Pattern.compile("\\$\\{policyScope\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(policyScope); + + pattern = Pattern.compile("\\$\\{policyName\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(policyName); + + pattern = Pattern.compile("\\$\\{policyVersion\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(policyVersion); + + pattern = Pattern.compile("\\$\\{controlLoopYaml\\}"); + matcher = pattern.matcher(ruleContents); + ruleContents = matcher.replaceAll(controlLoopYaml); + + return ruleContents; + } + + /** + * Build the container. + * + * @param droolsTemplate template + * @param closedLoopControlName control loop id + * @param policyScope policy scope + * @param policyName policy name + * @param policyVersion policy version + * @param yamlSpecification incoming yaml specification + * @return the Kie session + * @throws IOException if the container cannot be built + */ + public static KieSession buildContainer(String droolsTemplate, String closedLoopControlName, + String policyScope, String policyName, String policyVersion, + String yamlSpecification) throws IOException { + // + // Get our Drools Kie factory + // KieServices ks = KieServices.Factory.get(); - - KieModuleModel kModule = ks.newKieModuleModel(); - - logger.debug("KMODULE:" + System.lineSeparator() + kModule.toXML()); - + + KieModuleModel kieModule = ks.newKieModuleModel(); + + logger.debug("KMODULE:" + System.lineSeparator() + kieModule.toXML()); + // // Generate our drools rule from our template // KieFileSystem kfs = ks.newKieFileSystem(); - - kfs.writeKModuleXML(kModule.toXML()); + + kfs.writeKModuleXML(kieModule.toXML()); { - Path rule = Paths.get(droolsTemplate); - String ruleTemplate = new String(Files.readAllBytes(rule)); - String drlContents = generatePolicy(ruleTemplate, - closedLoopControlName, - policyScope, - policyName, - policyVersion, - yamlSpecification); - - kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes())); + Path rule = Paths.get(droolsTemplate); + String ruleTemplate = new String(Files.readAllBytes(rule)); + String drlContents = generatePolicy(ruleTemplate, + closedLoopControlName, + policyScope, + policyName, + policyVersion, + yamlSpecification); + + kfs.write("src/main/resources/" + policyName + ".drl", + ks.getResources().newByteArrayResource(drlContents.getBytes())); } // // Compile the rule @@ -190,95 +216,112 @@ public final class Util { KieBuilder builder = ks.newKieBuilder(kfs).buildAll(); Results results = builder.getResults(); if (results.hasMessages(Message.Level.ERROR)) { - for (Message msg : results.getMessages()) { - logger.error(msg.toString()); - } - throw new RuntimeException("Drools Rule has Errors"); + for (Message msg : results.getMessages()) { + logger.error(msg.toString()); + } + throw new RuntimeException("Drools Rule has Errors"); + } + for (Message msg : results.getMessages()) { + logger.debug(msg.toString()); } - for (Message msg : results.getMessages()) { - logger.debug(msg.toString()); - } - // - // Create our kie Session and container - // + // + // Create our kie Session and container + // ReleaseId releaseId = ks.getRepository().getDefaultReleaseId(); logger.debug(releaseId.toString()); - KieContainer kContainer = ks.newKieContainer(releaseId); - - return setupSession(kContainer.newKieSession()); - } - - private static KieSession setupSession (KieSession kieSession) { - - - // - // Create XACML Guard policy from YAML - // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm) - // - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", - "src/main/resources/frequency_limiter_template.xml", - "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml", + KieContainer keyContainer = ks.newKieContainer(releaseId); + + return setupSession(keyContainer.newKieSession()); + } + + private static KieSession setupSession(KieSession kieSession) { + + + // + // Create XACML Guard policy from YAML + // We prepare 4 Guards. Notice that Rebuilds recipe has two Guards (for checking policy combining algorithm) + // + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_restart.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_restart.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_rebuild_1.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_rebuild_1.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_migrate.yaml", + "src/main/resources/frequency_limiter_template.xml", + "src/test/resources/xacml/autogenerated_frequency_limiter_migrate.xml"); + + PolicyGuardYamlToXacml.fromYamlToXacml("src/test/resources/yaml/policy_guard_appc_modifyconfig.yaml", "src/main/resources/frequency_limiter_template.xml", "src/test/resources/xacml/autogenerated_frequency_limiter_modifyconfig.xml"); - - PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist("src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", - "src/main/resources/blacklist_template.xml", - "src/test/resources/xacml/autogenerated_blacklist.xml"); - - // - // Creating an embedded XACML PDP - // - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties"); - - return kieSession; - } - - public static void setAAIProps(){ - PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); + + PolicyGuardYamlToXacml.fromYamlToXacmlBlacklist( + "src/test/resources/yaml/policy_guard_appc_restart_blacklist.yaml", + "src/main/resources/blacklist_template.xml", + "src/test/resources/xacml/autogenerated_blacklist.xml"); + + // + // Creating an embedded XACML PDP + // + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml/xacml_guard.properties"); + + return kieSession; + } + + /** + * Set the A&AI properties. + */ + public static void setAaiProps() { + PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666"); PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI"); PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI"); - } - - public static void setSOProps(){ - PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667"); + } + + /** + * Set the SO properties. + */ + public static void setSoProps() { + PolicyEngine.manager.setEnvironmentProperty("so.url", "http://localhost:6667"); PolicyEngine.manager.setEnvironmentProperty("so.username", "SO"); PolicyEngine.manager.setEnvironmentProperty("so.password", "SO"); - } - - public static void setGuardProps(){ - /* - * Guard PDP-x connection Properties - */ - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, "http://localhost:6669/pdp/api/getDecision"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, "python"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, "test"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, "python"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, "test"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, "TEST"); - PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_DISABLED, "false"); } - - public static void setVFCProps() { - PolicyEngine.manager.setEnvironmentProperty("vfc.url", "http://localhost:6668"); + + /** + * Set the Guard properties. + */ + public static void setGuardProps() { + /* + * Guard PDP-x connection Properties + */ + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_URL, "http://localhost:6669/pdp/api/getDecision"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_USER, "python"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_PASS, "test"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_USER, "python"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_CLIENT_PASS, "test"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_ENV, "TEST"); + PolicyEngine.manager.setEnvironmentProperty(org.onap.policy.guard.Util.PROP_GUARD_DISABLED, "false"); + } + + /** + * Set the VFC properties. + */ + public static void setVfcProps() { + PolicyEngine.manager.setEnvironmentProperty("vfc.url", "http://localhost:6668"); PolicyEngine.manager.setEnvironmentProperty("vfc.username", "VFC"); PolicyEngine.manager.setEnvironmentProperty("vfc.password", "VFC"); - } - public static void setPUProp(){ - System.setProperty(OPSHISTPUPROP, "TestOperationsHistoryPU"); - } + } + + /** + * Set the operation history properties. + */ + public static void setPuProp() { + System.setProperty(OPSHISTPUPROP, "TestOperationsHistoryPU"); + } } diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java deleted file mode 100644 index 785be9907..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VCPEControlLoopTest.java +++ /dev/null @@ -1,399 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.appclcm.LcmRequest; -import org.onap.policy.appclcm.LcmRequestWrapper; -import org.onap.policy.appclcm.LcmResponse; -import org.onap.policy.appclcm.LcmResponseWrapper; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -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.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VCPEControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper"); - noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", - "org.onap.policy.appclcm.util.Serialization,gson"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", - "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111); - try { - Util.buildAaiSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - /* - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml", - "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE", - "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void aaiGetFailTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail", false); - - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } else if ("APPC-LCM-READ".equals(topic)) { - obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.appclcm.LcmRequestWrapper.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("APPC.LCM.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - kieSession.halt(); - } else { - assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); - kieSession.halt(); - } - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof LcmRequestWrapper) { - /* - * The request should be of type LcmRequestWrapper and the subrequestid should be 1 - */ - LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj; - LcmRequest appcRequest = dmaapRequest.getBody(); - assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1")); - assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id")); - - logger.debug("\n============ APPC received the request!!! ===========\n"); - - /* - * Simulate a success response from APPC and insert the response into the working memory - */ - LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); - LcmResponse appcResponse = new LcmResponse(appcRequest); - appcResponse.getStatus().setCode(400); - appcResponse.getStatus().setMessage("AppC success"); - dmaapResponse.setBody(appcResponse); - kieSession.insert(dmaapResponse); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName"); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfName, - boolean isEnriched) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setTargetType(ControlLoopTargetType.VNF); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", vnfName); - if (isEnriched) { - event.getAai().put("generic-vnf.in-maint", "false"); - event.getAai().put("generic-vnf.is-closed-loop-disabled", "false"); - event.getAai().put("generic-vnf.orchestration-status", "Created"); - event.getAai().put("generic-vnf.prov-status", "ACTIVE"); - event.getAai().put("generic-vnf.resource-version", "1"); - event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd"); - event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9"); - event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0"); - } - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method will dump all the facts in the working memory. - * - * @param kieSession the session containing the facts - */ - public void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: {}", kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: {}", handle); - } - } - -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java deleted file mode 100644 index 630ade8c5..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VDNSControlLoopTest.java +++ /dev/null @@ -1,403 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.onap.policy.so.SORequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VDNSControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VDNSControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setSOProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - - try { - Util.buildAaiSim(); - Util.buildSoSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - - /* - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void namedQueryFailTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error"); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void aaiGetFailTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail"); - - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail(e.getMessage()); - } - - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=SO")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("SO.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=SO")); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("error".equals(notification.getAai().get("vserver.vserver-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else { - assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); - } - kieSession.halt(); - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof SORequest) { - logger.debug("\n============ SO received the request!!! ===========\n"); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("vserver.vserver-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("vserver.vserver-name", "dfw1lb01lb01"); - event.getAai().put("vserver.is-closed-loop-disabled", "false"); - event.getAai().put("vserver.prov-status", "ACTIVE"); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, - String vserverName) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("vserver.vserver-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("vserver.vserver-name", vserverName); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method will dump all the facts in the working memory. - * - * @param kieSession the session containing the facts - */ - public void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: {}", kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: {}", handle); - } - } -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java deleted file mode 100644 index 6f11bc65c..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFCControlLoopTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * Copyright (C) 2017-2018 Intel Corp. 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -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.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.onap.policy.vfc.VFCRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -public class VFCControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VFCControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setVFCProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - - try { - Util.buildAaiSim(); - Util.buildVfcSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - /* - * - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() throws IOException { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void nullRequestTest() throws IOException { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(pair.a.getControlLoop().getControlLoopName()); - event.setRequestId(UUID.randomUUID()); - event.setClosedLoopEventClient("tca.instance00009"); - event.setTargetType(ControlLoopTargetType.VM); - event.setTarget("vserver.vserver-name"); - event.setFrom("DCAE"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap()); - event.getAai().put("vserver.vserver-name", "nullRequest"); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - kieSession.insert(event); - - kieSession.fireUntilHalt(); - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=VFC")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("VFC.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=VFC")); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else { - assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); - } - kieSession.halt(); - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof VFCRequest) { - logger.debug("\n============ VFC received the request!!! ===========\n"); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(UUID.randomUUID()); - event.setClosedLoopEventClient("tca.instance00009"); - event.setTargetType(ControlLoopTargetType.VM); - event.setTarget("vserver.vserver-name"); - event.setFrom("DCAE"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap()); - event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); - event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1"); - event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1"); - event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1"); - event.getAai().put("vserver.is-closed-loop-disabled", "false"); - event.getAai().put("vserver.prov-status", "ACTIVE"); - event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); - kieSession.insert(event); - } - - public static void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: " + kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: " + handle); - } - } - -} - diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java deleted file mode 100644 index 756fb202f..000000000 --- a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VFWControlLoopTest.java +++ /dev/null @@ -1,427 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * demo - * ================================================================================ - * 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.template.demo; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; -import java.net.URLEncoder; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; -import java.util.UUID; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.kie.api.runtime.KieSession; -import org.kie.api.runtime.rule.FactHandle; -import org.onap.policy.appc.Request; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.ResponseCode; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.http.server.HttpServletServer; -import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.policy.ControlLoopPolicy; -import org.onap.policy.drools.protocol.coders.EventProtocolCoder; -import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; -import org.onap.policy.drools.system.PolicyController; -import org.onap.policy.drools.system.PolicyEngine; -import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class VFWControlLoopTest implements TopicListener { - - private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class); - - private static List noopTopics; - - private static KieSession kieSession; - private static Util.Pair pair; - private UUID requestID; - - static { - /* Set environment properties */ - Util.setAAIProps(); - Util.setGuardProps(); - Util.setPUProp(); - LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); - } - - @BeforeClass - public static void setUpSimulator() { - PolicyEngine.manager.configure(new Properties()); - assertTrue(PolicyEngine.manager.start()); - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT"); - noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response"); - noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", - "org.onap.policy.appc.util.Serialization,gsonPretty"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", - "org.onap.policy.controlloop.VirtualControlLoopNotification"); - noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", - "org.onap.policy.controlloop.util.Serialization,gsonPretty"); - noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", - "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, - 1111); - EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", - "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111); - - try { - Util.buildAaiSim(); - Util.buildGuardSim(); - } catch (Exception e) { - fail(e.getMessage()); - } - - /* - * Start the kie session - */ - try { - kieSession = startSession( - "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/main/resources/__closedLoopControlName__.drl", - "src/test/resources/yaml/policy_ControlLoop_vFW.yaml", - "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW", - "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); - } catch (IOException e) { - e.printStackTrace(); - logger.debug("Could not create kieSession"); - fail("Could not create kieSession"); - } - } - - @AfterClass - public static void tearDownSimulator() { - /* - * Gracefully shut down the kie session - */ - kieSession.dispose(); - - PolicyEngine.manager.stop(); - HttpServletServer.factory.destroy(); - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - } - - @Test - public void successTest() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET); - - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail("fail"); - } - - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - @Test - public void aaiFailTests() { - - /* - * Allows the PolicyEngine to callback to this object to notify that there is an event ready - * to be pulled from the queue - */ - for (TopicSink sink : noopTopics) { - assertTrue(sink.start()); - sink.register(this); - } - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "error"); - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail(e.getMessage()); - } - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - - /* - * Create a unique requestId - */ - requestID = UUID.randomUUID(); - - /* - * Simulate an onset event the policy engine will receive from DCAE to kick off processing - * through the rules - */ - - sendEvent(pair.a, requestID, ControlLoopEventStatus.ONSET, "getFail"); - - try { - kieSession.fireUntilHalt(); - } catch (Exception e) { - e.printStackTrace(); - logger.warn(e.toString()); - fail(e.getMessage()); - } - - /* - * The only fact in memory should be Params - */ - assertEquals(1, kieSession.getFactCount()); - - /* - * Print what's left in memory - */ - dumpFacts(kieSession); - } - - /** - * This method will start a kie session and instantiate the Policy Engine. - * - * @param droolsTemplate the DRL rules file - * @param yamlFile the yaml file containing the policies - * @param policyScope scope for policy - * @param policyName name of the policy - * @param policyVersion version of the policy - * @return the kieSession to be used to insert facts - * @throws IOException - */ - private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, - String policyName, String policyVersion) throws IOException { - - /* - * Load policies from yaml - */ - pair = Util.loadYaml(yamlFile); - assertNotNull(pair); - assertNotNull(pair.a); - assertNotNull(pair.a.getControlLoop()); - assertNotNull(pair.a.getControlLoop().getControlLoopName()); - assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0); - - /* - * Construct a kie session - */ - final KieSession kieSession = Util.buildContainer(droolsTemplate, pair.a.getControlLoop().getControlLoopName(), - policyScope, policyName, policyVersion, URLEncoder.encode(pair.b, "UTF-8")); - - /* - * Retrieve the Policy Engine - */ - - logger.debug("============"); - logger.debug(URLEncoder.encode(pair.b, "UTF-8")); - logger.debug("============"); - - return kieSession; - } - - /* - * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) - */ - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* - * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation - * of type active - */ - Object obj = null; - if ("POLICY-CL-MGT".equals(topic)) { - obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, - org.onap.policy.controlloop.VirtualControlLoopNotification.class); - } else if ("APPC-CL".equals(topic)) { - obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, - org.onap.policy.appc.Request.class); - } - assertNotNull(obj); - if (obj instanceof VirtualControlLoopNotification) { - VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; - String policyName = notification.getPolicyName(); - if (policyName.endsWith("EVENT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); - } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("Sending guard query")); - } else if (policyName.endsWith("GUARD.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); - } else if (policyName.endsWith("GUARD_PERMITTED")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - } else if (policyName.endsWith("OPERATION.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The operation timed out"); - fail("Operation Timed Out"); - } else if (policyName.endsWith("APPC.RESPONSE")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); - assertNotNull(notification.getMessage()); - assertTrue(notification.getMessage().startsWith("actor=APPC")); - sendEvent(pair.a, requestID, ControlLoopEventStatus.ABATED); - } else if (policyName.endsWith("EVENT.MANAGER")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - assertEquals("Target vnf-id could not be found", notification.getMessage()); - } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { - assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); - } else { - assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); - } - kieSession.halt(); - } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { - logger.debug("Rule Fired: " + notification.getPolicyName()); - kieSession.halt(); - logger.debug("The control loop timed out"); - fail("Control Loop Timed Out"); - } - } else if (obj instanceof Request) { - assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1")); - assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id")); - - logger.debug("\n============ APPC received the request!!! ===========\n"); - - /* - * Simulate a success response from APPC and insert the response into the working memory - */ - Response appcResponse = new Response((Request) obj); - appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue()); - appcResponse.getStatus().setValue("SUCCESS"); - kieSession.insert(appcResponse); - } - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID"); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method is used to simulate event messages from DCAE that start the control loop (onset - * message) or end the control loop (abatement message). - * - * @param policy the controlLoopName comes from the policy - * @param requestID the requestId for this event - * @param status could be onset or abated - */ - protected void sendEvent(ControlLoopPolicy policy, UUID requestID, ControlLoopEventStatus status, String vnfId) { - VirtualControlLoopEvent event = new VirtualControlLoopEvent(); - event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); - event.setRequestId(requestID); - event.setTarget("generic-vnf.vnf-name"); - event.setClosedLoopAlarmStart(Instant.now()); - event.setAai(new HashMap<>()); - event.getAai().put("generic-vnf.vnf-name", vnfId); - event.setClosedLoopEventStatus(status); - kieSession.insert(event); - } - - /** - * This method will dump all the facts in the working memory. - * - * @param kieSession the session containing the facts - */ - public void dumpFacts(KieSession kieSession) { - logger.debug("Fact Count: {}", kieSession.getFactCount()); - for (FactHandle handle : kieSession.getFactHandles()) { - logger.debug("FACT: {}", handle); - } - } -} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java new file mode 100644 index 000000000..c1e8e1e66 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VcpeControlLoopTest.java @@ -0,0 +1,407 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.appclcm.LcmRequest; +import org.onap.policy.appclcm.LcmRequestWrapper; +import org.onap.policy.appclcm.LcmResponse; +import org.onap.policy.appclcm.LcmResponseWrapper; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +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.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VcpeControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VcpeControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper"); + noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson", + "org.onap.policy.appclcm.util.Serialization,gson"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ", + "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111); + try { + Util.buildAaiSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + /* + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources" + + "/src/main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml", + "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE", + "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vCPEInfraVNF13", true); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void aaiGetFailTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail", false); + + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } else if ("APPC-LCM-READ".equals(topic)) { + obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.appclcm.LcmRequestWrapper.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("APPC.LCM.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + kieSession.halt(); + } else { + assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); + kieSession.halt(); + } + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof LcmRequestWrapper) { + /* + * The request should be of type LcmRequestWrapper and the subrequestid should be 1 + */ + LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj; + LcmRequest appcRequest = dmaapRequest.getBody(); + assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1")); + assertNotNull(appcRequest.getActionIdentifiers().get("vnf-id")); + + logger.debug("\n============ APPC received the request!!! ===========\n"); + + /* + * Simulate a success response from APPC and insert the response into the working memory + */ + LcmResponseWrapper dmaapResponse = new LcmResponseWrapper(); + LcmResponse appcResponse = new LcmResponse(appcRequest); + appcResponse.getStatus().setCode(400); + appcResponse.getStatus().setMessage("AppC success"); + dmaapResponse.setBody(appcResponse); + kieSession.insert(dmaapResponse); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", "testGenericVnfName"); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfName, + boolean isEnriched) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setTargetType(ControlLoopTargetType.VNF); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", vnfName); + if (isEnriched) { + event.getAai().put("generic-vnf.in-maint", "false"); + event.getAai().put("generic-vnf.is-closed-loop-disabled", "false"); + event.getAai().put("generic-vnf.orchestration-status", "Created"); + event.getAai().put("generic-vnf.prov-status", "ACTIVE"); + event.getAai().put("generic-vnf.resource-version", "1"); + event.getAai().put("generic-vnf.service-id", "e8cb8968-5411-478b-906a-f28747de72cd"); + event.getAai().put("generic-vnf.vnf-id", "63b31229-9a3a-444f-9159-04ce2dca3be9"); + event.getAai().put("generic-vnf.vnf-type", "vCPEInfraService10/vCPEInfraService10 0"); + } + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method will dump all the facts in the working memory. + * + * @param kieSession the session containing the facts + */ + public void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: {}", kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: {}", handle); + } + } + +} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java new file mode 100644 index 000000000..d1fb29e0a --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VdnsControlLoopTest.java @@ -0,0 +1,411 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.onap.policy.so.SORequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VdnsControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VdnsControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setSoProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + + try { + Util.buildAaiSim(); + Util.buildSoSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + + /* + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources/" + + "src/main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_SO-test.yaml", "type=operational", "CL_vDNS", "v2.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void namedQueryFailTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error"); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void aaiGetFailTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail"); + + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail(e.getMessage()); + } + + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO Exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=SO")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("SO.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=SO")); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("error".equals(notification.getAai().get("vserver.vserver-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else if ("getFail".equals(notification.getAai().get("vserver.vserver-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else { + assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); + } + kieSession.halt(); + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof SORequest) { + logger.debug("\n============ SO received the request!!! ===========\n"); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("vserver.vserver-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("vserver.vserver-name", "dfw1lb01lb01"); + event.getAai().put("vserver.is-closed-loop-disabled", "false"); + event.getAai().put("vserver.prov-status", "ACTIVE"); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, + String vserverName) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("vserver.vserver-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("vserver.vserver-name", vserverName); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method will dump all the facts in the working memory. + * + * @param kieSession the session containing the facts + */ + public void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: {}", kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: {}", handle); + } + } +} diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java new file mode 100644 index 000000000..449a90fe0 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfcControlLoopTest.java @@ -0,0 +1,376 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * Copyright (C) 2017-2018 Intel Corp. All rights reserved. + * Modifications 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +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.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.onap.policy.vfc.VFCRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class VfcControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VfcControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setVfcProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + + try { + Util.buildAaiSim(); + Util.buildVfcSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + /* + * + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources/" + + "src/main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_VFC.yaml", "type=operational", "CL_VoLTE", "v2.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() throws IOException { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void nullRequestTest() throws IOException { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(pair.first.getControlLoop().getControlLoopName()); + event.setRequestId(UUID.randomUUID()); + event.setClosedLoopEventClient("tca.instance00009"); + event.setTargetType(ControlLoopTargetType.VM); + event.setTarget("vserver.vserver-name"); + event.setFrom("DCAE"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap()); + event.getAai().put("vserver.vserver-name", "nullRequest"); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + kieSession.insert(event); + + kieSession.fireUntilHalt(); + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO Exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=VFC")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("VFC.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=VFC")); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("nullRequest".equals(notification.getAai().get("vserver.vserver-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else { + assertEquals(ControlLoopNotificationType.FINAL_SUCCESS, notification.getNotification()); + } + kieSession.halt(); + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof VFCRequest) { + logger.debug("\n============ VFC received the request!!! ===========\n"); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(UUID.randomUUID()); + event.setClosedLoopEventClient("tca.instance00009"); + event.setTargetType(ControlLoopTargetType.VM); + event.setTarget("vserver.vserver-name"); + event.setFrom("DCAE"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap()); + event.getAai().put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1"); + event.getAai().put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1"); + event.getAai().put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1"); + event.getAai().put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1"); + event.getAai().put("vserver.is-closed-loop-disabled", "false"); + event.getAai().put("vserver.prov-status", "ACTIVE"); + event.setClosedLoopEventStatus(ControlLoopEventStatus.ONSET); + kieSession.insert(event); + } + + /** + * Dumps the kie session facts. + * + * @param kieSession input session + */ + public static void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: " + kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: " + handle); + } + } + +} + diff --git a/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java new file mode 100644 index 000000000..b06f4c695 --- /dev/null +++ b/controlloop/templates/template.demo/src/test/java/org/onap/policy/template/demo/VfwControlLoopTest.java @@ -0,0 +1,435 @@ +/*- + * ============LICENSE_START======================================================= + * demo + * ================================================================================ + * 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.template.demo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.net.URLEncoder; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; +import java.util.UUID; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.runtime.KieSession; +import org.kie.api.runtime.rule.FactHandle; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.drools.protocol.coders.EventProtocolCoder; +import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; +import org.onap.policy.drools.system.PolicyController; +import org.onap.policy.drools.system.PolicyEngine; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class VfwControlLoopTest implements TopicListener { + + private static final Logger logger = LoggerFactory.getLogger(VfwControlLoopTest.class); + + private static List noopTopics; + + private static KieSession kieSession; + private static Util.Pair pair; + private UUID requestId; + + static { + /* Set environment properties */ + Util.setAaiProps(); + Util.setGuardProps(); + Util.setPuProp(); + LoggerUtil.setLevel(LoggerUtil.ROOT_LOGGER, "INFO"); + } + + /** + * Setup the simulator. + */ + @BeforeClass + public static void setUpSimulator() { + PolicyEngine.manager.configure(new Properties()); + assertTrue(PolicyEngine.manager.start()); + Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-CL,POLICY-CL-MGT"); + noopSinkProperties.put("noop.sink.topics.APPC-CL.events", "org.onap.policy.appc.Response"); + noopSinkProperties.put("noop.sink.topics.APPC-CL.events.custom.gson", + "org.onap.policy.appc.util.Serialization,gsonPretty"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events", + "org.onap.policy.controlloop.VirtualControlLoopNotification"); + noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson", + "org.onap.policy.controlloop.util.Serialization,gsonPretty"); + noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT", + "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null, + 1111); + EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-CL", + "org.onap.policy.appc.Request", new JsonProtocolFilter(), null, null, 1111); + + try { + Util.buildAaiSim(); + Util.buildGuardSim(); + } catch (Exception e) { + fail(e.getMessage()); + } + + /* + * Start the kie session + */ + try { + kieSession = startSession( + "../archetype-cl-amsterdam/src/main/resources/archetype-resources/src/" + + "main/resources/__closedLoopControlName__.drl", + "src/test/resources/yaml/policy_ControlLoop_vFW.yaml", + "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vFW", + "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0"); + } catch (IOException e) { + e.printStackTrace(); + logger.debug("Could not create kieSession"); + fail("Could not create kieSession"); + } + } + + /** + * Tear down the simulator. + */ + @AfterClass + public static void tearDownSimulator() { + /* + * Gracefully shut down the kie session + */ + kieSession.dispose(); + + PolicyEngine.manager.stop(); + HttpServletServer.factory.destroy(); + PolicyController.factory.shutdown(); + TopicEndpoint.manager.shutdown(); + } + + @Test + public void successTest() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET); + + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail("fail"); + } + + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + @Test + public void aaiFailTests() { + + /* + * Allows the PolicyEngine to callback to this object to notify that there is an event ready + * to be pulled from the queue + */ + for (TopicSink sink : noopTopics) { + assertTrue(sink.start()); + sink.register(this); + } + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "error"); + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail(e.getMessage()); + } + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + + /* + * Create a unique requestId + */ + requestId = UUID.randomUUID(); + + /* + * Simulate an onset event the policy engine will receive from DCAE to kick off processing + * through the rules + */ + + sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "getFail"); + + try { + kieSession.fireUntilHalt(); + } catch (Exception e) { + e.printStackTrace(); + logger.warn(e.toString()); + fail(e.getMessage()); + } + + /* + * The only fact in memory should be Params + */ + assertEquals(1, kieSession.getFactCount()); + + /* + * Print what's left in memory + */ + dumpFacts(kieSession); + } + + /** + * This method will start a kie session and instantiate the Policy Engine. + * + * @param droolsTemplate the DRL rules file + * @param yamlFile the yaml file containing the policies + * @param policyScope scope for policy + * @param policyName name of the policy + * @param policyVersion version of the policy + * @return the kieSession to be used to insert facts + * @throws IOException IO Exception + */ + private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope, + String policyName, String policyVersion) throws IOException { + + /* + * Load policies from yaml + */ + pair = Util.loadYaml(yamlFile); + assertNotNull(pair); + assertNotNull(pair.first); + assertNotNull(pair.first.getControlLoop()); + assertNotNull(pair.first.getControlLoop().getControlLoopName()); + assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0); + + /* + * Construct a kie session + */ + final KieSession kieSession = Util.buildContainer(droolsTemplate, + pair.first.getControlLoop().getControlLoopName(), + policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8")); + + /* + * Retrieve the Policy Engine + */ + + logger.debug("============"); + logger.debug(URLEncoder.encode(pair.second, "UTF-8")); + logger.debug("============"); + + return kieSession; + } + + /* + * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String) + */ + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* + * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation + * of type active + */ + Object obj = null; + if ("POLICY-CL-MGT".equals(topic)) { + obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event, + org.onap.policy.controlloop.VirtualControlLoopNotification.class); + } else if ("APPC-CL".equals(topic)) { + obj = org.onap.policy.appc.util.Serialization.gsonPretty.fromJson(event, + org.onap.policy.appc.Request.class); + } + assertNotNull(obj); + if (obj instanceof VirtualControlLoopNotification) { + VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj; + String policyName = notification.getPolicyName(); + if (policyName.endsWith("EVENT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification())); + } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("Sending guard query")); + } else if (policyName.endsWith("GUARD.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().toLowerCase().endsWith("permit")); + } else if (policyName.endsWith("GUARD_PERMITTED")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + } else if (policyName.endsWith("OPERATION.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The operation timed out"); + fail("Operation Timed Out"); + } else if (policyName.endsWith("APPC.RESPONSE")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification())); + assertNotNull(notification.getMessage()); + assertTrue(notification.getMessage().startsWith("actor=APPC")); + sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED); + } else if (policyName.endsWith("EVENT.MANAGER")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + if ("error".equals(notification.getAai().get("generic-vnf.vnf-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + assertEquals("Target vnf-id could not be found", notification.getMessage()); + } else if ("getFail".equals(notification.getAai().get("generic-vnf.vnf-name"))) { + assertEquals(ControlLoopNotificationType.FINAL_FAILURE, notification.getNotification()); + } else { + assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification())); + } + kieSession.halt(); + } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) { + logger.debug("Rule Fired: " + notification.getPolicyName()); + kieSession.halt(); + logger.debug("The control loop timed out"); + fail("Control Loop Timed Out"); + } + } else if (obj instanceof Request) { + assertTrue(((Request) obj).getCommonHeader().getSubRequestId().equals("1")); + assertNotNull(((Request) obj).getPayload().get("generic-vnf.vnf-id")); + + logger.debug("\n============ APPC received the request!!! ===========\n"); + + /* + * Simulate a success response from APPC and insert the response into the working memory + */ + Response appcResponse = new Response((Request) obj); + appcResponse.getStatus().setCode(ResponseCode.SUCCESS.getValue()); + appcResponse.getStatus().setValue("SUCCESS"); + kieSession.insert(appcResponse); + } + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", "testGenericVnfID"); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method is used to simulate event messages from DCAE that start the control loop (onset + * message) or end the control loop (abatement message). + * + * @param policy the controlLoopName comes from the policy + * @param requestID the requestId for this event + * @param status could be onset or abated + */ + protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String vnfId) { + VirtualControlLoopEvent event = new VirtualControlLoopEvent(); + event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName()); + event.setRequestId(requestId); + event.setTarget("generic-vnf.vnf-name"); + event.setClosedLoopAlarmStart(Instant.now()); + event.setAai(new HashMap<>()); + event.getAai().put("generic-vnf.vnf-name", vnfId); + event.setClosedLoopEventStatus(status); + kieSession.insert(event); + } + + /** + * This method will dump all the facts in the working memory. + * + * @param kieSession the session containing the facts + */ + public void dumpFacts(KieSession kieSession) { + logger.debug("Fact Count: {}", kieSession.getFactCount()); + for (FactHandle handle : kieSession.getFactHandles()) { + logger.debug("FACT: {}", handle); + } + } +} diff --git a/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml b/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml index ec956a274..808cef9b6 100644 --- a/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml +++ b/controlloop/templates/template.demo/src/test/resources/META-INF/persistence.xml @@ -19,23 +19,30 @@ ============LICENSE_END========================================================= --> + xmlns="http://xmlns.jcp.org/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - - - org.eclipse.persistence.jpa.PersistenceProvider - org.onap.policy.controlloop.eventmanager.OperationsHistoryDbEntry - - - - - - - - - + + + org.eclipse.persistence.jpa.PersistenceProvider + org.onap.policy.controlloop.eventmanager.OperationsHistoryDbEntry + + + + + + + + + -- cgit 1.2.3-korg