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.so.SOResponseWrapper;
 
  59 import org.onap.policy.guard.PolicyGuard;
 
  60 import org.onap.policy.guard.PolicyGuard.LockResult;
 
  61 import org.onap.policy.guard.TargetLock;
 
  62 import org.onap.policy.guard.GuardResult;
 
  63 import org.onap.policy.guard.PolicyGuardRequest;
 
  64 import org.onap.policy.guard.PolicyGuardResponse;
 
  65 import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes;
 
  66 import org.onap.policy.guard.PolicyGuardXacmlHelper;
 
  68 import org.yaml.snakeyaml.Yaml;
 
  69 import org.yaml.snakeyaml.constructor.Constructor;
 
  71 import org.slf4j.LoggerFactory;
 
  72 import org.slf4j.Logger;
 
  74 import java.time.Instant;
 
  75 import java.util.LinkedList;
 
  76 import java.util.Iterator;
 
  78 import org.onap.policy.drools.system.PolicyEngine;
 
  81  * This structure mimics the Params structure.
 
  82  * Its only purpose is to allow management of
 
  83  * rules by the PAP component..
 
  84  * It has no use at runtime since the rules go by
 
  85  * Params for matching purposes.
 
  88   closedLoopControlName : String
 
  89   controlLoopYaml : String
 
  93  * Control Loop Identity
 
  96   closedLoopControlName : String
 
  97   controlLoopYaml : String
 
 104 declare OperationTimer
 
 105   closedLoopControlName : String
 
 113 declare ControlLoopTimer
 
 114   closedLoopControlName : String
 
 121 * Called once and only once to insert the parameters into working memory for this Closed Loop policy.
 
 124 rule "${policyName}.SETUP"
 
 128     Params params = new Params();
 
 129     params.setClosedLoopControlName("${closedLoopControlName}");
 
 130     params.setControlLoopYaml("${controlLoopYaml}");
 
 133     // Note: globals have bad behavior when persistence is used,
 
 134     //       hence explicitly getting the logger vs using a global
 
 136     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 137     logger.info("{}: {} : YAML=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(), params.getControlLoopYaml());
 
 142 * This rule responds to DCAE Events where there is no manager yet. Either it is
 
 143 * the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled)
 
 146 rule "${policyName}.EVENT"
 
 148         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 149         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 150         not ( ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() ) )
 
 153     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 154     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 159         // Check the event, because we need it to not be null when
 
 160         // we create the ControlLoopEventManager. The ControlLoopEventManager
 
 161         // will do extra syntax checking as well check if the closed loop is disabled.
 
 163         if ($event.getRequestID() == null) {
 
 164             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 165             notification.setNotification(ControlLoopNotificationType.REJECTED);
 
 166             notification.setFrom("policy");
 
 167             notification.setMessage("Missing requestID");
 
 168             notification.setPolicyName(drools.getRule().getName());
 
 169             notification.setPolicyScope("${policyScope}");
 
 170             notification.setPolicyVersion("${policyVersion}");
 
 173             // Let interested parties know
 
 175             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 178             // Retract it from memory
 
 181         } else if ($event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET) {
 
 182                 throw new ControlLoopException($event.getClosedLoopEventStatus() + " received with no prior onset");
 
 185             // Create an EventManager
 
 187             ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.getRequestID());
 
 189             // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.)
 
 191             VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event);
 
 192             notification.setFrom("pdp-0001-controller=controlloop"); // Engine.getInstanceName()
 
 193             notification.setPolicyName(drools.getRule().getName());
 
 194             notification.setPolicyScope("${policyScope}");
 
 195             notification.setPolicyVersion("${policyVersion}");
 
 197             // Are we actively pursuing this event?
 
 199             if (notification.getNotification() == ControlLoopNotificationType.ACTIVE) {
 
 201                 // Insert Event Manager into memory, this will now kick off processing.
 
 205                 // Let interested parties know
 
 207                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 209                 // Setup the Overall Control Loop timer
 
 211                 ControlLoopTimer clTimer = new ControlLoopTimer();
 
 212                 clTimer.setClosedLoopControlName($event.getClosedLoopControlName());
 
 213                 clTimer.setRequestID($event.getRequestID().toString());
 
 214                 clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s");
 
 221                 // Let interested parties know
 
 223                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 225                 // Retract it from memory
 
 231             // Now that the manager is inserted into Drools working memory, we'll wait for
 
 232             // another rule to fire in order to continue processing. This way we can also
 
 233             // then screen for additional ONSET and ABATED events for this RequestID.
 
 236     } catch (Exception e) {
 
 237         logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
 
 239         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 240         notification.setNotification(ControlLoopNotificationType.REJECTED);
 
 241         notification.setMessage("Exception occurred: " + e.getMessage());
 
 242         notification.setPolicyName(drools.getRule().getName());
 
 243         notification.setPolicyScope("${policyScope}");
 
 244         notification.setPolicyVersion("${policyVersion}");
 
 248         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 258 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
 
 259 * is now created. We can start processing the yaml specification via the Event Manager.
 
 262 rule "${policyName}.EVENT.MANAGER"
 
 264         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 265         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 266         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
 267         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
 270     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 271     logger.info("{}: {}: event={} manager={} clTimer={}", 
 
 272                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 273                 $event, $manager, $clTimer);
 
 277             // Check which event this is.
 
 279             ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);
 
 281             // Check what kind of event this is
 
 283             if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) {
 
 285                 // We don't care about subsequent onsets
 
 287                 logger.info("{}: {}: subsequent onset", 
 
 288                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 292             if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) {
 
 294                 // Ignore any bad syntax events
 
 296                 logger.warn("{}: {}: syntax error", 
 
 297                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 302             // We only want the initial ONSET event in memory,
 
 303             // all the other events need to be retracted to support
 
 304             // cleanup and avoid the other rules being fired for this event.
 
 306             if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) {
 
 307                 logger.warn("{}: {}: no first onset", 
 
 308                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 312             logger.debug("{}: {}: target={}", $params.getClosedLoopControlName(), 
 
 313                          drools.getRule().getName(), $event.getTarget());
 
 315             // Now start seeing if we need to process this event
 
 319         // Check if this is a Final Event
 
 321         VirtualControlLoopNotification notification = $manager.isControlLoopFinal();
 
 324         if (notification != null) {
 
 326             // Its final, but are we waiting for abatement?
 
 328             if ($manager.getNumAbatements() > 0) {
 
 329                 logger.info("{}: {}: abatement received for {}.  Closing the control loop", 
 
 330                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 331                             $event.getRequestID());
 
 332                 notification.setFrom("policy");
 
 333                 notification.setPolicyName(drools.getRule().getName());
 
 334                 notification.setPolicyScope("${policyScope}");
 
 335                 notification.setPolicyVersion("${policyVersion}");
 
 337                 // In this case, we are done
 
 339                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 343                 TargetLock lock = $manager.unlockCurrentOperation();
 
 345                     logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
 
 346                                  drools.getRule().getName(), lock);
 
 350                 // Retract everything from memory
 
 352                 logger.info("{}: {}: retracting onset, manager, and timer", 
 
 353                             $params.getClosedLoopControlName(), drools.getRule().getName());
 
 355                 retract($manager.getOnsetEvent());
 
 359                 // TODO - what if we get subsequent Events for this RequestID?
 
 360                 // By default, it will all start over again. May be confusing for Ruby.
 
 361                 // Or, we could track this and then subsequently ignore the events
 
 365                 // Check whether we need to wait for abatement
 
 367                 if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.getNotification() == ControlLoopNotificationType.FINAL_SUCCESS) {
 
 368                   logger.info("{}: {}: waiting for abatement ..", 
 
 369                               $params.getClosedLoopControlName(), drools.getRule().getName());
 
 371                   logger.info("{}: {}: no abatement expect for {}.  Closing the control loop", 
 
 372                               $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 373                               $event.getRequestID());
 
 375                   notification.setFrom("policy");
 
 376                   notification.setPolicyName(drools.getRule().getName());
 
 377                   notification.setPolicyScope("${policyScope}");
 
 378                   notification.setPolicyVersion("${policyVersion}");
 
 381                   // In this case, we are done
 
 383                   PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 387                   TargetLock lock = $manager.unlockCurrentOperation();
 
 389                       logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
 
 390                                   drools.getRule().getName(), lock);
 
 394                   // Retract everything from memory
 
 396                   logger.info("{}: {}: retracting onset, manager, and timer", 
 
 397                               $params.getClosedLoopControlName(), drools.getRule().getName());
 
 399                   retract($manager.getOnsetEvent());
 
 406             // NOT final, so let's ask for the next operation
 
 408             ControlLoopOperationManager operation = $manager.processControlLoop();
 
 409             if (operation != null) {
 
 411               // Let's ask for a lock right away
 
 413               LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation();
 
 414               logger.info("{}: {}: guard lock acquired={}", 
 
 415                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 417               if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) {
 
 419                 // insert the operation into memory
 
 424                 // insert operation timeout object
 
 426                 OperationTimer opTimer = new OperationTimer();
 
 427                 opTimer.setClosedLoopControlName($event.getClosedLoopControlName());
 
 428                 opTimer.setRequestID($event.getRequestID().toString());
 
 429                 opTimer.setDelay(operation.getOperationTimeout().toString() + "s");
 
 433                 // Insert lock into memory
 
 435                 insert(result.getB());
 
 438                 logger.debug("The target resource {} is already processing",
 
 439                                           $event.getAAI().get($event.getTarget()));
 
 440                 notification = new VirtualControlLoopNotification($event);
 
 441                         notification.setNotification(ControlLoopNotificationType.REJECTED);
 
 442                         notification.setMessage("The target " + $event.getAAI().get($event.getTarget()) + " is already locked");
 
 443                         notification.setFrom("policy");
 
 444                         notification.setPolicyName(drools.getRule().getName());
 
 445                         notification.setPolicyScope("${policyScope}");
 
 446                         notification.setPolicyVersion("${policyVersion}");
 
 448                         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);                      
 
 454               logger.info("{}: {}: starting operation={}", 
 
 455                           $params.getClosedLoopControlName(), drools.getRule().getName(), 
 
 459                 // Probably waiting for abatement
 
 461               logger.info("{}: {}: no operation, probably waiting for abatement", 
 
 462                           $params.getClosedLoopControlName(), drools.getRule().getName());
 
 465     } catch (Exception e) {
 
 466         logger.warn("{}: {}: unexpected", 
 
 467                   $params.getClosedLoopControlName(), 
 
 468                   drools.getRule().getName(), e);
 
 470         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 471             notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
 
 472             notification.setMessage(e.getMessage());
 
 473             notification.setFrom("policy");
 
 474             notification.setPolicyName(drools.getRule().getName());
 
 475             notification.setPolicyScope("${policyScope}");
 
 476             notification.setPolicyVersion("${policyVersion}");
 
 478                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);                      
 
 489 * Guard Permitted, let's send request to the actor.
 
 492 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED"
 
 494         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 495         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 496         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
 497         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID(), "Permit".equalsIgnoreCase(getGuardApprovalStatus()) )
 
 498         $lock : TargetLock (requestID == $event.getRequestID())
 
 499         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
 502     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 503     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
 
 504                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 505                 $event, $manager, $operation, $lock);    
 
 507     Object request = null;
 
 508     boolean caughtException = false;
 
 510         request = $operation.startOperation($event);
 
 512     catch (ControlLoopException e) {
 
 513         String msg = e.getMessage();
 
 514         logger.warn("{}: {}: operation={}:  AAI failure: {}", 
 
 515                     $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 517         $operation.setOperationHasException(msg);
 
 520         caughtException = true;
 
 523     // Having the modify statement in the catch clause doesn't work for whatever reason
 
 524     if (caughtException) {
 
 525         modify($manager) {finishOperation($operation)};
 
 527     else if (request != null) {
 
 528       logger.debug("{}: {}: starting operation ..", 
 
 529                    $params.getClosedLoopControlName(), drools.getRule().getName());
 
 531       // Tell interested parties we are performing this Operation
 
 533       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 534       notification.setNotification(ControlLoopNotificationType.OPERATION);
 
 535       notification.setMessage($operation.getOperationMessage());
 
 536       notification.setHistory($operation.getHistory());
 
 537       notification.setFrom("policy");
 
 538       notification.setPolicyName(drools.getRule().getName());
 
 539       notification.setPolicyScope("${policyScope}");
 
 540       notification.setPolicyVersion("${policyVersion}");
 
 542       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 544       switch ($operation.policy.getActor()){
 
 548               if (request instanceof Request) {
 
 549                   PolicyEngine.manager.deliver("APPC-CL", request);
 
 551               else if (request instanceof LCMRequestWrapper) {
 
 552                   PolicyEngine.manager.deliver("APPC-LCM-READ", request);
 
 556               // at this point the AAI named query request should have already been made, the response recieved and used
 
 557               // in the construction of the SO Request which is stored in operationRequest
 
 559               if(request instanceof SORequest) {
 
 560                   // Call SO. The response will be inserted into memory once it's received 
 
 561                   SOActorServiceProvider.sendRequest($event.getRequestID().toString(), drools.getWorkingMemory(), request);                        
 
 565               if (request instanceof VFCRequest) {
 
 567                   Thread t = new Thread(new VFCManager(drools.getWorkingMemory(), (VFCRequest)request));
 
 574       // What happens if its null?
 
 576                 logger.warn("{}: {}: unexpected null operation request", 
 
 577                   $params.getClosedLoopControlName(), 
 
 578                   drools.getRule().getName());
 
 579                 if ("SO".equals($operation.policy.getActor())) {
 
 582                         modify($manager) {finishOperation($operation)};
 
 584                 else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) {
 
 587                         modify($manager) {finishOperation($operation)};
 
 596 * We were able to acquire a lock so now let's ask Xacml Guard whether 
 
 597 * we are allowed to proceed with the request to the actor.
 
 600 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
 
 602         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 603         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
 604         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
 605         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID(), getGuardApprovalStatus() == "NONE" )
 
 606         $lock : TargetLock (requestID == $event.getRequestID())
 
 609     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 610     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
 
 611                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 612                 $event, $manager, $operation, $lock);
 
 615     // Sending notification that we are about to query Guard ("DB write - start operation")
 
 617     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 618     notification.setNotification(ControlLoopNotificationType.OPERATION);
 
 619     notification.setMessage("Sending guard query for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe());
 
 620     notification.setHistory($operation.getHistory());
 
 621     notification.setFrom("policy");
 
 622     notification.setPolicyName(drools.getRule().getName());
 
 623     notification.setPolicyScope("${policyScope}");
 
 624     notification.setPolicyVersion("${policyVersion}");
 
 626     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 629     // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, 
 
 630     // just change guardEnabled to false.
 
 632     // In order to use REST XACML, provide a URL instead of "" as a second argument 
 
 633     // to the CallGuardTask() and set the first argument to null 
 
 634     // (instead of XacmlPdpEngine).
 
 637     // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled
 
 638     boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
 
 642         Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
 
 643                                                         drools.getWorkingMemory(),
 
 644                                                         $event.getClosedLoopControlName(),
 
 645                                                         $operation.policy.getActor().toString(),
 
 646                                                         $operation.policy.getRecipe(),
 
 647                                                         $operation.getTargetEntity(),
 
 648                                                         $event.getRequestID().toString()
 
 653         insert(new PolicyGuardResponse("Permit", $event.getRequestID(), $operation.policy.getRecipe()));
 
 659 // This rule will be triggered when a thread talking to the XACML Guard inserts a 
 
 660 // guardResponse object into the working memory
 
 662 rule "${policyName}.GUARD.RESPONSE"
 
 664         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 665         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
 
 666         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() ) 
 
 667         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() )
 
 668         $lock : TargetLock (requestID == $event.getRequestID())
 
 669         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
 670         $guardResponse : PolicyGuardResponse(requestID == $event.getRequestID(), $operation.policy.recipe == operation)
 
 673     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 674     logger.info("{}: {}: event={} manager={} operation={} lock={} opTimer={} guardResponse={}", 
 
 675                  $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 676                  $event, $manager, $operation, $lock, $opTimer, $guardResponse);
 
 679     //we will permit the operation if there was no Guard for it
 
 680     if("Indeterminate".equalsIgnoreCase($guardResponse.getResult())){
 
 681         $guardResponse.setResult("Permit");
 
 685     // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
 
 687     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 688     notification.setNotification(ControlLoopNotificationType.OPERATION);
 
 689     notification.setMessage("Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe() + " is " + $guardResponse.getResult());
 
 690     notification.setHistory($operation.getHistory());
 
 691     notification.setFrom("policy");
 
 692     notification.setPolicyName(drools.getRule().getName());
 
 693     notification.setPolicyScope("${policyScope}");
 
 694     notification.setPolicyVersion("${policyVersion}");
 
 696     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 698     if("Permit".equalsIgnoreCase($guardResponse.getResult())){
 
 700         modify($operation){setGuardApprovalStatus($guardResponse.getResult())};
 
 703         //This is the Deny case
 
 704         $operation.startOperation($event);
 
 705         $operation.setOperationHasGuardDeny();
 
 708         modify($manager) {finishOperation($operation)};
 
 711     retract($guardResponse);
 
 717 * This rule responds to APPC Response Events
 
 719 * I would have like to be consistent and write the Response like this:
 
 720 * $response : Response( CommonHeader.RequestID == $onset.getRequestID() )
 
 722 * However, no compile error was given. But a runtime error was given. I think
 
 723 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
 
 726 rule "${policyName}.APPC.RESPONSE"
 
 728         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 729         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
 
 730         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
 731         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() )
 
 732         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
 733         $lock : TargetLock (requestID == $event.getRequestID())
 
 734         $response : Response( getCommonHeader().RequestID == $event.getRequestID() )
 
 737     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 738     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 739     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
 740                  $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 741                  $event, $manager, $operation, $lock, $opTimer, $response);
 
 743     // Get the result of the operation
 
 745     PolicyResult policyResult = $operation.onResponse($response);
 
 746     if (policyResult != null) {
 
 747         logger.debug("{}: {}: operation finished - result={}", 
 
 748                     $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 751         // This Operation has completed, construct a notification showing our results. (DB write - end operation)
 
 753         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 754         notification.setFrom("policy");
 
 755         notification.setPolicyName(drools.getRule().getName());
 
 756         notification.setPolicyScope("${policyScope}");
 
 757         notification.setPolicyVersion("${policyVersion}");
 
 758         notification.setMessage($operation.getOperationHistory());
 
 759         notification.setHistory($operation.getHistory());
 
 760         if (policyResult.equals(PolicyResult.SUCCESS)) {
 
 761             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
 
 763             // Let interested parties know
 
 765             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 767             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
 
 769             // Let interested parties know
 
 771             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 774         // Ensure the operation is complete
 
 776         if ($operation.isOperationComplete() == true) {
 
 778             // It is complete, remove it from memory
 
 782             // We must also retract the timer object
 
 783             // NOTE: We could write a Rule to do this
 
 787             // Complete the operation
 
 789             modify($manager) {finishOperation($operation)};
 
 792             // Just doing this will kick off the LOCKED rule again
 
 794             modify($operation) {};
 
 798         // Its not finished yet (i.e. expecting more Response objects)
 
 800         // Or possibly it is a leftover response that we timed the request out previously
 
 804     // We are going to retract these objects from memory
 
 811 * The problem with Responses is that they don't have a controlLoopControlName
 
 812 * field in them, so the only way to attach them is via RequestID. If we have multiple
 
 813 * control loop .drl's loaded in the same container, we need to be sure the cleanup
 
 814 * rules don't remove Responses for other control loops.
 
 817 rule "${policyName}.APPC.RESPONSE.CLEANUP"
 
 819         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 820         $response : Response($id : getCommonHeader().RequestID )
 
 821         not ( VirtualControlLoopEvent( requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
 
 824     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 825     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 826     logger.debug("{}: {}: orphan appc response={}", 
 
 827                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
 
 837 * This rule responds to APPC Response Events using the new LCM interface provided by appc
 
 840 rule "${policyName}.APPC.LCM.RESPONSE"
 
 842         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 843         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
 
 844         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
 845         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() )
 
 846         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
 847         $lock : TargetLock (requestID == $event.getRequestID())
 
 848         $response : LCMResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.getRequestID() )
 
 851     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 852     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 853     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
 854                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 855                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
 
 858     // Get the result of the operation
 
 860     PolicyResult policyResult = $operation.onResponse($response);
 
 861     if (policyResult != null) {
 
 862       logger.debug("{}: {}: operation finished - result={}", 
 
 863                   $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 867       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
 
 869       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 870       notification.setFrom("policy");
 
 871       notification.setPolicyName(drools.getRule().getName());
 
 872       notification.setPolicyScope("${policyScope}");
 
 873       notification.setPolicyVersion("${policyVersion}");
 
 874       notification.setMessage($operation.getOperationHistory());
 
 875       notification.setHistory($operation.getHistory());
 
 876       if (policyResult.equals(PolicyResult.SUCCESS)) {
 
 877           notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
 
 879           notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
 
 881       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 883       // Ensure the operation is complete
 
 885       if ($operation.isOperationComplete() == true) {
 
 887           // It is complete, remove it from memory
 
 891           // We must also retract the timer object
 
 892           // NOTE: We could write a Rule to do this
 
 896           // Complete the operation
 
 898           modify($manager) {finishOperation($operation)};
 
 901           // Just doing this will kick off the LOCKED rule again
 
 903           modify($operation) {};
 
 907         // Its not finished yet (i.e. expecting more Response objects)
 
 909         // Or possibly it is a leftover response that we timed the request out previously
 
 913     // We are going to retract these objects from memory
 
 920 * Clean Up any lingering LCM reponses
 
 923 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
 
 925         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 926         $response : LCMResponseWrapper($id : getBody().getCommonHeader().getRequestId )
 
 927         not ( VirtualControlLoopEvent( requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
 
 930     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 931     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 932     logger.debug("{}: {}: orphan appc response={}", 
 
 933                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
 
 942 * This rule responds to SO Response Events
 
 945 rule "${policyName}.SO.RESPONSE"
 
 947         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
 948         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
 
 949         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName() )
 
 950         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() )
 
 951         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
 952         $lock : TargetLock (requestID == $event.getRequestID())
 
 953         $response : SOResponseWrapper(requestID.toString() == $event.getRequestID().toString() )
 
 956     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
 957     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
 958     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
 959                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 960                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
 
 962     // Get the result of the operation
 
 964     PolicyResult policyResult = $operation.onResponse($response);
 
 965     if (policyResult != null) {
 
 966         logger.debug("{}: {}: operation finished - result={}", 
 
 967                     $params.getClosedLoopControlName(), drools.getRule().getName(),
 
 971         // This Operation has completed, construct a notification showing our results
 
 973         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
 974         notification.setFrom("policy");
 
 975         notification.setPolicyName(drools.getRule().getName());
 
 976         notification.setPolicyScope("${policyScope}");
 
 977         notification.setPolicyVersion("${policyVersion}");
 
 978         notification.setMessage($operation.getOperationHistory());
 
 979         notification.setHistory($operation.getHistory());
 
 980         if (policyResult.equals(PolicyResult.SUCCESS)) {
 
 981             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
 
 983             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
 
 986         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
 988         // Ensure the operation is complete
 
 990         if ($operation.isOperationComplete() == true) {
 
 992             // It is complete, remove it from memory
 
 996             // We must also retract the timer object
 
 997             // NOTE: We could write a Rule to do this
 
1001             // Complete the operation
 
1003             modify($manager) {finishOperation($operation)};
 
1006             // Just doing this will kick off the LOCKED rule again
 
1008             modify($operation) {};
 
1012         // Its not finished yet (i.e. expecting more Response objects)
 
1014         // Or possibly it is a leftover response that we timed the request out previously
 
1018     // We are going to retract these objects from memory
 
1026 * This rule responds to VFC Response Events
 
1029 rule "${policyName}.VFC.RESPONSE"
 
1031                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
1032                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
 
1033                 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName() )
 
1034                 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() )
 
1035                 $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() )
 
1036         $lock : TargetLock (requestID == $event.getRequestID())
 
1037                 $response : VFCResponse( requestId.toString() == $event.getRequestID().toString() )     
 
1039                 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
1040         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
1041         logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
 
1042                         $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1043                         $event, $manager, $operation, $lock, $operation, $opTimer, $response);
 
1045                 // Get the result of the operation
 
1047                 PolicyResult policyResult = $operation.onResponse($response);
 
1048                 if (policyResult != null) {
 
1050                         // This Operation has completed, construct a notification showing our results
 
1052                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
1053                         notification.setFrom("policy");
 
1054                         notification.setPolicyName(drools.getRule().getName());
 
1055                         notification.setPolicyScope("${policyScope}");
 
1056                         notification.setPolicyVersion("${policyVersion}");
 
1057                         notification.setMessage($operation.getOperationHistory());
 
1058                         notification.setHistory($operation.getHistory());
 
1060                         // Ensure the operation is complete
 
1062                         if ($operation.isOperationComplete() == true) {
 
1064                                 // It is complete, remove it from memory
 
1066                                 retract($operation);
 
1068                                 // We must also retract the timer object
 
1069                                 // NOTE: We could write a Rule to do this
 
1073                                 // Complete the operation
 
1075                                 modify($manager) {finishOperation($operation)};
 
1078                                 // Just doing this will kick off the LOCKED rule again
 
1080                                 modify($operation) {};
 
1084                         // Its not finished yet (i.e. expecting more Response objects)
 
1086                         // Or possibly it is a leftover response that we timed the request out previously
 
1090                 // We are going to retract these objects from memory
 
1098 * This is the timer that manages the timeout for an individual operation.
 
1101 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
 
1104         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
1105         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
1106         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
1107         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() )
 
1108         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString(), $to : getDelay() )
 
1109         $lock : TargetLock (requestID == $event.getRequestID())
 
1112     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
1113     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
1114     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={}", 
 
1115                 $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1116                 $event, $manager, $operation, $lock, $operation, $opTimer);
 
1119     // Tell it its timed out
 
1121     $operation.setOperationHasTimedOut();
 
1123     // Create a notification for it ("DB Write - end operation")
 
1125     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
 
1126     notification.setFrom("policy");
 
1127     notification.setPolicyName(drools.getRule().getName());
 
1128     notification.setPolicyScope("${policyScope}");
 
1129     notification.setPolicyVersion("${policyVersion}");
 
1130     notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
 
1131     notification.setMessage($operation.getOperationHistory());
 
1132     notification.setHistory($operation.getHistory());
 
1134     // Let interested parties know
 
1136     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
1138     // Get rid of the timer
 
1142     // Ensure the operation is complete
 
1144     if ($operation.isOperationComplete() == true) {
 
1146         // It is complete, remove it from memory
 
1148         retract($operation);
 
1150         // Complete the operation
 
1152         modify($manager) {finishOperation($operation)};
 
1155         // Just doing this will kick off the LOCKED rule again
 
1157         modify($operation) {};
 
1163 * This is the timer that manages the overall control loop timeout.
 
1166 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
 
1169         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
 
1170         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
 
1171         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID() )
 
1172         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString(), $to : getDelay() )
 
1173         $operations : LinkedList()
 
1174                         from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestID() == $event.getRequestID() ) )
 
1175         $opTimers : LinkedList()
 
1176                         from collect( OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestID().toString() ) )
 
1177         $locks : LinkedList()
 
1178                         from collect( TargetLock (requestID == $event.getRequestID()) )
 
1181     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
 
1182     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
 
1184     if ($operations == null) {
 
1185       logger.debug("{}: {}: event={} manager={} clTimer={} operations=0", 
 
1186                   $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1187                   $event, $manager, $clTimer);
 
1189       logger.debug("{}: {}: event={} manager={} clTimer={} operations={}", 
 
1190                   $params.getClosedLoopControlName(), drools.getRule().getName(),
 
1191                   $event, $manager, $clTimer, $operations.size());
 
1194     // Tell the Event Manager it has timed out
 
1196     VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
 
1197     if (notification != null) {
 
1198         notification.setFrom("policy");
 
1199         notification.setPolicyName(drools.getRule().getName());
 
1200         notification.setPolicyScope("${policyScope}");
 
1201         notification.setPolicyVersion("${policyVersion}");
 
1203         // Let interested parties know
 
1205         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
 
1208     // Retract EVERYTHING
 
1213     if ($operations != null && $operations.size() > 0) {
 
1214         Iterator<ControlLoopOperationManager> iter = $operations.iterator();
 
1215         while (iter.hasNext()) {
 
1216             ControlLoopOperationManager manager = iter.next();
 
1220     if ($opTimers != null && $opTimers.size() > 0) {
 
1221         Iterator<OperationTimer> iter = $opTimers.iterator();
 
1222         while (iter.hasNext()) {
 
1223             OperationTimer opTimer = iter.next();
 
1227     if ($locks != null && $locks.size() > 0) {
 
1228         Iterator<TargetLock> iter = $locks.iterator();
 
1229         while (iter.hasNext()) {
 
1230             TargetLock lock = iter.next();
 
1232             // Ensure we release the lock
 
1234             PolicyGuard.unlockTarget(lock);