2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017-2018 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;
 
  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 java.io.IOException;
 
  29 import java.net.URLEncoder;
 
  30 import java.time.Instant;
 
  31 import java.util.HashMap;
 
  32 import java.util.List;
 
  33 import java.util.Properties;
 
  34 import java.util.UUID;
 
  36 import org.junit.AfterClass;
 
  37 import org.junit.BeforeClass;
 
  38 import org.junit.Test;
 
  39 import org.kie.api.runtime.KieSession;
 
  40 import org.kie.api.runtime.rule.FactHandle;
 
  41 import org.onap.policy.appclcm.LcmRequest;
 
  42 import org.onap.policy.appclcm.LcmRequestWrapper;
 
  43 import org.onap.policy.appclcm.LcmResponse;
 
  44 import org.onap.policy.appclcm.LcmResponseWrapper;
 
  45 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
 
  46 import org.onap.policy.common.endpoints.event.comm.TopicEndpoint;
 
  47 import org.onap.policy.common.endpoints.event.comm.TopicListener;
 
  48 import org.onap.policy.common.endpoints.event.comm.TopicSink;
 
  49 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
 
  50 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 
  51 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  52 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  53 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  54 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  55 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  56 import org.onap.policy.drools.protocol.coders.EventProtocolCoder;
 
  57 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
 
  58 import org.onap.policy.drools.system.PolicyController;
 
  59 import org.onap.policy.drools.system.PolicyEngine;
 
  60 import org.slf4j.Logger;
 
  61 import org.slf4j.LoggerFactory;
 
  63 public class ControlLoopFailureTest implements TopicListener {
 
  65     private static final Logger logger = LoggerFactory.getLogger(ControlLoopFailureTest.class);
 
  67     private static List<? extends TopicSink> noopTopics;
 
  69     private static KieSession kieSession;
 
  70     private static Util.Pair<ControlLoopPolicy, String> pair;
 
  71     private UUID requestId;
 
  72     private UUID requestId2;
 
  73     private UUID requestId3;
 
  74     private int eventCount;
 
  77         /* Set environment properties */
 
  87     public static void setUpSimulator() {
 
  88         PolicyEngine.manager.configure(new Properties());
 
  89         assertTrue(PolicyEngine.manager.start());
 
  90         Properties noopSinkProperties = new Properties();
 
  91         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, "APPC-LCM-READ,POLICY-CL-MGT");
 
  92         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events", "org.onap.policy.appclcm.LcmRequestWrapper");
 
  93         noopSinkProperties.put("noop.sink.topics.APPC-LCM-READ.events.custom.gson",
 
  94                 "org.onap.policy.appclcm.util.Serialization,gson");
 
  95         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events",
 
  96                 "org.onap.policy.controlloop.VirtualControlLoopNotification");
 
  97         noopSinkProperties.put("noop.sink.topics.POLICY-CL-MGT.events.custom.gson",
 
  98                 "org.onap.policy.controlloop.util.Serialization,gsonPretty");
 
  99         noopTopics = TopicEndpoint.manager.addTopicSinks(noopSinkProperties);
 
 101         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "POLICY-CL-MGT",
 
 102                 "org.onap.policy.controlloop.VirtualControlLoopNotification", new JsonProtocolFilter(), null, null,
 
 104         EventProtocolCoder.manager.addEncoder("junit.groupId", "junit.artifactId", "APPC-LCM-READ",
 
 105                 "org.onap.policy.appclcm.LcmRequestWrapper", new JsonProtocolFilter(), null, null, 1111);
 
 108             Util.buildGuardSim();
 
 109         } catch (Exception e) {
 
 110             fail(e.getMessage());
 
 114          * Start the kie session
 
 117             kieSession = startSession(
 
 118                     "../archetype-cl-amsterdam/src/main/resources/archetype-resources"
 
 119                     + "/src/main/resources/__closedLoopControlName__.drl",
 
 120                     "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
 
 121                     "service=ServiceDemo;resource=Res1Demo;type=operational", "CL_vCPE",
 
 122                     "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
 123         } catch (IOException e) {
 
 125             logger.debug("Could not create kieSession");
 
 126             fail("Could not create kieSession");
 
 131      * Tear down simulator.
 
 134     public static void tearDownSimulator() {
 
 136          * Gracefully shut down the kie session
 
 138         kieSession.dispose();
 
 140         PolicyEngine.manager.stop();
 
 141         HttpServletServer.factory.destroy();
 
 142         PolicyController.factory.shutdown();
 
 143         TopicEndpoint.manager.shutdown();
 
 147      * This test case tests the scenario where 3 events occur and 2 of the requests refer to the
 
 148      * same target entity while the 3rd is for another entity. The expected result is that the event
 
 149      * with the duplicate target entity will have a final success result for one of the events, and
 
 150      * a rejected message for the one that was unable to obtain the lock. The event that is
 
 151      * referring to a different target entity should be able to obtain a lock since it is a
 
 152      * different target. After processing of all events there should only be the params object left
 
 156     public void targetLockedTest() {
 
 159          * Allows the PolicyEngine to callback to this object to notify that there is an event ready
 
 160          * to be pulled from the queue
 
 162         for (TopicSink sink : noopTopics) {
 
 163             assertTrue(sink.start());
 
 168          * Create a unique requestId
 
 170         requestId = UUID.randomUUID();
 
 173          * This will be a unique request for another target entity
 
 175         requestId2 = UUID.randomUUID();
 
 178          * This will be a request duplicating the target entity of the first request
 
 180         requestId3 = UUID.randomUUID();
 
 183          * Simulate an onset event the policy engine will receive from DCAE to kick off processing
 
 186         sendEvent(pair.first, requestId, ControlLoopEventStatus.ONSET, "vnf01");
 
 189          * Send a second event requesting an action for a different target entity
 
 191         sendEvent(pair.first, requestId2, ControlLoopEventStatus.ONSET, "vnf02");
 
 194          * Send a second event for a different target to ensure there are no problems with obtaining
 
 195          * a lock for a different
 
 197         kieSession.fireUntilHalt();
 
 199         // allow object clean-up
 
 200         kieSession.fireAllRules();
 
 203          * The only fact in memory should be Params
 
 205         assertEquals(1, kieSession.getFactCount());
 
 208          * Print what's left in memory
 
 210         dumpFacts(kieSession);
 
 215      * This method will start a kie session and instantiate the Policy Engine.
 
 217      * @param droolsTemplate the DRL rules file
 
 218      * @param yamlFile the yaml file containing the policies
 
 219      * @param policyScope scope for policy
 
 220      * @param policyName name of the policy
 
 221      * @param policyVersion version of the policy
 
 222      * @return the kieSession to be used to insert facts
 
 223      * @throws IOException throws IO exception
 
 225     private static KieSession startSession(String droolsTemplate, String yamlFile, String policyScope,
 
 226             String policyName, String policyVersion) throws IOException {
 
 229          * Load policies from yaml
 
 231         pair = Util.loadYaml(yamlFile);
 
 233         assertNotNull(pair.first);
 
 234         assertNotNull(pair.first.getControlLoop());
 
 235         assertNotNull(pair.first.getControlLoop().getControlLoopName());
 
 236         assertTrue(pair.first.getControlLoop().getControlLoopName().length() > 0);
 
 239          * Construct a kie session
 
 241         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
 
 242                 pair.first.getControlLoop().getControlLoopName(),
 
 243                 policyScope, policyName, policyVersion, URLEncoder.encode(pair.second, "UTF-8"));
 
 246          * Retrieve the Policy Engine
 
 249         logger.debug("============");
 
 250         logger.debug(URLEncoder.encode(pair.second, "UTF-8"));
 
 251         logger.debug("============");
 
 259      * @see org.onap.policy.drools.PolicyEngineListener#newEventNotification(java.lang.String)
 
 262     public void onTopicEvent(CommInfrastructure commType, String topic, String event) {
 
 264          * Pull the object that was sent out to DMAAP and make sure it is a ControlLoopNoticiation
 
 268         if ("POLICY-CL-MGT".equals(topic)) {
 
 269             obj = org.onap.policy.controlloop.util.Serialization.gsonJunit.fromJson(event,
 
 270                     org.onap.policy.controlloop.VirtualControlLoopNotification.class);
 
 271         } else if ("APPC-LCM-READ".equals(topic)) {
 
 272             obj = org.onap.policy.appclcm.util.Serialization.gsonJunit.fromJson(event,
 
 273                     org.onap.policy.appclcm.LcmRequestWrapper.class);
 
 276         if (obj instanceof VirtualControlLoopNotification) {
 
 277             VirtualControlLoopNotification notification = (VirtualControlLoopNotification) obj;
 
 278             String policyName = notification.getPolicyName();
 
 279             if (policyName.endsWith("EVENT")) {
 
 280                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 281                 assertTrue(ControlLoopNotificationType.ACTIVE.equals(notification.getNotification()));
 
 282             } else if (policyName.endsWith("GUARD_NOT_YET_QUERIED")) {
 
 283                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 284                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 285                 assertNotNull(notification.getMessage());
 
 286                 assertTrue(notification.getMessage().startsWith("Sending guard query"));
 
 287             } else if (policyName.endsWith("GUARD.RESPONSE")) {
 
 288                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 289                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 290                 assertNotNull(notification.getMessage());
 
 291                 assertTrue(notification.getMessage().toLowerCase().endsWith("permit"));
 
 292             } else if (policyName.endsWith("GUARD_PERMITTED")) {
 
 293                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 294                 assertTrue(ControlLoopNotificationType.OPERATION.equals(notification.getNotification()));
 
 295                 assertNotNull(notification.getMessage());
 
 296                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
 
 297             } else if (policyName.endsWith("OPERATION.TIMEOUT")) {
 
 298                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 300                 logger.debug("The operation timed out");
 
 301                 fail("Operation Timed Out");
 
 302             } else if (policyName.endsWith("APPC.LCM.RESPONSE")) {
 
 303                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 304                 assertTrue(ControlLoopNotificationType.OPERATION_SUCCESS.equals(notification.getNotification()));
 
 305                 assertNotNull(notification.getMessage());
 
 306                 assertTrue(notification.getMessage().startsWith("actor=APPC"));
 
 307                 if (requestId.equals(notification.getRequestId())) {
 
 308                     sendEvent(pair.first, requestId, ControlLoopEventStatus.ABATED, "vnf01");
 
 309                 } else if (requestId2.equals(notification.getRequestId())) {
 
 310                     sendEvent(pair.first, requestId2, ControlLoopEventStatus.ABATED, "vnf02");
 
 312             } else if (policyName.endsWith("EVENT.MANAGER")) {
 
 313                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 314                 if (requestId3.equals(notification.getRequestId())) {
 
 316                      * The event with the duplicate target should be rejected
 
 318                     assertTrue(ControlLoopNotificationType.REJECTED.equals(notification.getNotification()));
 
 320                     assertTrue(ControlLoopNotificationType.FINAL_SUCCESS.equals(notification.getNotification()));
 
 322                 if (++eventCount == 3) {
 
 325             } else if (policyName.endsWith("EVENT.MANAGER.TIMEOUT")) {
 
 326                 logger.debug("Rule Fired: " + notification.getPolicyName());
 
 328                 logger.debug("The control loop timed out");
 
 329                 fail("Control Loop Timed Out");
 
 331         } else if (obj instanceof LcmRequestWrapper) {
 
 333              * The request should be of type LCMRequestWrapper and the subrequestid should be 1
 
 335             LcmRequestWrapper dmaapRequest = (LcmRequestWrapper) obj;
 
 336             LcmRequest appcRequest = dmaapRequest.getBody();
 
 337             assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
 
 339             logger.debug("\n============ APPC received the request!!! ===========\n");
 
 342              * Simulate a success response from APPC and insert the response into the working memory
 
 344             LcmResponseWrapper dmaapResponse = new LcmResponseWrapper();
 
 345             LcmResponse appcResponse = new LcmResponse(appcRequest);
 
 346             appcResponse.getStatus().setCode(400);
 
 347             appcResponse.getStatus().setMessage("AppC success");
 
 348             dmaapResponse.setBody(appcResponse);
 
 351              * Interrupting with a different request for the same target entity to check if lock
 
 354             if (requestId.equals(appcResponse.getCommonHeader().getRequestId())) {
 
 355                 sendEvent(pair.first, requestId3, ControlLoopEventStatus.ONSET, "vnf01");
 
 357             kieSession.insert(dmaapResponse);
 
 362      * This method is used to simulate event messages from DCAE that start the control loop (onset
 
 363      * message) or end the control loop (abatement message).
 
 365      * @param policy the controlLoopName comes from the policy
 
 366      * @param requestID the requestId for this event
 
 367      * @param status could be onset or abated
 
 368      * @param target the target entity to take an action on
 
 370     protected void sendEvent(ControlLoopPolicy policy, UUID requestId, ControlLoopEventStatus status, String target) {
 
 371         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 372         event.setClosedLoopControlName(policy.getControlLoop().getControlLoopName());
 
 373         event.setRequestId(requestId);
 
 374         event.setTarget("generic-vnf.vnf-id");
 
 375         event.setClosedLoopAlarmStart(Instant.now());
 
 376         event.setAai(new HashMap<>());
 
 377         event.getAai().put("generic-vnf.vnf-id", target);
 
 378         event.setClosedLoopEventStatus(status);
 
 379         kieSession.insert(event);
 
 383      * This method will dump all the facts in the working memory.
 
 385      * @param kieSession the session containing the facts
 
 387     public void dumpFacts(KieSession kieSession) {
 
 388         logger.debug("Fact Count: {}", kieSession.getFactCount());
 
 389         for (FactHandle handle : kieSession.getFactHandles()) {
 
 390             logger.debug("FACT: {}", handle);