2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 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.assertFalse;
 
  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.UUID;
 
  34 import org.junit.AfterClass;
 
  35 import org.junit.BeforeClass;
 
  36 import org.junit.Test;
 
  37 import org.kie.api.runtime.KieSession;
 
  38 import org.kie.api.runtime.rule.FactHandle;
 
  39 import org.onap.policy.appc.Request;
 
  40 import org.onap.policy.appc.Response;
 
  41 import org.onap.policy.appc.ResponseCode;
 
  42 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  43 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  44 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  45 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  46 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  47 import org.onap.policy.controlloop.policy.TargetType;
 
  48 import org.onap.policy.drools.http.server.HttpServletServer;
 
  49 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
 
  50 import org.onap.policy.guard.PolicyGuard;
 
  51 import org.slf4j.Logger;
 
  52 import org.slf4j.LoggerFactory;
 
  54 public class VFWControlLoopTest {
 
  56     private static final Logger logger = LoggerFactory.getLogger(VFWControlLoopTest.class);
 
  58     private KieSession kieSession;
 
  59     private Util.Pair<ControlLoopPolicy, String> pair;
 
  60     private PolicyEngineJUnitImpl engine;
 
  63         /* Set environment properties */
 
  70     public static void setUpSimulator() {
 
  74         } catch (Exception e) {
 
  80     public static void tearDownSimulator() {
 
  81         HttpServletServer.factory.destroy();
 
  85     public void successTest() {
 
  88          * Start the kie session
 
  91             kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl", 
 
  92                         "src/test/resources/yaml/policy_ControlLoop_vFW.yaml",
 
  93                         "service=ServiceDemo;resource=Res1Demo;type=operational", 
 
  95                         "org.onap.closed_loop.ServiceDemo:VNFS:1.0.0");
 
  96         } catch (IOException e) {
 
  98             logger.debug("Could not create kieSession");
 
  99             fail("Could not create kieSession");
 
 103          * Create a thread to continuously fire rules 
 
 104          * until main thread calls halt
 
 106         new Thread( new Runnable() {
 
 109                 kieSession.fireUntilHalt();
 
 114          * Create a unique requestId and a unique trigger source
 
 116         UUID requestID = UUID.randomUUID();
 
 117         String triggerSourceName = "foobartriggersource36";
 
 120          * This will be the object returned from the PolicyEngine
 
 125          * Simulate an onset event the policy engine will 
 
 126          * receive from DCAE to kick off processing through
 
 130             sendOnset(pair.a, requestID, triggerSourceName);
 
 131         } catch (InterruptedException e) {
 
 133             logger.debug("Unable to send onset event");
 
 134             fail("Unable to send onset event");
 
 138          * Pull the object that was sent out to DMAAP and make
 
 139          * sure it is a ControlLoopNoticiation of type active
 
 141         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
 
 143         assertTrue(obj instanceof VirtualControlLoopNotification);
 
 144         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
 
 147          * Give the control loop time to acquire a lock
 
 151         } catch (InterruptedException e) {
 
 153             logger.debug("An interrupt Exception was thrown");
 
 154             fail("An interrupt Exception was thrown");
 
 158          * The fact should be ready to query guard now to see 
 
 159          * if a ModifyConfig recipe is allowed
 
 161         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
 
 163         logger.debug("\n\n####################### GOING TO QUERY GUARD about ModifyConfig!!!!!!");
 
 164         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
 
 167          * Make sure the object is an instance of a ControlLoopNotification
 
 168          * and is of type operation
 
 170         assertTrue(obj instanceof VirtualControlLoopNotification);
 
 171         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
 
 175         } catch (InterruptedException e) {
 
 177             logger.debug("An interrupt Exception was thrown");
 
 178             fail("An interrupt Exception was thrown");
 
 182          * The guard response should be received at this point
 
 184         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
 
 186         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
 
 189          * The object should be a ControlLoopNotification with type operation
 
 191         assertTrue(obj instanceof VirtualControlLoopNotification);
 
 192         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
 
 195          * See if Guard permits this action, if it does 
 
 196          * not then the test should fail
 
 198         if (((VirtualControlLoopNotification)obj).message.contains("PERMIT")) {
 
 201              * Obtain the ControlLoopNoticiation, it should be of type operation
 
 203             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
 
 205             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
 
 208              * A notification should be sent out of the Policy
 
 209              * Engine at this point, it will be of type operation
 
 211             assertTrue(obj instanceof VirtualControlLoopNotification);
 
 212             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
 
 216             } catch (InterruptedException e) {
 
 218                 logger.debug("An interrupt Exception was thrown");
 
 219                 fail("An interrupt Exception was thrown");
 
 223              * Obtain the request sent from the Policy Engine
 
 225             obj = engine.subscribe("UEB", "APPC-CL");
 
 229              * The request should be of type Request 
 
 230              * and the subrequestid should be 1
 
 232             assertTrue(obj instanceof Request);
 
 233             assertTrue(((Request)obj).getCommonHeader().SubRequestID.equals("1"));
 
 235             logger.debug("\n============ APPC received the request!!! ===========\n");
 
 238              * Give some time for processing
 
 242             } catch (InterruptedException e) {
 
 244                 logger.debug("An interrupt Exception was thrown");
 
 245                 fail("An interrupt Exception was thrown");
 
 249              * Simulate a success response from APPC and insert
 
 250              * the response into the working memory
 
 252             Response appcResponse = new Response((Request)obj);
 
 253             appcResponse.getStatus().Code = ResponseCode.SUCCESS.getValue();
 
 254             appcResponse.getStatus().Value = "SUCCESS";
 
 255             kieSession.insert(appcResponse);
 
 258              * Give time for processing
 
 262             } catch (InterruptedException e) {
 
 264                 logger.debug("An interrupt Exception was thrown");
 
 265                 fail("An interrupt Exception was thrown");
 
 269              * Make sure the next notification is delivered
 
 271             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
 
 273             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
 
 276              * The ControlLoopNotification should be
 
 277              * an OPERATION_SUCCESS
 
 279             assertTrue(obj instanceof VirtualControlLoopNotification);
 
 280             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
 
 283              * Now simulate the abatement sent from DCAE
 
 286                 sendAbatement(pair.a, requestID, triggerSourceName);
 
 287             } catch (InterruptedException e1) {
 
 288                 e1.printStackTrace();
 
 289                 logger.debug("Abatement could not be sent");
 
 290                 fail("Abatement could not be sent");
 
 294              * Give time to finish processing
 
 298             } catch (InterruptedException e) {
 
 300                 logger.debug("An interrupt Exception was thrown");
 
 301                 fail("An interrupt Exception was thrown");
 
 305              * This should be the final notification from the Policy Engine
 
 307             obj = engine.subscribe("UEB", "POLICY-CL-MGT");
 
 309             logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
 
 312              * The ControlLoopNotification should be of type FINAL_SUCCESS
 
 314             assertTrue(obj instanceof VirtualControlLoopNotification);
 
 315             assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
 
 318              * One final check to make sure the lock is released 
 
 320             assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
 
 323             fail("Operation Denied by Guard");
 
 327          * This will stop the thread that is firing the rules
 
 332          * The only fact in memory should be Params
 
 334         // assertEquals(1, kieSession.getFactCount());
 
 335         if (kieSession.getFactCount() != 1L) {
 
 336             logger.error("FACT count mismatch: 1 expected but there are {}", kieSession.getFactCount());
 
 340          * Print what's left in memory
 
 342         dumpFacts(kieSession);
 
 345          * Gracefully shut down the kie session
 
 347         kieSession.dispose();
 
 351      * This method will start a kie session and instantiate 
 
 354      * @param droolsTemplate
 
 357      *          the yaml file containing the policies
 
 362      * @param policyVersion
 
 363      *          version of the policy          
 
 364      * @return the kieSession to be used to insert facts 
 
 365      * @throws IOException
 
 367     private KieSession startSession(String droolsTemplate, 
 
 371             String policyVersion) throws IOException {
 
 374          * Load policies from yaml
 
 376         pair = Util.loadYaml(yamlFile);
 
 378         assertNotNull(pair.a);
 
 379         assertNotNull(pair.a.getControlLoop());
 
 380         assertNotNull(pair.a.getControlLoop().getControlLoopName());
 
 381         assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
 
 384          * Construct a kie session
 
 386         final KieSession kieSession = Util.buildContainer(droolsTemplate, 
 
 387                 pair.a.getControlLoop().getControlLoopName(), 
 
 391                 URLEncoder.encode(pair.b, "UTF-8"));
 
 394          * Retrieve the Policy Engine
 
 396         engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
 
 398         logger.debug("============");
 
 399         logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
 
 400         logger.debug("============");
 
 406      * This method is used to simulate event messages from DCAE
 
 407      * that start the control loop (onset message).
 
 409      * @param policy the controlLoopName comes from the policy 
 
 410      * @param requestID the requestId for this event
 
 411      * @param triggerSourceName 
 
 412      * @throws InterruptedException
 
 414     protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
 
 415         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 416         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
 
 417         event.requestID = requestID;
 
 418         event.target = "generic-vnf.vnf-id";
 
 419         event.closedLoopAlarmStart = Instant.now();
 
 420         event.AAI = new HashMap<>();
 
 421         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
 
 422         event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
 
 423         kieSession.insert(event);
 
 428      * This method is used to simulate event messages from DCAE
 
 429      * that end the control loop (abatement message).
 
 431      * @param policy the controlLoopName comes from the policy 
 
 432      * @param requestID the requestId for this event
 
 433      * @param triggerSourceName 
 
 434      * @throws InterruptedException
 
 436     protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
 
 437         VirtualControlLoopEvent event = new VirtualControlLoopEvent();
 
 438         event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
 
 439         event.requestID = requestID;
 
 440         event.target = "generic-vnf.vnf-id";
 
 441         event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
 
 442         event.closedLoopAlarmEnd = Instant.now();
 
 443         event.AAI = new HashMap<>();
 
 444         event.AAI.put("cloud-region.identity-url", "foo");
 
 445         event.AAI.put("vserver.selflink", "bar");
 
 446         event.AAI.put("vserver.is-closed-loop-disabled", "false");
 
 447         event.AAI.put("generic-vnf.vnf-id", "testGenericVnfID");
 
 448         event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
 
 449         kieSession.insert(event);
 
 453      * This method will dump all the facts in the working memory.
 
 455      * @param kieSession the session containing the facts
 
 457     public void dumpFacts(KieSession kieSession) {
 
 458         logger.debug("Fact Count: {}", kieSession.getFactCount());
 
 459         for (FactHandle handle : kieSession.getFactHandles()) {
 
 460             logger.debug("FACT: {}", handle);