2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
 
   6  * ================================================================================
 
   7  * Licensed under the Apache License, Version 2.0 (the "License");
 
   8  * you may not use this file except in compliance with the License.
 
   9  * You may obtain a copy of the License at
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  13  * Unless required by applicable law or agreed to in writing, software
 
  14  * distributed under the License is distributed on an "AS IS" BASIS,
 
  15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  16  * See the License for the specific language governing permissions and
 
  17  * limitations under the License.
 
  18  * ============LICENSE_END=========================================================
 
  21 package org.onap.policy.template.demo.clc;
 
  23 import static org.junit.Assert.assertEquals;
 
  24 import static org.junit.Assert.assertNotNull;
 
  25 import static org.junit.Assert.assertTrue;
 
  26 import static org.junit.Assert.fail;
 
  28 import com.google.gson.Gson;
 
  30 import java.io.IOException;
 
  31 import java.lang.StringBuilder;
 
  32 import java.net.URLEncoder;
 
  33 import java.time.Instant;
 
  34 import java.util.HashMap;
 
  35 import java.util.List;
 
  36 import java.util.Properties;
 
  37 import java.util.UUID;
 
  39 import org.junit.AfterClass;
 
  40 import org.junit.BeforeClass;
 
  41 import org.junit.Test;
 
  43 import org.kie.api.runtime.KieSession;
 
  44 import org.kie.api.runtime.rule.FactHandle;
 
  46 import org.onap.policy.appclcm.LcmRequest;
 
  47 import org.onap.policy.appclcm.LcmRequestWrapper;
 
  48 import org.onap.policy.appclcm.LcmResponse;
 
  49 import org.onap.policy.appclcm.LcmResponseWrapper;
 
  50 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 
  51 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
 
  52 import org.onap.policy.common.endpoints.event.comm.TopicListener;
 
  53 import org.onap.policy.common.endpoints.event.comm.TopicSink;
 
  54 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
 
  55 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
  56 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  57 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  58 import org.onap.policy.controlloop.ControlLoopTargetType;
 
  59 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  60 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  61 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  62 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
 
  63 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
 
  64 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
 
  65 import org.onap.policy.drools.system.PolicyController;
 
  66 import org.onap.policy.drools.system.PolicyEngine;
 
  68 import org.slf4j.Logger;
 
  69 import org.slf4j.LoggerFactory;
 
  71 public class ControlLoopCoordinationTest implements TopicListener {
 
  73     private static final Logger logger = LoggerFactory.getLogger(ControlLoopCoordinationTest.class);
 
  75     private static List<? extends TopicSink> noopTopics;
 
  77     private static KieSession kieSession1;
 
  78     private static KieSession kieSession2;
 
  79     private static StringBuilder controlLoopOneName = new StringBuilder();
 
  80     private static StringBuilder controlLoopTwoName = new StringBuilder();
 
  81     private static String expectedDecision;
 
  84         /* Set environment properties */
 
  85         SupportUtil.setAaiProps();
 
  86         SupportUtil.setGuardPropsEmbedded();
 
  87         SupportUtil.setPuProp();
 
  94     public static void setUpSimulator() {
 
  95         PolicyEngine.manager.configure(new Properties());
 
  96         assertTrue(PolicyEngine.manager.start());
 
  97         Properties noopSinkProperties = new Properties();
 
  98         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
 
  99         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
 
 100         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
 
 101                 "org.onap.policy.appclcm.util.Serialization,gson");
 
 102         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
 
 103                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
 
 104         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
 
 105                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
 
 106         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
 
 108         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
 
 109                 .groupId("junit.groupId")
 
 110                 .artifactId("junit.artifactId")
 
 111                 .topic("POLICY-CL-MGT")
 
 112                 .eventClass("org.onap.policy.controlloop.VirtualControlLoopNotification")
 
 113                 .protocolFilter(new JsonProtocolFilter())
 
 114                 .modelClassLoaderHash(1111));
 
 115         EventProtocolCoder.manager.addEncoder(EventProtocolParams.builder()
 
 116                 .groupId("junit.groupId")
 
 117                 .artifactId("junit.artifactId")
 
 118                 .topic("APPC-LCM-READ")
 
 119                 .eventClass("org.onap.policy.appclcm.LcmRequestWrapper")
 
 120                 .protocolFilter(new JsonProtocolFilter())
 
 121                 .modelClassLoaderHash(1111));
 
 123             SupportUtil.buildAaiSim();
 
 124         } catch (Exception e) {
 
 125             fail(e.getMessage());
 
 129          * Start the kie sessions
 
 132             kieSession1 = startSession(
 
 134                     "src/main/resources/__closedLoopControlName__.drl",
 
 135                     "src/test/resources/yaml/policy_ControlLoop_SyntheticOne.yaml",
 
 136                     "service=ServiceDemo;resource=Res1Demo;type=operational",
 
 137                     "SyntheticControlLoopOnePolicy",
 
 138                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
 139             kieSession2 = startSession(
 
 141                     "src/main/resources/__closedLoopControlName__.drl",
 
 142                     "src/test/resources/yaml/policy_ControlLoop_SyntheticTwo.yaml",
 
 143                     "service=ServiceDemo;resource=Res1Demo;type=operational",
 
 144                     "SyntheticControlLoopTwoPolicy",
 
 145                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
 146         } catch (IOException e) {
 
 147             logger.debug("Could not create kieSession, exception {}", e.getMessage());
 
 148             fail("Could not create kieSession");
 
 153      * Tear down simulator.
 
 156     public static void tearDownSimulator() {
 
 158          * Gracefully shut down the kie session
 
 160         kieSession1.dispose();
 
 161         kieSession2.dispose();
 
 163         PolicyEngine.manager.stop();
 
 164         HttpServletServer.factory.destroy();
 
 165         PolicyController.factory.shutdown();
 
 166         TopicEndpoint.manager.shutdown();
 
 170      * Set expected decision.
 
 172      * @param ed the expected decision ("PERMIT" or "DENY")
 
 174     public void expectedDecisionIs(String ed) {
 
 175         expectedDecision = ed;
 
 176         logger.info("Expected decision is {}", ed);
 
 180      * This method is used to simulate event messages from DCAE
 
 181      * that start the control loop (onset message) or end the
 
 182      * control loop (abatement message).
 
 184      * @param controlLoopName the control loop name
 
 185      * @param requestId the requestId for this event
 
 186      * @param status could be onset or abated
 
 187      * @param target the target name
 
 188      * @param kieSession the kieSession to which this event is being sent
 
 190     protected void sendEvent(String controlLoopName,
 
 192                              ControlLoopEventStatus status,
 
 194                              KieSession kieSession) {
 
 195         logger.debug("sendEvent controlLoopName={}", controlLoopName);
 
 196         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 197         event.setClosedLoopControlName(controlLoopName);
 
 198         event.setRequestId(requestId);
 
 199         event.setTarget("generic-vnf.vnf-name");
 
 200         event.setTargetType(ControlLoopTargetType.VNF);
 
 201         event.setClosedLoopAlarmStart(Instant.now());
 
 202         event.setAai(new HashMap<>());
 
 203         event.getAai().put("generic-vnf.vnf-name", target);
 
 204         event.setClosedLoopEventStatus(status);
 
 206         Gson gson = new Gson();
 
 207         String json = gson.toJson(event);
 
 208         logger.debug("sendEvent {}", json);
 
 210         kieSession.insert(event);
 
 215      * Simulate an event by inserting into kieSession and firing rules as needed.
 
 217      * @param cles the ControlLoopEventStatus
 
 218      * @param rid the request ID
 
 219      * @param controlLoopName the control loop name
 
 220      * @param kieSession the kieSession to which this event is being sent
 
 221      * @param expectedDecision the expected decision
 
 223     protected void simulateEvent(ControlLoopEventStatus cles,
 
 225                                  String controlLoopName,
 
 227                                  KieSession kieSession,
 
 228                                  String expectedDecision) {
 
 230         // if onset, set expected decision
 
 232         if (cles == ControlLoopEventStatus.ONSET) {
 
 233             expectedDecisionIs(expectedDecision);
 
 236         // simulate sending event
 
 238         sendEvent(controlLoopName, rid, cles, target, kieSession);
 
 239         kieSession.fireUntilHalt();
 
 241         // get dump of database entries and log
 
 243         List<?> entries = SupportUtil.dumpDb();
 
 244         assertNotNull(entries);
 
 245         logger.debug("dumpDB, {} entries", entries.size());
 
 246         for (Object entry : entries) {
 
 247             logger.debug("{}", entry);
 
 252         logger.info("simulateEvent: done");
 
 256      * Simulate an onset event.
 
 258      * @param rid the request ID
 
 259      * @param controlLoopName the control loop name
 
 260      * @param kieSession the kieSession to which this event is being sent
 
 261      * @param expectedDecision the expected decision 
 
 263     public void simulateOnset(UUID rid,
 
 264                               String controlLoopName,
 
 266                               KieSession kieSession,
 
 267                               String expectedDecision) {
 
 268         simulateEvent(ControlLoopEventStatus.ONSET, rid, controlLoopName, target, kieSession, expectedDecision);
 
 272      * Simulate an abated event.
 
 274      * @param rid the request ID
 
 275      * @param controlLoopName the control loop name
 
 276      * @param kieSession the kieSession to which this event is being sent
 
 278     public void simulateAbatement(UUID rid,
 
 279                                   String controlLoopName,
 
 281                                   KieSession kieSession) {
 
 282         simulateEvent(ControlLoopEventStatus.ABATED, rid, controlLoopName, target, kieSession, null);
 
 286      * This method will start a kie session and instantiate the Policy Engine.
 
 288      * @param droolsTemplate the DRL rules file
 
 289      * @param yamlFile the yaml file containing the policies
 
 290      * @param policyScope scope for policy
 
 291      * @param policyName name of the policy
 
 292      * @param policyVersion version of the policy
 
 293      * @return the kieSession to be used to insert facts
 
 294      * @throws IOException throws IO exception
 
 296     private static KieSession startSession(StringBuilder controlLoopName,
 
 297                                            String droolsTemplate,
 
 301                                            String policyVersion) throws IOException {
 
 304          * Load policies from yaml
 
 306         SupportUtil.Pair<ControlLoopPolicy, String> pair = SupportUtil.loadYaml(yamlFile);
 
 308         assertNotNull(pair.first);
 
 309         assertNotNull(pair.first.getControlLoop());
 
 310         assertNotNull(pair.first.getControlLoop().getControlLoopName());
 
 311         assertTrue(!pair.first.getControlLoop().getControlLoopName().isEmpty());
 
 313         controlLoopName.append(pair.first.getControlLoop().getControlLoopName());
 
 314         String yamlContents = pair.second;
 
 317          * Construct a kie session
 
 319         final KieSession kieSession = SupportUtil.buildContainer(droolsTemplate, 
 
 320                                                           controlLoopName.toString(),
 
 324                                                           URLEncoder.encode(yamlContents, "UTF-8"));
 
 327          * Retrieve the Policy Engine
 
 330         logger.debug("============");
 
 331         logger.debug(URLEncoder.encode(yamlContents, "UTF-8"));
 
 332         logger.debug("============");
 
 340      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
 
 343     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
 
 345          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
 
 349         if ("POLICY-CL-MGT".equals(topic)) {
 
 350             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
 
 351                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
 
 352         } else if ("APPC-LCM-READ".equals(topic)) {
 
 353             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
 
 354                     org.onap.policy.appclcm.LcmRequestWrapper.class);
 
 357         if (obj instanceof VirtualControlLoopNotification) {
 
 358             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
 
 359             String policyName = notification.getPolicyName();
 
 360             if (policyName.endsWith("EVENT")) {
 
 361                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 362                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
 
 363             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
 
 364                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 365                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 366                 assertNotNull(notification.getMessage());
 
 367                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
 
 368             } else if (policyName.endsWith("GUARD.RESPONSE")) {
 
 369                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 370                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 371                 assertNotNull(notification.getMessage());
 
 372                 // THESE ARE THE MOST CRITICAL ASSERTS
 
 373                 // TEST IF GUARD.RESPONSE IS CORRECT
 
 374                 logger.debug("Testing whether decision was {} as expected", expectedDecision);
 
 375                 assertTrue(notification.getMessage().toUpperCase().endsWith(expectedDecision));
 
 376             } else if (policyName.endsWith("GUARD_PERMITTED")) {
 
 377                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 378                 assertEquals(ControlLoopNotificationType.OPERATION,notification.getNotification());
 
 379                 assertNotNull(notification.getMessage());
 
 380                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
 
 381             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
 
 382                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 385                 logger.debug("The operation timed out");
 
 386                 fail("Operation Timed Out");
 
 387             } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
 
 388                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 389                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
 
 390                 assertNotNull(notification.getMessage());
 
 391                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
 
 392             } else if (policyName.endsWith("EVENT.MANAGER")) {
 
 393                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 394                 if (notification.getMessage().endsWith("Closing the control loop.")
 
 395                     || notification.getMessage().equals("Waiting for abatement")) {
 
 396                     if (policyName.startsWith(controlLoopOneName.toString())) {
 
 397                         logger.debug("Halting kieSession1");
 
 399                     } else if (policyName.startsWith(controlLoopTwoName.toString())) {
 
 400                         logger.debug("Halting kieSession2");
 
 403                         fail("Unknown ControlLoop"); 
 
 406             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
 
 407                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 410                 logger.debug("The control loop timed out");
 
 411                 fail("Control Loop Timed Out");
 
 413         } else if (obj instanceof LcmRequestWrapper) {
 
 415              * The request should be of type LCMRequestWrapper and the subrequestid should be 1
 
 417             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
 
 418             LcmRequest appcRequest = dmaapRequest.getBody();
 
 419             assertEquals(appcRequest.getCommonHeader().getSubRequestId(),"1");
 
 421             logger.debug("\n============ APPC received the request!!! ===========\n");
 
 424              * Simulate a success response from APPC and insert the response into the working memory
 
 426             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
 
 427             LcmResponse appcResponse = new LcmResponse(appcRequest);
 
 428             appcResponse.getStatus().setCode(400);
 
 429             appcResponse.getStatus().setMessage("AppC success");
 
 430             dmaapResponse.setBody(appcResponse);
 
 431             kieSession1.insert(dmaapResponse);
 
 432             kieSession2.insert(dmaapResponse);
 
 437      * This method will dump all the facts in the working memory.
 
 439      * @param kieSession the session containing the facts
 
 441     public void dumpFacts(KieSession kieSession) {
 
 442         logger.debug("Fact Count: {}", kieSession.getFactCount());
 
 443         for (FactHandle handle : kieSession.getFactHandles()) {
 
 444             logger.debug("FACT: {}", handle);
 
 449      * Test that SyntheticControlLoopOne blocks SyntheticControlLoopTwo
 
 450      * is enforced correctly.
 
 453     public void testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo() throws InterruptedException {
 
 454         logger.info("Beginning testSyntheticControlLoopOneBlocksSyntheticControlLoopTwo");
 
 456          * Allows the PolicyEngine to callback to this object to
 
 457          * notify that there is an event ready to be pulled 
 
 460         for (TopicSink sink : noopTopics) {
 
 461             assertTrue(sink.start());
 
 466          * Create unique requestIds
 
 468         final UUID requestId1 = UUID.randomUUID();
 
 469         final UUID requestId2 = UUID.randomUUID();
 
 470         final UUID requestId3 = UUID.randomUUID();
 
 471         final UUID requestId4 = UUID.randomUUID();
 
 472         final UUID requestId5 = UUID.randomUUID();
 
 473         final String cl1 = controlLoopOneName.toString();
 
 474         final String cl2 = controlLoopTwoName.toString();
 
 475         final String t1 = "TARGET_1";
 
 476         final String t2 = "TARGET_2";
 
 478         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@"); 
 
 479         simulateOnset(requestId1, cl2, t1, kieSession2,"PERMIT");
 
 480         logger.info("@@@@@@@@@@ cl1 ONSET t1 @@@@@@@@@@"); 
 
 481         simulateOnset(requestId2, cl1, t1, kieSession1,"PERMIT");
 
 482         logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@"); 
 
 483         simulateAbatement(requestId1, cl2, t1, kieSession2);
 
 484         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Fail) @@@@@@@@@@"); 
 
 485         simulateOnset(requestId3, cl2, t1, kieSession2,"DENY");
 
 486         logger.info("@@@@@@@@@@ cl2 ONSET t2 (Success) @@@@@@@@@@");
 
 487         simulateOnset(requestId4, cl2, t2, kieSession2,"PERMIT");
 
 488         logger.info("@@@@@@@@@@ cl2 ABATED t2 @@@@@@@@@@"); 
 
 489         simulateAbatement(requestId4, cl2, t2, kieSession2);
 
 490         logger.info("@@@@@@@@@@ cl1 ABATED t1  @@@@@@@@@@"); 
 
 491         simulateAbatement(requestId2, cl1, t1, kieSession1);
 
 492         logger.info("@@@@@@@@@@ cl2 ONSET t1 (Success) @@@@@@@@@@"); 
 
 493         simulateOnset(requestId5, cl2, t1, kieSession2,"PERMIT");
 
 494         logger.info("@@@@@@@@@@ cl2 ABATED t1 @@@@@@@@@@"); 
 
 495         simulateAbatement(requestId5, cl2, t1, kieSession2);
 
 498          * Print what's left in memory
 
 500         dumpFacts(kieSession1);
 
 501         dumpFacts(kieSession2);