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.controlloop;
 
  23 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 
  24 import org.onap.policy.controlloop.VirtualControlLoopNotification;
 
  25 import org.onap.policy.controlloop.ControlLoopEventStatus;
 
  26 import org.onap.policy.controlloop.ControlLoopNotificationType;
 
  27 import org.onap.policy.controlloop.ControlLoopLogger;
 
  28 import org.onap.policy.controlloop.policy.PolicyResult;
 
  29 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
 
  30 import org.onap.policy.controlloop.policy.Policy;
 
  31 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
 
  32 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NEW_EVENT_STATUS;
 
  33 import org.onap.policy.controlloop.eventmanager.ControlLoopOperationManager;
 
  34 import org.onap.policy.controlloop.actor.so.SOActorServiceProvider;
 
  35 import org.onap.policy.aai.util.AAIException;
 
  36 import org.onap.policy.appc.Request;
 
  37 import org.onap.policy.appc.Response;
 
  38 import org.onap.policy.appc.CommonHeader;
 
  39 import org.onap.policy.appclcm.LCMRequestWrapper;
 
  40 import org.onap.policy.appclcm.LCMResponseWrapper;
 
  41 import org.onap.policy.appclcm.LCMRequest;
 
  42 import org.onap.policy.appclcm.LCMResponse;
 
  43 import org.onap.policy.appclcm.LCMCommonHeader;
 
  44 import org.onap.policy.vfc.VFCRequest;
 
  45 import org.onap.policy.vfc.VFCResponse;
 
  46 import org.onap.policy.vfc.VFCManager;
 
  47 import org.onap.policy.so.SOManager;
 
  48 import org.onap.policy.so.SORequest;
 
  49 import org.onap.policy.so.SORequestStatus;
 
  50 import org.onap.policy.so.SORequestDetails;
 
  51 import org.onap.policy.so.SOModelInfo;
 
  52 import org.onap.policy.so.SOCloudConfiguration;
 
  53 import org.onap.policy.so.SORequestInfo;
 
  54 import org.onap.policy.so.SORequestParameters;
 
  55 import org.onap.policy.so.SORelatedInstanceListElement;
 
  56 import org.onap.policy.so.SORelatedInstance;
 
  57 import org.onap.policy.so.SOResponse;
 
  58 import org.onap.policy.guard.PolicyGuard;
 
  59 import org.onap.policy.guard.PolicyGuard.LockResult;
 
  60 import org.onap.policy.guard.TargetLock;
 
  61 import org.onap.policy.guard.GuardResult;
 
  62 import org.onap.policy.guard.PolicyGuardRequest;
 
  63 import org.onap.policy.guard.PolicyGuardResponse;
 
  64 import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes;
 
  65 import org.onap.policy.guard.PolicyGuardXacmlHelper;
 
  67 import org.yaml.snakeyaml.Yaml;
 
  68 import org.yaml.snakeyaml.constructor.Constructor;
 
  70 import org.slf4j.LoggerFactory;
 
  71 import org.slf4j.Logger;
 
  73 import java.time.Instant;
 
  74 import java.util.LinkedList;
 
  75 import java.util.Iterator;
 
  77 import org.onap.policy.drools.system.PolicyEngine;
 
  80  * This structure mimics the Params structure.
 
  81  * Its only purpose is to allow management of
 
  82  * rules by the PAP component..
 
  83  * It has no use at runtime since the rules go by
 
  84  * Params for matching purposes.
 
  87   closedLoopControlName : String
 
  88   controlLoopYaml : String
 
  92  * Control Loop Identity
 
  95   closedLoopControlName : String
 
  96   controlLoopYaml : String
 
 103 declare OperationTimer
 
 104   closedLoopControlName : String
 
 112 declare ControlLoopTimer
 
 113   closedLoopControlName : String
 
 120 * Called once and only once to insert the parameters into working memory for this Closed Loop policy.
 
 123 rule "${policyName}.SETUP"
 
 127     Params params = new Params();
 
 128     params.setClosedLoopControlName("${closedLoopControlName}");
 
 129     params.setControlLoopYaml("${controlLoopYaml}");
 
 132     // Note: globals have bad behavior when persistence is used,
 
 133     //       hence explicitly getting the logger vs using a global
 
 135     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 136     logger.info("{}: {} : YAML=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(), params.getControlLoopYaml());
 
 138     String sqlDbUsername = PolicyEngine.manager.getEnvironmentProperty("sql.db.username");
 
 140     String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url");
 
 141     String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username");
 
 142     String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
 
 144     String soUrl =PolicyEngine.manager.getEnvironmentProperty("so.url");
 
 145     String soUsername = PolicyEngine.manager.getEnvironmentProperty("so.username");
 
 146     String soPassword = PolicyEngine.manager.getEnvironmentProperty("so.password");
 
 148     String vfcUrl =PolicyEngine.manager.getEnvironmentProperty("vfc.url");
 
 149     String vfcUsername = PolicyEngine.manager.getEnvironmentProperty("vfc.username");
 
 150     String vfcPassword = PolicyEngine.manager.getEnvironmentProperty("vfc.password");
 
 152     String guardUrl = PolicyEngine.manager.getEnvironmentProperty("guard.url");
 
 153     String guardUsername = PolicyEngine.manager.getEnvironmentProperty("pdpx.username");
 
 154     String guardPassword = PolicyEngine.manager.getEnvironmentProperty("pdpx.password");
 
 155     String guardJdbcUrl = PolicyEngine.manager.getEnvironmentProperty("guard.jdbc.url");
 
 156     String guardDisabled = PolicyEngine.manager.getEnvironmentProperty("guard.disabled");
 
 158     logger.info("{}: {} : AAI=[{}:{}]", params.getClosedLoopControlName(), drools.getRule().getName(), aaiUrl, aaiUsername);
 
 159     logger.info("{}: {} : SO=[{}:{}]", params.getClosedLoopControlName(), drools.getRule().getName(), soUrl, soUsername);
 
 160     logger.info("{}: {} : VFC=[{}:{}]", params.getClosedLoopControlName(), drools.getRule().getName(), vfcUrl, vfcUsername);
 
 161     logger.info("{}: {} : GUARD=[{}:{}:{}:{}]", params.getClosedLoopControlName(), drools.getRule().getName(), guardUrl, guardUsername, guardJdbcUrl, guardDisabled);
 
 162     logger.info("{}: {} : DB=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(), sqlDbUsername);
 
 167 * This rule responds to DCAE Events where there is no manager yet. Either it is
 
 168 * the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled)
 
 171 rule "${policyName}.EVENT"
 
 173         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 174         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 175         not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) )
 
 178     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 179     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 184         // Check the event, because we need it to not be null when
 
 185         // we create the ControlLoopEventManager. The ControlLoopEventManager
 
 186         // will do extra syntax checking as well check if the closed loop is disabled.
 
 188         if ($event.requestID == null) {
 
 189             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 190             notification.notification = ControlLoopNotificationType.REJECTED;
 
 191             notification.from = "policy";
 
 192             notification.message = "Missing requestID";
 
 193             notification.policyName = drools.getRule().getName();
 
 194             notification.policyScope = "${policyScope}";
 
 195             notification.policyVersion = "${policyVersion}";
 
 198             // Let interested parties know
 
 200             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 203             // Retract it from memory
 
 206         } else if ($event.closedLoopEventStatus != ControlLoopEventStatus.ONSET) {
 
 207                 throw new ControlLoopException($event.closedLoopEventStatus + " received with no prior onset");
 
 210             // Create an EventManager
 
 212             ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID);
 
 214             // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.)
 
 216             VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event);
 
 217             notification.from = "pdp-0001-controller=controlloop"; // Engine.getInstanceName()
 
 218             notification.policyName = drools.getRule().getName();
 
 219             notification.policyScope = "${policyScope}";
 
 220             notification.policyVersion = "${policyVersion}";
 
 222             // Are we actively pursuing this event?
 
 224             if (notification.notification == ControlLoopNotificationType.ACTIVE) {
 
 226                 // Insert Event Manager into memory, this will now kick off processing.
 
 230                 // Let interested parties know
 
 232                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 234                 // Setup the Overall Control Loop timer
 
 236                 ControlLoopTimer clTimer = new ControlLoopTimer();
 
 237                 clTimer.setClosedLoopControlName($event.closedLoopControlName);
 
 238                 clTimer.setRequestID($event.requestID.toString());
 
 239                 clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s");
 
 246                 // Let interested parties know
 
 248                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 250                 // Retract it from memory
 
 256             // Now that the manager is inserted into Drools working memory, we'll wait for
 
 257             // another rule to fire in order to continue processing. This way we can also
 
 258             // then screen for additional ONSET and ABATED events for this RequestID.
 
 261     } catch (Exception e) {
 
 262         logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
 
 264         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 265         notification.notification = ControlLoopNotificationType.REJECTED;
 
 266         notification.message = "Exception occurred: " + e.getMessage();
 
 267         notification.policyName = drools.getRule().getName();
 
 268         notification.policyScope = "${policyScope}";
 
 269         notification.policyVersion = "${policyVersion}";
 
 273         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 283 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
 
 284 * is now created. We can start processing the yaml specification via the Event Manager.
 
 287 rule "${policyName}.EVENT.MANAGER"
 
 289         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 290         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 291         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
 292         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
 295     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 296     logger.info("{}: {}: event={} manager={} clTimer={}", 
 
 297                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 298                 $event, $manager, $clTimer);
 
 302             // Check which event this is.
 
 304             ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);
 
 306             // Check what kind of event this is
 
 308             if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) {
 
 310                 // We don't care about subsequent onsets
 
 312                 logger.info("{}: {}: subsequent onset", 
 
 313                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 317             if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) {
 
 319                 // Ignore any bad syntax events
 
 321                 logger.warn("{}: {}: syntax error", 
 
 322                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 327             // We only want the initial ONSET event in memory,
 
 328             // all the other events need to be retracted to support
 
 329             // cleanup and avoid the other rules being fired for this event.
 
 331             if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) {
 
 332                 logger.warn("{}: {}: no first onset", 
 
 333                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 337             logger.debug("{}: {}: target={}", $params.getClosedLoopControlName(), 
 
 338                          drools.getRule().getName(), $event.target);
 
 340             // Now start seeing if we need to process this event
 
 344         // Check if this is a Final Event
 
 346         VirtualControlLoopNotification notification = $manager.isControlLoopFinal();
 
 349         if (notification != null) {
 
 351             // Its final, but are we waiting for abatement?
 
 353             if ($manager.getNumAbatements() > 0) {
 
 354                 logger.info("{}: {}: abatement received for {}.  Closing the control loop", 
 
 355                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 357                 notification.from = "policy";
 
 358                 notification.policyName = drools.getRule().getName();
 
 359                 notification.policyScope = "${policyScope}";
 
 360                 notification.policyVersion = "${policyVersion}";
 
 362                 // In this case, we are done
 
 364                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 368                 TargetLock lock = $manager.unlockCurrentOperation();
 
 370                     logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
 
 371                                  drools.getRule().getName(), lock);
 
 375                 // Retract everything from memory
 
 377                 logger.info("{}: {}: retracting onset, manager, and timer", 
 
 378                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 380                 retract($manager.getOnsetEvent());
 
 384                 // TODO - what if we get subsequent Events for this RequestID?
 
 385                 // By default, it will all start over again. May be confusing for Ruby.
 
 386                 // Or, we could track this and then subsequently ignore the events
 
 390                 // Check whether we need to wait for abatement
 
 392                 if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.notification == ControlLoopNotificationType.FINAL_SUCCESS) {
 
 393                   logger.info("{}: {}: waiting for abatement ..", 
 
 394                               $params.getClosedLoopControlName(), drools.getRule().getName());
 
 396                   logger.info("{}: {}: no abatement expect for {}.  Closing the control loop", 
 
 397                               $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 400                   notification.from = "policy";
 
 401                   notification.policyName = drools.getRule().getName();
 
 402                   notification.policyScope = "${policyScope}";
 
 403                   notification.policyVersion = "${policyVersion}";
 
 406                   // In this case, we are done
 
 408                   PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 412                   TargetLock lock = $manager.unlockCurrentOperation();
 
 414                       logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
 
 415                                   drools.getRule().getName(), lock);
 
 419                   // Retract everything from memory
 
 421                   logger.info("{}: {}: retracting onset, manager, and timer", 
 
 422                               $params.getClosedLoopControlName(), drools.getRule().getName());
 
 424                   retract($manager.getOnsetEvent());
 
 431             // NOT final, so let's ask for the next operation
 
 433             ControlLoopOperationManager operation = $manager.processControlLoop();
 
 434             if (operation != null) {
 
 436               // Let's ask for a lock right away
 
 438               LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation();
 
 439               logger.info("{}: {}: guard lock acquired={}", 
 
 440                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 442               if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) {
 
 444                 // insert the operation into memory
 
 449                 // insert operation timeout object
 
 451                 OperationTimer opTimer = new OperationTimer();
 
 452                 opTimer.setClosedLoopControlName($event.closedLoopControlName);
 
 453                 opTimer.setRequestID($event.requestID.toString());
 
 454                 opTimer.setDelay(operation.getOperationTimeout().toString() + "s");
 
 458                 // Insert lock into memory
 
 460                 insert(result.getB());
 
 463                 logger.debug("The target resource {} is already processing",
 
 464                                           $event.AAI.get($event.target));
 
 465                 notification = new VirtualControlLoopNotification($event);
 
 466                         notification.notification = ControlLoopNotificationType.REJECTED;
 
 467                         notification.message = "The target " + $event.AAI.get($event.target) + " is already locked";
 
 468                         notification.from = "policy";
 
 469                         notification.policyName = drools.getRule().getName();
 
 470                         notification.policyScope = "${policyScope}";
 
 471                         notification.policyVersion = "${policyVersion}";
 
 473                         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);                      
 
 479               logger.info("{}: {}: starting operation={}", 
 
 480                           $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 484                 // Probably waiting for abatement
 
 486               logger.info("{}: {}: no operation, probably waiting for abatement", 
 
 487                           $params.getClosedLoopControlName(), drools.getRule().getName());
 
 490     } catch (Exception e) {
 
 491         logger.warn("{}: {}: unexpected", 
 
 492                   $params.getClosedLoopControlName(), 
 
 493                   drools.getRule().getName(), e);
 
 495         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 496             notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
 
 497             notification.message = e.getMessage();
 
 498             notification.from = "policy";
 
 499             notification.policyName = drools.getRule().getName();
 
 500             notification.policyScope = "${policyScope}";
 
 501             notification.policyVersion = "${policyVersion}";
 
 503                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);                      
 
 514 * Guard Permitted, let's send request to the actor.
 
 517 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED"
 
 519         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 520         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 521         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
 522         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, "Permit".equalsIgnoreCase(getGuardApprovalStatus()) )
 
 523         $lock : TargetLock (requestID == $event.requestID)
 
 524         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
 527     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 528     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
 
 529                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 530                 $event, $manager, $operation, $lock);    
 
 532     Object request = null;
 
 533     boolean caughtException = false;
 
 535         request = $operation.startOperation($event);
 
 537     catch (AAIException e) {
 
 538         String msg = e.getMessage();
 
 539         logger.warn("{}: {}: operation={}:  AAI failure: {}", 
 
 540                     $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 542         $operation.setOperationHasException(msg);
 
 545         caughtException = true;
 
 548     // Having the modify statement in the catch clause doesn't work for whatever reason
 
 549     if (caughtException) {
 
 550         modify($manager) {finishOperation($operation)};
 
 552     else if (request != null) {
 
 553       logger.debug("{}: {}: starting operation ..", 
 
 554                    $params.getClosedLoopControlName(), drools.getRule().getName());
 
 556       // Tell interested parties we are performing this Operation
 
 558       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 559       notification.notification = ControlLoopNotificationType.OPERATION;
 
 560       notification.message = $operation.getOperationMessage();
 
 561       notification.history = $operation.getHistory();
 
 562       notification.from = "policy";
 
 563       notification.policyName = drools.getRule().getName();
 
 564       notification.policyScope = "${policyScope}";
 
 565       notification.policyVersion = "${policyVersion}";
 
 567       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 569       switch ($operation.policy.getActor()){
 
 573               if (request instanceof Request) {
 
 574                   PolicyEngine.manager.deliver("APPC-CL", request);
 
 576               else if (request instanceof LCMRequestWrapper) {
 
 577                   PolicyEngine.manager.deliver("APPC-LCM-READ", request);
 
 581               // at this point the AAI named query request should have already been made, the response recieved and used
 
 582               // in the construction of the SO Request which is stored in operationRequest
 
 584               if(request instanceof SORequest) {
 
 585                   // Call SO. The response will be inserted into memory once it's received 
 
 586                   SOActorServiceProvider.sendRequest(drools.getWorkingMemory(), request);                        
 
 590               if (request instanceof VFCRequest) {
 
 592                   Thread t = new Thread(new VFCManager(drools.getWorkingMemory(), (VFCRequest)request));
 
 599       // What happens if its null?
 
 601                 logger.warn("{}: {}: unexpected null operation request", 
 
 602                   $params.getClosedLoopControlName(), 
 
 603                   drools.getRule().getName());
 
 604                 if ("SO".equals($operation.policy.getActor())) {
 
 607                         modify($manager) {finishOperation($operation)};
 
 609                 else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) {
 
 612                         modify($manager) {finishOperation($operation)};
 
 621 * We were able to acquire a lock so now let's ask Xacml Guard whether 
 
 622 * we are allowed to proceed with the request to the actor.
 
 625 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
 
 627         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 628         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 629         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
 630         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "NONE" )
 
 631         $lock : TargetLock (requestID == $event.requestID)
 
 634     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 635     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
 
 636                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 637                 $event, $manager, $operation, $lock);
 
 640     // Sending notification that we are about to query Guard ("DB write - start operation")
 
 642     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 643     notification.notification = ControlLoopNotificationType.OPERATION;
 
 644     notification.message = "Sending guard query for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe();
 
 645     notification.history = $operation.getHistory();
 
 646     notification.from = "policy";
 
 647     notification.policyName = drools.getRule().getName();
 
 648     notification.policyScope = "${policyScope}";
 
 649     notification.policyVersion = "${policyVersion}";
 
 651     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 654     // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, 
 
 655     // just change guardEnabled to false.
 
 657     // In order to use REST XACML, provide a URL instead of "" as a second argument 
 
 658     // to the CallGuardTask() and set the first argument to null 
 
 659     // (instead of XacmlPdpEngine).
 
 662     // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled
 
 663     boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
 
 667         Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
 
 668                                                         drools.getWorkingMemory(),
 
 669                                                         $event.closedLoopControlName,
 
 670                                                         $operation.policy.getActor().toString(),
 
 671                                                         $operation.policy.getRecipe(),
 
 672                                                         $operation.getTargetEntity(),
 
 673                                                         $event.requestID.toString()
 
 678         insert(new PolicyGuardResponse("Permit", $event.requestID, $operation.policy.getRecipe()));
 
 684 // This rule will be triggered when a thread talking to the XACML Guard inserts a 
 
 685 // guardResponse object into the working memory
 
 687 rule "${policyName}.GUARD.RESPONSE"
 
 689         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 690         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
 
 691         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) 
 
 692         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
 
 693         $lock : TargetLock (requestID == $event.requestID)
 
 694         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
 695         $guardResponse : PolicyGuardResponse(requestID == $event.requestID, $operation.policy.recipe == operation)
 
 698     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 699     logger.info("{}: {}: event={} manager={} operation={} lock={} opTimer={} guardResponse={}", 
 
 700                  $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 701                  $event, $manager, $operation, $lock, $opTimer, $guardResponse);
 
 704     //we will permit the operation if there was no Guard for it
 
 705     if("Indeterminate".equalsIgnoreCase($guardResponse.result)){
 
 706         $guardResponse.result = "Permit";
 
 710     // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
 
 712     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 713     notification.notification = ControlLoopNotificationType.OPERATION;
 
 714     notification.message = "Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe() + " is " + $guardResponse.result;
 
 715     notification.history = $operation.getHistory();
 
 716     notification.from = "policy";
 
 717     notification.policyName = drools.getRule().getName();
 
 718     notification.policyScope = "${policyScope}";
 
 719     notification.policyVersion = "${policyVersion}";
 
 721     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 723     if("Permit".equalsIgnoreCase($guardResponse.result)){
 
 725         modify($operation){setGuardApprovalStatus($guardResponse.result)};
 
 728         //This is the Deny case
 
 729         $operation.setOperationHasGuardDeny();
 
 732         modify($manager) {finishOperation($operation)};
 
 735     retract($guardResponse);
 
 741 * This rule responds to APPC Response Events
 
 743 * I would have like to be consistent and write the Response like this:
 
 744 * $response : Response( CommonHeader.RequestID == $onset.requestID )
 
 746 * However, no compile error was given. But a runtime error was given. I think
 
 747 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
 
 750 rule "${policyName}.APPC.RESPONSE"
 
 752         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 753         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
 
 754         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
 755         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
 
 756         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
 757         $lock : TargetLock (requestID == $event.requestID)
 
 758         $response : Response( getCommonHeader().RequestID == $event.requestID )
 
 761     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 762     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 763     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
 764                  $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 765                  $event, $manager, $operation, $lock, $opTimer, $response);
 
 767     // Get the result of the operation
 
 769     PolicyResult policyResult = $operation.onResponse($response);
 
 770     if (policyResult != null) {
 
 771         logger.debug("{}: {}: operation finished - result={}", 
 
 772                     $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 775         // This Operation has completed, construct a notification showing our results. (DB write - end operation)
 
 777         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 778         notification.from = "policy";
 
 779         notification.policyName = drools.getRule().getName();
 
 780         notification.policyScope = "${policyScope}";
 
 781         notification.policyVersion = "${policyVersion}";
 
 782         notification.message = $operation.getOperationHistory();
 
 783         notification.history = $operation.getHistory();
 
 784         if (policyResult.equals(PolicyResult.SUCCESS)) {
 
 785             notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
 
 787             // Let interested parties know
 
 789             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 791             notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
 
 793             // Let interested parties know
 
 795             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 798         // Ensure the operation is complete
 
 800         if ($operation.isOperationComplete() == true) {
 
 802             // It is complete, remove it from memory
 
 806             // We must also retract the timer object
 
 807             // NOTE: We could write a Rule to do this
 
 811             // Complete the operation
 
 813             modify($manager) {finishOperation($operation)};
 
 816             // Just doing this will kick off the LOCKED rule again
 
 818             modify($operation) {};
 
 822         // Its not finished yet (i.e. expecting more Response objects)
 
 824         // Or possibly it is a leftover response that we timed the request out previously
 
 828     // We are going to retract these objects from memory
 
 835 * The problem with Responses is that they don't have a controlLoopControlName
 
 836 * field in them, so the only way to attach them is via RequestID. If we have multiple
 
 837 * control loop .drl's loaded in the same container, we need to be sure the cleanup
 
 838 * rules don't remove Responses for other control loops.
 
 841 rule "${policyName}.APPC.RESPONSE.CLEANUP"
 
 843         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 844         $response : Response($id : getCommonHeader().RequestID )
 
 845         not ( VirtualControlLoopEvent( requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
 
 848     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 849     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 850     logger.debug("{}: {}: orphan appc response={}", 
 
 851                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
 
 861 * This rule responds to APPC Response Events using the new LCM interface provided by appc
 
 864 rule "${policyName}.APPC.LCM.RESPONSE"
 
 866         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 867         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
 
 868         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
 869         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
 
 870         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
 871         $lock : TargetLock (requestID == $event.requestID)
 
 872         $response : LCMResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.requestID )
 
 875     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 876     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 877     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
 878                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 879                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
 
 882     // Get the result of the operation
 
 884     PolicyResult policyResult = $operation.onResponse($response);
 
 885     if (policyResult != null) {
 
 886       logger.debug("{}: {}: operation finished - result={}", 
 
 887                   $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 891       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
 
 893       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 894       notification.from = "policy";
 
 895       notification.policyName = drools.getRule().getName();
 
 896       notification.policyScope = "${policyScope}";
 
 897       notification.policyVersion = "${policyVersion}";
 
 898       notification.message = $operation.getOperationHistory();
 
 899       notification.history = $operation.getHistory();
 
 900       if (policyResult.equals(PolicyResult.SUCCESS)) {
 
 901           notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
 
 903           notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
 
 905       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 907       // Ensure the operation is complete
 
 909       if ($operation.isOperationComplete() == true) {
 
 911           // It is complete, remove it from memory
 
 915           // We must also retract the timer object
 
 916           // NOTE: We could write a Rule to do this
 
 920           // Complete the operation
 
 922           modify($manager) {finishOperation($operation)};
 
 925           // Just doing this will kick off the LOCKED rule again
 
 927           modify($operation) {};
 
 931         // Its not finished yet (i.e. expecting more Response objects)
 
 933         // Or possibly it is a leftover response that we timed the request out previously
 
 937     // We are going to retract these objects from memory
 
 944 * Clean Up any lingering LCM reponses
 
 947 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
 
 949         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 950         $response : LCMResponseWrapper($id : getBody().getCommonHeader().getRequestId )
 
 951         not ( VirtualControlLoopEvent( requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
 
 954     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 955     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 956     logger.debug("{}: {}: orphan appc response={}", 
 
 957                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
 
 966 * This rule responds to SO Response Events
 
 969 rule "${policyName}.SO.RESPONSE"
 
 971         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 972         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
 
 973         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )
 
 974         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
 
 975         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
 976         $lock : TargetLock (requestID == $event.requestID)
 
 977         $response : SOResponse( requestReferences.requestId.toString() == $event.requestID.toString() )  
 
 980     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 981     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 982     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
 983                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 984                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
 
 986     // Get the result of the operation
 
 988     PolicyResult policyResult = $operation.onResponse($response);
 
 989     if (policyResult != null) {
 
 990         logger.debug("{}: {}: operation finished - result={}", 
 
 991                     $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 995         // This Operation has completed, construct a notification showing our results
 
 997         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 998         notification.from = "policy";
 
 999         notification.policyName = drools.getRule().getName();
 
1000         notification.policyScope = "${policyScope}";
 
1001         notification.policyVersion = "${policyVersion}";
 
1002         notification.message = $operation.getOperationHistory();
 
1003         notification.history = $operation.getHistory();
 
1004         if (policyResult.equals(PolicyResult.SUCCESS)) {
 
1005             notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
 
1007             notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
 
1010         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
1012         // Ensure the operation is complete
 
1014         if ($operation.isOperationComplete() == true) {
 
1016             // It is complete, remove it from memory
 
1018             retract($operation);
 
1020             // We must also retract the timer object
 
1021             // NOTE: We could write a Rule to do this
 
1025             // Complete the operation
 
1027             modify($manager) {finishOperation($operation)};
 
1030             // Just doing this will kick off the LOCKED rule again
 
1032             modify($operation) {};
 
1036         // Its not finished yet (i.e. expecting more Response objects)
 
1038         // Or possibly it is a leftover response that we timed the request out previously
 
1042     // We are going to retract these objects from memory
 
1050 * This rule responds to VFC Response Events
 
1053 rule "${policyName}.VFC.RESPONSE"
 
1055                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
1056                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
 
1057                 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )
 
1058                 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
 
1059                 $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
 
1060         $lock : TargetLock (requestID == $event.requestID)
 
1061                 $response : VFCResponse( requestId.toString() == $event.requestID.toString() )  
 
1063                 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
1064         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
1065         logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
1066                         $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1067                         $event, $manager, $operation, $lock, $operation, $opTimer, $response);
 
1069                 // Get the result of the operation
 
1071                 PolicyResult policyResult = $operation.onResponse($response);
 
1072                 if (policyResult != null) {
 
1074                         // This Operation has completed, construct a notification showing our results
 
1076                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
1077                         notification.from = "policy";
 
1078                         notification.policyName = drools.getRule().getName();
 
1079                         notification.policyScope = "${policyScope}";
 
1080                         notification.policyVersion = "${policyVersion}";
 
1081                         notification.message = $operation.getOperationHistory();
 
1082                         notification.history = $operation.getHistory();
 
1084                         // Ensure the operation is complete
 
1086                         if ($operation.isOperationComplete() == true) {
 
1088                                 // It is complete, remove it from memory
 
1090                                 retract($operation);
 
1092                                 // We must also retract the timer object
 
1093                                 // NOTE: We could write a Rule to do this
 
1097                                 // Complete the operation
 
1099                                 modify($manager) {finishOperation($operation)};
 
1102                                 // Just doing this will kick off the LOCKED rule again
 
1104                                 modify($operation) {};
 
1108                         // Its not finished yet (i.e. expecting more Response objects)
 
1110                         // Or possibly it is a leftover response that we timed the request out previously
 
1114                 // We are going to retract these objects from memory
 
1122 * This is the timer that manages the timeout for an individual operation.
 
1125 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
 
1128         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
1129         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
1130         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
1131         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
 
1132         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() )
 
1133         $lock : TargetLock (requestID == $event.requestID)
 
1136     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
1137     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
1138     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={}", 
 
1139                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1140                 $event, $manager, $operation, $lock, $operation, $opTimer);
 
1143     // Tell it its timed out
 
1145     $operation.setOperationHasTimedOut();
 
1147     // Create a notification for it ("DB Write - end operation")
 
1149     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
1150     notification.from = "policy";
 
1151     notification.policyName = drools.getRule().getName();
 
1152     notification.policyScope = "${policyScope}";
 
1153     notification.policyVersion = "${policyVersion}";
 
1154     notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
 
1155     notification.message = $operation.getOperationHistory();
 
1156     notification.history = $operation.getHistory();
 
1158     // Let interested parties know
 
1160     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
1162     // Get rid of the timer
 
1166     // Ensure the operation is complete
 
1168     if ($operation.isOperationComplete() == true) {
 
1170         // It is complete, remove it from memory
 
1172         retract($operation);
 
1174         // Complete the operation
 
1176         modify($manager) {finishOperation($operation)};
 
1179         // Just doing this will kick off the LOCKED rule again
 
1181         modify($operation) {};
 
1187 * This is the timer that manages the overall control loop timeout.
 
1190 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
 
1193         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
1194         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
1195         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
 
1196         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() )
 
1197         $operations : LinkedList()
 
1198                         from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) )
 
1199         $opTimers : LinkedList()
 
1200                         from collect( OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) )
 
1201         $locks : LinkedList()
 
1202                         from collect( TargetLock (requestID == $event.requestID) )
 
1205     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
1206     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
1208     if ($operations == null) {
 
1209       logger.debug("{}: {}: event={} manager={} clTimer={} operations=0", 
 
1210                   $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1211                   $event, $manager, $clTimer);
 
1213       logger.debug("{}: {}: event={} manager={} clTimer={} operations={}", 
 
1214                   $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1215                   $event, $manager, $clTimer, $operations.size());
 
1218     // Tell the Event Manager it has timed out
 
1220     VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
 
1221     if (notification != null) {
 
1222         notification.from = "policy";
 
1223         notification.policyName = drools.getRule().getName();
 
1224         notification.policyScope = "${policyScope}";
 
1225         notification.policyVersion = "${policyVersion}";
 
1227         // Let interested parties know
 
1229         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
1232     // Retract EVERYTHING
 
1237     if ($operations != null && $operations.size() > 0) {
 
1238         Iterator<ControlLoopOperationManager> iter = $operations.iterator();
 
1239         while (iter.hasNext()) {
 
1240             ControlLoopOperationManager manager = iter.next();
 
1244     if ($opTimers != null && $opTimers.size() > 0) {
 
1245         Iterator<OperationTimer> iter = $opTimers.iterator();
 
1246         while (iter.hasNext()) {
 
1247             OperationTimer opTimer = iter.next();
 
1251     if ($locks != null && $locks.size() > 0) {
 
1252         Iterator<TargetLock> iter = $locks.iterator();
 
1253         while (iter.hasNext()) {
 
1254             TargetLock lock = iter.next();
 
1256             // Ensure we release the lock
 
1258             PolicyGuard.unlockTarget(lock);