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.startOperation($event);
730 $operation.setOperationHasGuardDeny();
733 modify($manager) {finishOperation($operation)};
736 retract($guardResponse);
742 * This rule responds to APPC Response Events
744 * I would have like to be consistent and write the Response like this:
745 * $response : Response( CommonHeader.RequestID == $onset.requestID )
747 * However, no compile error was given. But a runtime error was given. I think
748 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
751 rule "${policyName}.APPC.RESPONSE"
753 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
754 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
755 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
756 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
757 $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
758 $lock : TargetLock (requestID == $event.requestID)
759 $response : Response( getCommonHeader().RequestID == $event.requestID )
762 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
763 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
764 logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}",
765 $params.getClosedLoopControlName(), drools.getRule().getName(),
766 $event, $manager, $operation, $lock, $opTimer, $response);
768 // Get the result of the operation
770 PolicyResult policyResult = $operation.onResponse($response);
771 if (policyResult != null) {
772 logger.debug("{}: {}: operation finished - result={}",
773 $params.getClosedLoopControlName(), drools.getRule().getName(),
776 // This Operation has completed, construct a notification showing our results. (DB write - end operation)
778 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
779 notification.from = "policy";
780 notification.policyName = drools.getRule().getName();
781 notification.policyScope = "${policyScope}";
782 notification.policyVersion = "${policyVersion}";
783 notification.message = $operation.getOperationHistory();
784 notification.history = $operation.getHistory();
785 if (policyResult.equals(PolicyResult.SUCCESS)) {
786 notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
788 // Let interested parties know
790 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
792 notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
794 // Let interested parties know
796 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
799 // Ensure the operation is complete
801 if ($operation.isOperationComplete() == true) {
803 // It is complete, remove it from memory
807 // We must also retract the timer object
808 // NOTE: We could write a Rule to do this
812 // Complete the operation
814 modify($manager) {finishOperation($operation)};
817 // Just doing this will kick off the LOCKED rule again
819 modify($operation) {};
823 // Its not finished yet (i.e. expecting more Response objects)
825 // Or possibly it is a leftover response that we timed the request out previously
829 // We are going to retract these objects from memory
836 * The problem with Responses is that they don't have a controlLoopControlName
837 * field in them, so the only way to attach them is via RequestID. If we have multiple
838 * control loop .drl's loaded in the same container, we need to be sure the cleanup
839 * rules don't remove Responses for other control loops.
842 rule "${policyName}.APPC.RESPONSE.CLEANUP"
844 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
845 $response : Response($id : getCommonHeader().RequestID )
846 not ( VirtualControlLoopEvent( requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
849 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
850 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
851 logger.debug("{}: {}: orphan appc response={}",
852 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
862 * This rule responds to APPC Response Events using the new LCM interface provided by appc
865 rule "${policyName}.APPC.LCM.RESPONSE"
867 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
868 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
869 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
870 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
871 $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
872 $lock : TargetLock (requestID == $event.requestID)
873 $response : LCMResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.requestID )
876 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
877 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
878 logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}",
879 $params.getClosedLoopControlName(), drools.getRule().getName(),
880 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
883 // Get the result of the operation
885 PolicyResult policyResult = $operation.onResponse($response);
886 if (policyResult != null) {
887 logger.debug("{}: {}: operation finished - result={}",
888 $params.getClosedLoopControlName(), drools.getRule().getName(),
892 // This Operation has completed, construct a notification showing our results. (DB write - end operation)
894 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
895 notification.from = "policy";
896 notification.policyName = drools.getRule().getName();
897 notification.policyScope = "${policyScope}";
898 notification.policyVersion = "${policyVersion}";
899 notification.message = $operation.getOperationHistory();
900 notification.history = $operation.getHistory();
901 if (policyResult.equals(PolicyResult.SUCCESS)) {
902 notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
904 notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
906 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
908 // Ensure the operation is complete
910 if ($operation.isOperationComplete() == true) {
912 // It is complete, remove it from memory
916 // We must also retract the timer object
917 // NOTE: We could write a Rule to do this
921 // Complete the operation
923 modify($manager) {finishOperation($operation)};
926 // Just doing this will kick off the LOCKED rule again
928 modify($operation) {};
932 // Its not finished yet (i.e. expecting more Response objects)
934 // Or possibly it is a leftover response that we timed the request out previously
938 // We are going to retract these objects from memory
945 * Clean Up any lingering LCM reponses
948 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
950 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
951 $response : LCMResponseWrapper($id : getBody().getCommonHeader().getRequestId )
952 not ( VirtualControlLoopEvent( requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
955 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
956 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
957 logger.debug("{}: {}: orphan appc response={}",
958 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
967 * This rule responds to SO Response Events
970 rule "${policyName}.SO.RESPONSE"
972 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
973 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
974 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )
975 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
976 $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
977 $lock : TargetLock (requestID == $event.requestID)
978 $response : SOResponse( requestReferences.requestId.toString() == $event.requestID.toString() )
981 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
982 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
983 logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}",
984 $params.getClosedLoopControlName(), drools.getRule().getName(),
985 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
987 // Get the result of the operation
989 PolicyResult policyResult = $operation.onResponse($response);
990 if (policyResult != null) {
991 logger.debug("{}: {}: operation finished - result={}",
992 $params.getClosedLoopControlName(), drools.getRule().getName(),
996 // This Operation has completed, construct a notification showing our results
998 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
999 notification.from = "policy";
1000 notification.policyName = drools.getRule().getName();
1001 notification.policyScope = "${policyScope}";
1002 notification.policyVersion = "${policyVersion}";
1003 notification.message = $operation.getOperationHistory();
1004 notification.history = $operation.getHistory();
1005 if (policyResult.equals(PolicyResult.SUCCESS)) {
1006 notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
1008 notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
1011 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1013 // Ensure the operation is complete
1015 if ($operation.isOperationComplete() == true) {
1017 // It is complete, remove it from memory
1019 retract($operation);
1021 // We must also retract the timer object
1022 // NOTE: We could write a Rule to do this
1026 // Complete the operation
1028 modify($manager) {finishOperation($operation)};
1031 // Just doing this will kick off the LOCKED rule again
1033 modify($operation) {};
1037 // Its not finished yet (i.e. expecting more Response objects)
1039 // Or possibly it is a leftover response that we timed the request out previously
1043 // We are going to retract these objects from memory
1051 * This rule responds to VFC Response Events
1054 rule "${policyName}.VFC.RESPONSE"
1056 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1057 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1058 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )
1059 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
1060 $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
1061 $lock : TargetLock (requestID == $event.requestID)
1062 $response : VFCResponse( requestId.toString() == $event.requestID.toString() )
1064 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1065 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1066 logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}",
1067 $params.getClosedLoopControlName(), drools.getRule().getName(),
1068 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
1070 // Get the result of the operation
1072 PolicyResult policyResult = $operation.onResponse($response);
1073 if (policyResult != null) {
1075 // This Operation has completed, construct a notification showing our results
1077 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1078 notification.from = "policy";
1079 notification.policyName = drools.getRule().getName();
1080 notification.policyScope = "${policyScope}";
1081 notification.policyVersion = "${policyVersion}";
1082 notification.message = $operation.getOperationHistory();
1083 notification.history = $operation.getHistory();
1085 // Ensure the operation is complete
1087 if ($operation.isOperationComplete() == true) {
1089 // It is complete, remove it from memory
1091 retract($operation);
1093 // We must also retract the timer object
1094 // NOTE: We could write a Rule to do this
1098 // Complete the operation
1100 modify($manager) {finishOperation($operation)};
1103 // Just doing this will kick off the LOCKED rule again
1105 modify($operation) {};
1109 // Its not finished yet (i.e. expecting more Response objects)
1111 // Or possibly it is a leftover response that we timed the request out previously
1115 // We are going to retract these objects from memory
1123 * This is the timer that manages the timeout for an individual operation.
1126 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
1129 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1130 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1131 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
1132 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
1133 $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() )
1134 $lock : TargetLock (requestID == $event.requestID)
1137 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1138 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1139 logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={}",
1140 $params.getClosedLoopControlName(), drools.getRule().getName(),
1141 $event, $manager, $operation, $lock, $operation, $opTimer);
1144 // Tell it its timed out
1146 $operation.setOperationHasTimedOut();
1148 // Create a notification for it ("DB Write - end operation")
1150 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1151 notification.from = "policy";
1152 notification.policyName = drools.getRule().getName();
1153 notification.policyScope = "${policyScope}";
1154 notification.policyVersion = "${policyVersion}";
1155 notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
1156 notification.message = $operation.getOperationHistory();
1157 notification.history = $operation.getHistory();
1159 // Let interested parties know
1161 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1163 // Get rid of the timer
1167 // Ensure the operation is complete
1169 if ($operation.isOperationComplete() == true) {
1171 // It is complete, remove it from memory
1173 retract($operation);
1175 // Complete the operation
1177 modify($manager) {finishOperation($operation)};
1180 // Just doing this will kick off the LOCKED rule again
1182 modify($operation) {};
1188 * This is the timer that manages the overall control loop timeout.
1191 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
1194 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1195 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1196 $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
1197 $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() )
1198 $operations : LinkedList()
1199 from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) )
1200 $opTimers : LinkedList()
1201 from collect( OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) )
1202 $locks : LinkedList()
1203 from collect( TargetLock (requestID == $event.requestID) )
1206 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1207 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1209 if ($operations == null) {
1210 logger.debug("{}: {}: event={} manager={} clTimer={} operations=0",
1211 $params.getClosedLoopControlName(), drools.getRule().getName(),
1212 $event, $manager, $clTimer);
1214 logger.debug("{}: {}: event={} manager={} clTimer={} operations={}",
1215 $params.getClosedLoopControlName(), drools.getRule().getName(),
1216 $event, $manager, $clTimer, $operations.size());
1219 // Tell the Event Manager it has timed out
1221 VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
1222 if (notification != null) {
1223 notification.from = "policy";
1224 notification.policyName = drools.getRule().getName();
1225 notification.policyScope = "${policyScope}";
1226 notification.policyVersion = "${policyVersion}";
1228 // Let interested parties know
1230 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1233 // Retract EVERYTHING
1238 if ($operations != null && $operations.size() > 0) {
1239 Iterator<ControlLoopOperationManager> iter = $operations.iterator();
1240 while (iter.hasNext()) {
1241 ControlLoopOperationManager manager = iter.next();
1245 if ($opTimers != null && $opTimers.size() > 0) {
1246 Iterator<OperationTimer> iter = $opTimers.iterator();
1247 while (iter.hasNext()) {
1248 OperationTimer opTimer = iter.next();
1252 if ($locks != null && $locks.size() > 0) {
1253 Iterator<TargetLock> iter = $locks.iterator();
1254 while (iter.hasNext()) {
1255 TargetLock lock = iter.next();
1257 // Ensure we release the lock
1259 PolicyGuard.unlockTarget(lock);