2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Bell Canada.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.controlloop;
24 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
26 import org.onap.policy.controlloop.VirtualControlLoopEvent;
27 import org.onap.policy.controlloop.VirtualControlLoopNotification;
28 import org.onap.policy.controlloop.ControlLoopEventStatus;
29 import org.onap.policy.controlloop.ControlLoopException;
30 import org.onap.policy.controlloop.ControlLoopNotificationType;
31 import org.onap.policy.controlloop.ControlLoopLogger;
32 import org.onap.policy.controlloop.policy.PolicyResult;
33 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
34 import org.onap.policy.controlloop.policy.Policy;
35 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
36 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NewEventStatus;
37 import org.onap.policy.controlloop.eventmanager.ControlLoopOperationManager;
38 import org.onap.policy.controlloop.eventmanager.LockCallbackWorkingMemory;
39 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
40 import org.onap.policy.controlloop.actor.cds.CdsActorServiceProvider;
41 import org.onap.policy.controlloop.actor.cds.CdsActorServiceProvider.CdsActorServiceManager;
42 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
43 import org.onap.policy.aai.AaiNqResponseWrapper;
44 import org.onap.policy.aai.AaiCqResponse;
45 import org.onap.policy.appc.Request;
46 import org.onap.policy.appc.Response;
47 import org.onap.policy.appc.CommonHeader;
48 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
49 import org.onap.policy.cds.CdsResponse;
50 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
51 import org.onap.policy.cds.properties.CdsServerProperties;
52 import org.onap.policy.drools.utils.Pair;
53 import org.onap.policy.sdnr.PciRequestWrapper;
54 import org.onap.policy.sdnr.PciResponseWrapper;
55 import org.onap.policy.sdnr.PciRequest;
56 import org.onap.policy.sdnr.PciResponse;
57 import org.onap.policy.vfc.VfcRequest;
58 import org.onap.policy.vfc.VfcResponse;
59 import org.onap.policy.vfc.VfcManager;
60 import org.onap.policy.so.SoManager;
61 import org.onap.policy.so.SoRequest;
62 import org.onap.policy.so.SoResponseWrapper;
63 import org.onap.policy.sdnc.SdncRequest;
64 import org.onap.policy.sdnc.SdncManager;
65 import org.onap.policy.sdnc.SdncResponse;
66 import org.onap.policy.drools.core.lock.Lock;
67 import org.onap.policy.guard.PolicyGuardRequest;
68 import org.onap.policy.guard.PolicyGuardResponse;
69 import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes;
70 import org.onap.policy.guard.PolicyGuardXacmlHelper;
72 import org.yaml.snakeyaml.Yaml;
73 import org.yaml.snakeyaml.constructor.Constructor;
75 import org.slf4j.LoggerFactory;
76 import org.slf4j.Logger;
78 import java.time.Instant;
79 import java.util.LinkedList;
80 import java.util.Iterator;
82 import org.onap.policy.drools.system.PolicyEngineConstants;
85 * This structure mimics the Params structure.
86 * Its only purpose is to allow management of
87 * rules by the PAP component..
88 * It has no use at runtime since the rules go by
89 * Params for matching purposes.
92 closedLoopControlName : String
93 controlLoopYaml : String
97 * Control Loop Identity
100 closedLoopControlName : String
101 controlLoopYaml : String
105 * Used to trigger clean up Params that no longer have associated rules.
107 declare ParamsInitCleaner
108 closedLoopControlName : String // only used when logging
112 * Used to clean up Params that no longer have associated rules.
114 declare ParamsCleaner
115 closedLoopControlName : String
116 controlLoopYaml : String
120 * This object is to provide support for timeouts
121 * due to a bug in drools' built-in timers
123 declare ControlLoopTimer
124 closedLoopControlName : String
128 //timerType is the type of timer: either "ClosedLoop" or "Operation"
134 * Called to insert the parameters into working memory for this Closed Loop policy. This is called
135 * once each time a closed loop is added or its YAML is updated.
136 * This has a higher salience so we can ensure that the Params is created before we have a chance to
137 * discard any events.
140 rule "${policyName}.SETUP"
143 not( Params( getClosedLoopControlName() == "${closedLoopControlName}",
144 getControlLoopYaml() == "${controlLoopYaml}" ) )
147 Params params = new Params();
148 params.setClosedLoopControlName("${closedLoopControlName}");
149 params.setControlLoopYaml("${controlLoopYaml}");
152 ParamsInitCleaner initCleaner = new ParamsInitCleaner();
153 initCleaner.setClosedLoopControlName("${closedLoopControlName}");
156 // Note: globals have bad behavior when persistence is used,
157 // hence explicitly getting the logger vs using a global
159 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
160 logger.info("{}: {} : YAML=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(),
161 params.getControlLoopYaml());
166 * This rule responds to DCAE Events where there is no manager yet. Either it is
167 * the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled)
170 rule "${policyName}.EVENT"
172 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
173 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
174 not ( ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
175 requestId == $event.getRequestId() ) )
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.getRequestId() == null) {
189 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
190 notification.setNotification(ControlLoopNotificationType.REJECTED);
191 notification.setFrom("policy");
192 notification.setMessage("Missing requestId");
193 notification.setPolicyName(drools.getRule().getName());
194 notification.setPolicyScope("${policyScope}");
195 notification.setPolicyVersion("${policyVersion}");
198 // Let interested parties know
200 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
203 // Retract it from memory
206 } else if ($event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET) {
207 throw new ControlLoopException($event.getClosedLoopEventStatus() + " received with no prior onset");
210 // Create an EventManager
212 ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(),
213 $event.getRequestId());
215 // Determine if EventManager can actively process the event
216 // (i.e. syntax, is_closed_loop_disabled checks etc.)
218 VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event);
219 notification.setFrom("pdp-0001-controller=controlloop"); // Engine.getInstanceName()
220 notification.setPolicyName(drools.getRule().getName());
221 notification.setPolicyScope("${policyScope}");
222 notification.setPolicyVersion("${policyVersion}");
224 // Are we actively pursuing this event?
226 if (notification.getNotification() == ControlLoopNotificationType.ACTIVE) {
228 // Insert Event Manager into memory, this will now kick off processing.
232 // Let interested parties know
234 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
236 // Setup the Overall Control Loop timer
238 ControlLoopTimer clTimer = new ControlLoopTimer();
239 clTimer.setTimerType("ClosedLoop");
240 clTimer.setClosedLoopControlName($event.getClosedLoopControlName());
241 clTimer.setRequestId($event.getRequestId().toString());
242 clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s");
249 // Let interested parties know
251 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
253 // Retract it from memory
259 // Now that the manager is inserted into Drools working memory, we'll wait for
260 // another rule to fire in order to continue processing. This way we can also
261 // then screen for additional ONSET and ABATED events for this RequestId.
264 } catch (Exception e) {
265 logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
267 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
268 notification.setNotification(ControlLoopNotificationType.REJECTED);
269 notification.setMessage("Exception occurred: " + e.getMessage());
270 notification.setPolicyName(drools.getRule().getName());
271 notification.setPolicyScope("${policyScope}");
272 notification.setPolicyVersion("${policyVersion}");
276 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
286 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
287 * is now created. We can start processing the yaml specification via the Event Manager.
290 rule "${policyName}.EVENT.MANAGER"
292 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
293 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
294 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
295 requestId == $event.getRequestId() )
296 $clTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
297 requestId == $event.getRequestId().toString(), timerType == "ClosedLoop", !expired )
300 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
301 logger.info("{}: {}: event={} manager={} clTimer={}",
302 $params.getClosedLoopControlName(), drools.getRule().getName(),
303 $event, $manager, $clTimer);
307 // Check which event this is.
309 ControlLoopEventManager.NewEventStatus eventStatus = $manager.onNewEvent($event);
311 // Check what kind of event this is
313 if (eventStatus == NewEventStatus.SUBSEQUENT_ONSET) {
315 // We don't care about subsequent onsets
317 logger.info("{}: {}: subsequent onset",
318 $params.getClosedLoopControlName(), drools.getRule().getName());
322 if (eventStatus == NewEventStatus.SYNTAX_ERROR) {
324 // Ignore any bad syntax events
326 logger.warn("{}: {}: syntax error",
327 $params.getClosedLoopControlName(), drools.getRule().getName());
332 // We only want the initial ONSET event in memory,
333 // all the other events need to be retracted to support
334 // cleanup and avoid the other rules being fired for this event.
336 if (eventStatus != NewEventStatus.FIRST_ONSET) {
337 logger.warn("{}: {}: not first onset",
338 $params.getClosedLoopControlName(), drools.getRule().getName());
342 logger.debug("{}: {}: target={}", $params.getClosedLoopControlName(),
343 drools.getRule().getName(), $event.getTarget());
345 // Now start seeing if we need to process this event
349 // Check if this is a Final Event
351 VirtualControlLoopNotification notification = $manager.isControlLoopFinal();
354 if (notification != null) {
356 // Its final, but are we waiting for abatement?
358 if ($manager.getNumAbatements() > 0) {
359 logger.info("{}: {}: abatement received for {}. Closing the control loop",
360 $params.getClosedLoopControlName(), drools.getRule().getName(),
361 $event.getRequestId());
363 /// DB Write---end event processing for this RequestId()
364 $manager.commitAbatement("Event Abated","Closed");
366 notification.setFrom("policy");
367 notification.setPolicyName(drools.getRule().getName());
368 notification.setPolicyScope("${policyScope}");
369 notification.setPolicyVersion("${policyVersion}");
371 // In this case, we are done
373 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
377 Lock lock = $manager.unlockCurrentOperation();
379 logger.debug("{}: {}: retracting lock={}", $params.getClosedLoopControlName(),
380 drools.getRule().getName(), lock);
384 // Retract everything from memory
386 logger.info("{}: {}: retracting onset, manager, and timer",
387 $params.getClosedLoopControlName(), drools.getRule().getName());
389 retract($manager.getOnsetEvent());
391 // don't retract manager, etc. - a clean-up rule will do that
394 // TODO - what if we get subsequent Events for this RequestId?
395 // By default, it will all start over again. May be confusing for Ruby.
396 // Or, we could track this and then subsequently ignore the events
400 // Check whether we need to wait for abatement
402 if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.getNotification() == ControlLoopNotificationType.FINAL_SUCCESS) {
403 logger.info("{}: {}: waiting for abatement ..",
404 $params.getClosedLoopControlName(), drools.getRule().getName());
406 logger.info("{}: {}: no abatement expect for {}. Closing the control loop",
407 $params.getClosedLoopControlName(), drools.getRule().getName(),
408 $event.getRequestId());
410 notification.setFrom("policy");
411 notification.setPolicyName(drools.getRule().getName());
412 notification.setPolicyScope("${policyScope}");
413 notification.setPolicyVersion("${policyVersion}");
416 // In this case, we are done
418 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
422 Lock lock = $manager.unlockCurrentOperation();
424 logger.debug("{}: {}: retracting lock={}", $params.getClosedLoopControlName(),
425 drools.getRule().getName(), lock);
429 // Retract everything from memory
431 logger.info("{}: {}: retracting onset, manager, and timer",
432 $params.getClosedLoopControlName(), drools.getRule().getName());
434 retract($manager.getOnsetEvent());
436 // don't retract manager, etc. - a clean-up rule will do that
441 // NOT final, so let's ask for the next operation
443 ControlLoopOperationManager operation = $manager.processControlLoop();
444 if (operation != null) {
446 // Let's ask for a lock right away
448 logger.info("{}: {}: requesting lock for operation={}",
449 $params.getClosedLoopControlName(), drools.getRule().getName(),
452 Pair<Lock,Lock> oldNew = $manager.lockCurrentOperation(
453 new LockCallbackWorkingMemory($params.getClosedLoopControlName(), drools.getWorkingMemory()));
454 if(oldNew.first() != null) {
455 logger.debug("{}: {}: retracting lock={}", $params.getClosedLoopControlName(),
456 drools.getRule().getName(), oldNew.first());
457 retract(oldNew.first());
459 if(oldNew.second() != null) {
460 logger.debug("{}: {}: inserting lock={}", $params.getClosedLoopControlName(),
461 drools.getRule().getName(), oldNew.second());
462 insert(oldNew.second());
466 // insert the operation into memory
470 // insert operation timeout object
472 ControlLoopTimer opTimer = new ControlLoopTimer();
473 opTimer.setTimerType("Operation");
474 opTimer.setClosedLoopControlName($event.getClosedLoopControlName());
475 opTimer.setRequestId($event.getRequestId().toString());
476 Integer timeout = operation.getOperationTimeout();
477 opTimer.setDelay(timeout > 0 ? timeout.toString() + "s" : $clTimer.getDelay());
482 // Probably waiting for abatement
484 logger.info("{}: {}: no operation, probably waiting for abatement",
485 $params.getClosedLoopControlName(), drools.getRule().getName());
488 } catch (Exception e) {
489 logger.warn("{}: {}: unexpected",
490 $params.getClosedLoopControlName(),
491 drools.getRule().getName(), e);
493 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
494 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
495 notification.setMessage(e.getMessage());
496 notification.setFrom("policy");
497 notification.setPolicyName(drools.getRule().getName());
498 notification.setPolicyScope("${policyScope}");
499 notification.setPolicyVersion("${policyVersion}");
501 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
505 // don't retract manager, etc. - a clean-up rule will do that
515 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCK.DENIED"
517 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
518 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
519 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
520 requestId == $event.getRequestId() )
521 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
522 onset.getRequestId() == $event.getRequestId(), "None".equalsIgnoreCase(getGuardApprovalStatus()) )
523 $lock : Lock (ownerKey == $event.getRequestId().toString(), isUnavailable())
526 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
527 logger.info("{}: {}: event={} manager={} operation={} lock={}",
528 $params.getClosedLoopControlName(), drools.getRule().getName(),
529 $event, $manager, $operation, $lock);
531 logger.debug("The target resource {} is already processing",
532 $event.getAai().get($event.getTarget()));
533 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
534 notification.setNotification(ControlLoopNotificationType.REJECTED);
535 notification.setMessage("The target " + $event.getAai().get($event.getTarget())
536 + " is already locked");
537 notification.setFrom("policy");
538 notification.setPolicyName(drools.getRule().getName());
539 notification.setPolicyScope("${policyScope}");
540 notification.setPolicyVersion("${policyVersion}");
542 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
546 // don't retract manager, etc. - a clean-up rule will do that
551 * Guard Permitted, let's send request to the actor.
554 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED"
556 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
557 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
558 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
559 requestId == $event.getRequestId() )
560 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
561 onset.getRequestId() == $event.getRequestId(), "Permit".equalsIgnoreCase(getGuardApprovalStatus()) )
562 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
563 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
566 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
567 logger.info("{}: {}: event={} manager={} operation={}",
568 $params.getClosedLoopControlName(), drools.getRule().getName(),
569 $event, $manager, $operation);
571 Object request = null;
572 boolean caughtException = false;
575 request = $operation.startOperation($event);
577 if (request != null) {
578 logger.debug("{}: {}: starting operation ..",
579 $params.getClosedLoopControlName(), drools.getRule().getName());
581 // Tell interested parties we are performing this Operation
583 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
584 notification.setNotification(ControlLoopNotificationType.OPERATION);
585 notification.setMessage($operation.getOperationMessage());
586 notification.setHistory($operation.getHistory());
587 notification.setFrom("policy");
588 notification.setPolicyName(drools.getRule().getName());
589 notification.setPolicyScope("${policyScope}");
590 notification.setPolicyVersion("${policyVersion}");
592 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
594 switch ($operation.policy.getActor()){
597 if (request instanceof Request) {
598 PolicyEngineConstants.getManager().deliver("APPC-CL", request);
600 else if (request instanceof AppcLcmDmaapWrapper) {
601 PolicyEngineConstants.getManager().deliver("APPC-LCM-READ", request);
605 // at this point the AAI named query request should have already been made,
606 // the response recieved and used
607 // in the construction of the SO Request which is stored in operationRequest
609 if(request instanceof SoRequest) {
610 // Call SO. The response will be inserted into memory once it's received
611 class mySoCallback implements SoManager.SoCallback {
612 public void onSoResponseWrapper(SoResponseWrapper wrapper) {
613 drools.getWorkingMemory().insert(wrapper);
616 SoActorServiceProvider.sendRequest($event.getRequestId().toString(),
619 PolicyEngineConstants.getManager().getEnvironmentProperty("so.url"),
620 PolicyEngineConstants.getManager().getEnvironmentProperty("so.username"),
621 PolicyEngineConstants.getManager().getEnvironmentProperty("so.password"));
625 if (request instanceof VfcRequest) {
627 class myVfcCallback implements VfcManager.VfcCallback {
629 public void onResponse(VfcResponse responseError) {
630 drools.getWorkingMemory().insert(responseError);
634 Thread t = new Thread(new VfcManager(new myVfcCallback(),
636 PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.url"),
637 PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.username"),
638 PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.password")));
644 if (request instanceof SdncRequest) {
646 class mySdncCallback implements SdncManager.SdncCallback {
647 public void onCallback(SdncResponse response) {
648 drools.getWorkingMemory().insert(response);
652 Thread t = new Thread(new SdncManager(new mySdncCallback(),
653 (SdncRequest)request,
654 PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.url"),
655 PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.username"),
656 PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.password")));
661 if (request instanceof PciRequestWrapper) {
662 PolicyEngineConstants.getManager().deliver("SDNR-CL", request);
668 if(request instanceof ExecutionServiceInput) {
670 // Instantiate cds actor, service manager and grpc properties
672 CdsActorServiceProvider cdsActor = new CdsActorServiceProvider();
673 CdsActorServiceProvider.CdsActorServiceManager cdsActorServiceManager = cdsActor.new CdsActorServiceManager();
675 CdsServerProperties props = new CdsServerProperties();
676 props.setHost(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcHost"));
677 props.setPort(Integer.parseInt(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcPort")));
678 props.setUsername(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcUsername"));
679 props.setPassword(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcPassword"));
680 props.setTimeout(Integer.parseInt(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcTimeout")));
682 // Send cds grpc request
683 try (CdsProcessorGrpcClient client = new CdsProcessorGrpcClient(cdsActorServiceManager, props)) {
684 CdsResponse response =
685 cdsActorServiceManager.sendRequestToCds(client, props, (ExecutionServiceInput) request);
686 logger.info("CDS response: {}", response);
696 // What happens if its null?
698 logger.warn("{}: {}: unexpected null operation request",
699 $params.getClosedLoopControlName(),
700 drools.getRule().getName());
701 if ("SO".equals($operation.policy.getActor())) {
704 modify($manager) {finishOperation($operation)};
706 else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) {
709 modify($manager) {finishOperation($operation)};
711 else if ("sdnc".equalsIgnoreCase($operation.policy.getActor())) {
714 modify($manager) {finishOperation($operation)};
718 } catch (Exception e) {
719 String msg = e.getMessage();
720 logger.warn("{}: {}: operation={}: AAI failure: {}",
721 $params.getClosedLoopControlName(), drools.getRule().getName(),
723 $operation.setOperationHasException(msg);
725 if(request != null) {
727 // Create a notification for it ("DB Write - end operation")
729 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
730 notification.setFrom("policy");
731 notification.setPolicyName(drools.getRule().getName());
732 notification.setPolicyScope("${policyScope}");
733 notification.setPolicyVersion("${policyVersion}");
734 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
735 notification.setMessage($operation.getOperationHistory());
736 notification.setHistory($operation.getHistory());
738 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
743 caughtException = true;
746 // Having the modify statement in the catch clause doesn't work for whatever reason
747 if (caughtException) {
748 modify($manager) {finishOperation($operation)};
755 * We were able to acquire a lock so now let's ask Xacml Guard whether
756 * we are allowed to proceed with the request to the actor.
759 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
761 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
762 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
763 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
764 requestId == $event.getRequestId() )
765 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
766 onset.getRequestId() == $event.getRequestId(), "None".equalsIgnoreCase(getGuardApprovalStatus()) )
767 $lock : Lock (ownerKey == $event.getRequestId().toString(), isActive())
770 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
771 logger.info("{}: {}: event={} manager={} operation={} lock={}",
772 $params.getClosedLoopControlName(), drools.getRule().getName(),
773 $event, $manager, $operation, $lock);
776 // Sending notification that we are about to query Guard ("DB write - start operation")
778 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
779 notification.setNotification(ControlLoopNotificationType.OPERATION);
780 notification.setMessage("Sending guard query for " + $operation.policy.getActor() + " "
781 + $operation.policy.getRecipe());
782 notification.setHistory($operation.getHistory());
783 notification.setFrom("policy");
784 notification.setPolicyName(drools.getRule().getName());
785 notification.setPolicyScope("${policyScope}");
786 notification.setPolicyVersion("${policyVersion}");
788 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
791 // Now send Guard Request to XACML Guard. In order to bypass the call to Guard,
792 // just change guardEnabled to false.
794 // In order to use REST XACML, provide a URL instead of "" as a second argument
795 // to the CallGuardTask() and set the first argument to null
796 // (instead of XacmlPdpEngine).
799 // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled
800 boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngineConstants.getManager().getEnvironmentProperty("guard.disabled"));
801 boolean cqEnabled = "true".equalsIgnoreCase(PolicyEngineConstants.getManager().getEnvironmentProperty("aai.customQuery"));
805 Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
806 drools.getWorkingMemory(),
807 $event.getClosedLoopControlName(),
808 $operation.policy.getActor().toString(),
809 $operation.policy.getRecipe(),
810 $operation.getTargetEntity(),
811 $event.getRequestId().toString(),
814 AaiNqResponseWrapper resp = $manager.getNqVserverFromAai();
815 return(resp == null ? null : resp.countVfModules());
818 AaiCqResponse resp_cq = $manager.getCqResponse($event);
819 if (resp_cq == null){
822 String custId = $operation.policy.getTarget().getModelCustomizationId();
823 String invId = $operation.policy.getTarget().getModelInvariantId();
824 String verId = $operation.policy.getTarget().getModelVersionId();
825 return resp_cq.getVfModuleCount(custId, invId, verId);
827 } catch (Exception e){
828 logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
836 insert(new PolicyGuardResponse("Permit", $event.getRequestId(), $operation.policy.getRecipe()));
842 // This rule will be triggered when a thread talking to the XACML Guard inserts a
843 // guardResponse object into the working memory
845 rule "${policyName}.GUARD.RESPONSE"
847 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
848 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
849 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
850 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
851 requestId == $event.getRequestId() )
852 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
853 onset.getRequestId() == $event.getRequestId() )
854 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
855 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
856 $guardResponse : PolicyGuardResponse(requestId == $event.getRequestId(), $operation.policy.recipe == operation)
859 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
860 logger.info("{}: {}: event={} manager={} operation={} opTimer={} guardResponse={}",
861 $params.getClosedLoopControlName(), drools.getRule().getName(),
862 $event, $manager, $operation, $opTimer, $guardResponse);
865 //we will permit the operation if there was no Guard for it
866 if("Indeterminate".equalsIgnoreCase($guardResponse.getResult())){
867 $guardResponse.setResult("Permit");
871 // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
873 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
874 notification.setNotification(ControlLoopNotificationType.OPERATION);
875 notification.setMessage("Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe()
876 + " is " + $guardResponse.getResult());
877 notification.setHistory($operation.getHistory());
878 notification.setFrom("policy");
879 notification.setPolicyName(drools.getRule().getName());
880 notification.setPolicyScope("${policyScope}");
881 notification.setPolicyVersion("${policyVersion}");
883 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
885 if("Permit".equalsIgnoreCase($guardResponse.getResult())){
887 modify($operation){setGuardApprovalStatus($guardResponse.getResult())};
890 //This is the Deny case
891 $operation.startOperation($event);
892 $operation.setOperationHasGuardDeny();
895 modify($manager) {finishOperation($operation)};
898 retract($guardResponse);
904 * This rule responds to APPC Response Events
906 * I would have like to be consistent and write the Response like this:
907 * $response : Response( CommonHeader.RequestId == $onset.getRequestId() )
909 * However, no compile error was given. But a runtime error was given. I think
910 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
913 rule "${policyName}.APPC.RESPONSE"
915 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
916 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
917 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
918 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
919 requestId == $event.getRequestId() )
920 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
921 onset.getRequestId() == $event.getRequestId() )
922 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
923 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
924 $response : Response( getCommonHeader().RequestId == $event.getRequestId() )
927 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
928 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
929 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
930 $params.getClosedLoopControlName(), drools.getRule().getName(),
931 $event, $manager, $operation, $opTimer, $response);
933 // Get the result of the operation
935 PolicyResult policyResult = $operation.onResponse($response);
936 if (policyResult != null) {
937 logger.debug("{}: {}: operation finished - result={}",
938 $params.getClosedLoopControlName(), drools.getRule().getName(),
941 // This Operation has completed, construct a notification showing our results. (DB write - end operation)
943 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
944 notification.setFrom("policy");
945 notification.setPolicyName(drools.getRule().getName());
946 notification.setPolicyScope("${policyScope}");
947 notification.setPolicyVersion("${policyVersion}");
948 notification.setMessage($operation.getOperationHistory());
949 notification.setHistory($operation.getHistory());
950 if (policyResult.equals(PolicyResult.SUCCESS)) {
951 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
953 // Let interested parties know
955 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
957 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
959 // Let interested parties know
961 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
964 // Ensure the operation is complete
966 if ($operation.isOperationComplete() == true) {
968 // It is complete, remove it from memory
972 // We must also retract the timer object
973 // NOTE: We could write a Rule to do this
977 // Complete the operation
979 modify($manager) {finishOperation($operation)};
982 // Just doing this will kick off the LOCKED rule again
984 modify($operation) {};
988 // Its not finished yet (i.e. expecting more Response objects)
990 // Or possibly it is a leftover response that we timed the request out previously
994 // We are going to retract these objects from memory
1001 * The problem with Responses is that they don't have a controlLoopControlName
1002 * field in them, so the only way to attach them is via RequestId. If we have multiple
1003 * control loop .drl's loaded in the same container, we need to be sure the cleanup
1004 * rules don't remove Responses for other control loops.
1007 rule "${policyName}.APPC.RESPONSE.CLEANUP"
1009 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1010 $response : Response($id : getCommonHeader().RequestId )
1011 not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
1014 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1015 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1016 logger.debug("{}: {}: orphan appc response={}",
1017 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
1027 * This rule responds to APPC Response Events using the new LCM interface provided by appc
1030 rule "${policyName}.APPC.LCM.RESPONSE"
1032 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1033 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1034 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1035 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1036 requestId == $event.getRequestId() )
1037 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1038 onset.getRequestId() == $event.getRequestId() )
1039 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1040 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1041 $response : AppcLcmDmaapWrapper( getBody().getOutput().getCommonHeader().getRequestId() == $event.getRequestId() )
1044 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1045 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1046 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1047 $params.getClosedLoopControlName(), drools.getRule().getName(),
1048 $event, $manager, $operation, $operation, $opTimer, $response);
1051 // Get the result of the operation
1053 PolicyResult policyResult = $operation.onResponse($response);
1054 if (policyResult != null) {
1055 logger.debug("{}: {}: operation finished - result={}",
1056 $params.getClosedLoopControlName(), drools.getRule().getName(),
1060 // This Operation has completed, construct a notification showing our results. (DB write - end operation)
1062 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1063 notification.setFrom("policy");
1064 notification.setPolicyName(drools.getRule().getName());
1065 notification.setPolicyScope("${policyScope}");
1066 notification.setPolicyVersion("${policyVersion}");
1067 notification.setMessage($operation.getOperationHistory());
1068 notification.setHistory($operation.getHistory());
1069 if (policyResult.equals(PolicyResult.SUCCESS)) {
1070 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1072 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1074 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1076 // Ensure the operation is complete
1078 if ($operation.isOperationComplete() == true) {
1080 // It is complete, remove it from memory
1082 retract($operation);
1084 // We must also retract the timer object
1085 // NOTE: We could write a Rule to do this
1089 // Complete the operation
1091 modify($manager) {finishOperation($operation)};
1094 // Just doing this will kick off the LOCKED rule again
1096 modify($operation) {};
1100 // Its not finished yet (i.e. expecting more Response objects)
1102 // Or possibly it is a leftover response that we timed the request out previously
1106 // We are going to retract these objects from memory
1113 * Clean Up any lingering LCM reponses
1116 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
1118 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1119 $response : AppcLcmDmaapWrapper($id : getBody().getOutput().getCommonHeader().getRequestId() )
1120 not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
1123 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1124 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1125 logger.debug("{}: {}: orphan appc response={}",
1126 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
1135 * This rule responds to SDNR Response Events using the new interface provided by SDNR
1138 rule "${policyName}.SDNR.RESPONSE"
1140 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1141 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1142 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1143 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1144 requestId == $event.getRequestId() )
1145 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1146 onset.getRequestId() == $event.getRequestId() )
1147 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1148 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1149 $response : PciResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.getRequestId() )
1152 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1153 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1154 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1155 $params.getClosedLoopControlName(), drools.getRule().getName(),
1156 $event, $manager, $operation, $operation, $opTimer, $response);
1159 // Get the result of the operation
1161 PolicyResult policyResult = $operation.onResponse($response);
1162 if (policyResult != null) {
1163 logger.debug("{}: {}: operation finished - result={}",
1164 $params.getClosedLoopControlName(), drools.getRule().getName(),
1168 // This Operation has completed, construct a notification showing our results. (DB write - end operation)
1170 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1171 notification.setFrom("policy");
1172 notification.setPolicyName(drools.getRule().getName());
1173 notification.setPolicyScope("${policyScope}");
1174 notification.setPolicyVersion("${policyVersion}");
1175 notification.setMessage($operation.getOperationHistory());
1176 notification.setHistory($operation.getHistory());
1177 if (policyResult.equals(PolicyResult.SUCCESS)) {
1178 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1180 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1182 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1184 // Ensure the operation is complete
1186 if ($operation.isOperationComplete()) {
1188 // It is complete, remove it from memory
1190 retract($operation);
1192 // We must also retract the timer object
1193 // NOTE: We could write a Rule to do this
1197 // Complete the operation
1199 modify($manager) {finishOperation($operation)};
1202 // Just doing this will kick off the LOCKED rule again
1204 modify($operation) {};
1208 // Its not finished yet (i.e. expecting more Response objects)
1210 // Or possibly it is a leftover response that we timed the request out previously
1214 // We are going to retract these objects from memory
1221 * Clean Up any lingering SDNR reponses
1224 rule "${policyName}.SDNR.RESPONSE.CLEANUP"
1226 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1227 $response : PciResponseWrapper($id : getBody().getCommonHeader().getRequestId )
1228 not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
1231 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1232 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1233 logger.debug("{}: {}: orphan SDNR response={}",
1234 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
1243 * This rule responds to SO Response Events
1246 rule "${policyName}.SO.RESPONSE"
1248 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1249 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1250 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1251 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1252 requestId == $event.getRequestId() )
1253 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1254 onset.getRequestId() == $event.getRequestId() )
1255 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1256 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1257 $response : SoResponseWrapper(requestId.toString() == $event.getRequestId().toString() )
1260 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1261 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1262 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1263 $params.getClosedLoopControlName(), drools.getRule().getName(),
1264 $event, $manager, $operation, $operation, $opTimer, $response);
1266 // Get the result of the operation
1268 PolicyResult policyResult = $operation.onResponse($response);
1269 if (policyResult != null) {
1270 logger.debug("{}: {}: operation finished - result={}",
1271 $params.getClosedLoopControlName(), drools.getRule().getName(),
1275 // This Operation has completed, construct a notification showing our results
1277 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1278 notification.setFrom("policy");
1279 notification.setPolicyName(drools.getRule().getName());
1280 notification.setPolicyScope("${policyScope}");
1281 notification.setPolicyVersion("${policyVersion}");
1282 notification.setMessage($operation.getOperationHistory());
1283 notification.setHistory($operation.getHistory());
1284 if (policyResult.equals(PolicyResult.SUCCESS)) {
1285 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1287 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1290 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1292 // Ensure the operation is complete
1294 if ($operation.isOperationComplete() == true) {
1296 // It is complete, remove it from memory
1298 retract($operation);
1300 // We must also retract the timer object
1301 // NOTE: We could write a Rule to do this
1305 // Complete the operation
1307 modify($manager) {finishOperation($operation)};
1310 // Just doing this will kick off the LOCKED rule again
1312 modify($operation) {};
1316 // Its not finished yet (i.e. expecting more Response objects)
1318 // Or possibly it is a leftover response that we timed the request out previously
1322 // We are going to retract these objects from memory
1330 * This rule responds to VFC Response Events
1333 rule "${policyName}.VFC.RESPONSE"
1335 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1336 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1337 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1338 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1339 requestId == $event.getRequestId() )
1340 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1341 onset.getRequestId() == $event.getRequestId() )
1342 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1343 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1344 $response : VfcResponse( requestId.toString() == $event.getRequestId().toString() )
1346 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1347 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1348 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1349 $params.getClosedLoopControlName(), drools.getRule().getName(),
1350 $event, $manager, $operation, $operation, $opTimer, $response);
1352 // Get the result of the operation
1354 PolicyResult policyResult = $operation.onResponse($response);
1355 if (policyResult != null) {
1357 // This Operation has completed, construct a notification showing our results
1359 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1360 notification.setFrom("policy");
1361 notification.setPolicyName(drools.getRule().getName());
1362 notification.setPolicyScope("${policyScope}");
1363 notification.setPolicyVersion("${policyVersion}");
1364 notification.setMessage($operation.getOperationHistory());
1365 notification.setHistory($operation.getHistory());
1367 // Ensure the operation is complete
1369 if ($operation.isOperationComplete() == true) {
1371 // It is complete, remove it from memory
1373 retract($operation);
1375 // We must also retract the timer object
1376 // NOTE: We could write a Rule to do this
1380 // Complete the operation
1382 modify($manager) {finishOperation($operation)};
1385 // Just doing this will kick off the LOCKED rule again
1387 modify($operation) {};
1391 // Its not finished yet (i.e. expecting more Response objects)
1393 // Or possibly it is a leftover response that we timed the request out previously
1397 // We are going to retract these objects from memory
1405 * This rule responds to SDNC Response Events
1409 rule "${policyName}.SDNC.RESPONSE"
1411 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1412 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1413 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1414 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1415 requestId == $event.getRequestId() )
1416 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1417 onset.getRequestId() == $event.getRequestId() )
1418 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1419 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1420 $response : SdncResponse( requestId.toString() == $event.getRequestId().toString() )
1422 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1423 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1424 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1425 $params.getClosedLoopControlName(), drools.getRule().getName(),
1426 $event, $manager, $operation, $operation, $opTimer, $response);
1428 // Get the result of the operation
1430 PolicyResult policyResult = $operation.onResponse($response);
1431 if (policyResult != null) {
1433 // This Operation has completed, construct a notification showing our results
1435 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1436 notification.setFrom("policy");
1437 notification.setPolicyName(drools.getRule().getName());
1438 notification.setPolicyScope("${policyScope}");
1439 notification.setPolicyVersion("${policyVersion}");
1440 notification.setMessage($operation.getOperationHistory());
1441 notification.setHistory($operation.getHistory());
1443 // Ensure the operation is complete
1445 if ($operation.isOperationComplete()) {
1447 // It is complete, remove it from memory
1449 retract($operation);
1451 // We must also retract the timer object
1452 // NOTE: We could write a Rule to do this
1456 // Complete the operation
1458 modify($manager) {finishOperation($operation)};
1461 // Just doing this will kick off the LOCKED rule again
1463 modify($operation) {};
1467 // Its not finished yet (i.e. expecting more Response objects)
1469 // Or possibly it is a leftover response that we timed the request out previously
1473 // We are going to retract these objects from memory
1481 * This rule responds to CDS Response Events
1483 rule "${policyName}.CDS.RESPONSE"
1485 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1486 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1487 closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1488 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1489 requestId == $event.getRequestId() )
1490 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1491 onset.getRequestId() == $event.getRequestId() )
1492 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1493 requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1494 $response : CdsResponse( requestId == $event.getRequestId().toString() )
1498 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1499 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1500 logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1501 $params.getClosedLoopControlName(), drools.getRule().getName(),
1502 $event, $manager, $operation, $operation, $opTimer, $response);
1504 // Get the result of the operation
1505 PolicyResult policyResult = $operation.onResponse($response);
1507 if (policyResult != null) {
1508 logger.debug("{}: {}: operation finished - result={}",
1509 $params.getClosedLoopControlName(), drools.getRule().getName(),
1512 // The operation has completed, construct a notification showing our results
1513 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1514 notification.setFrom("policy");
1515 notification.setPolicyName(drools.getRule().getName());
1516 notification.setPolicyScope("${policyScope}");
1517 notification.setPolicyVersion("${policyVersion}");
1518 notification.setMessage($operation.getOperationHistory());
1519 notification.setHistory($operation.getHistory());
1520 notification.setNotification(
1521 ($response != null && CdsActorConstants.SUCCESS.equals($response.getStatus()))
1522 ? ControlLoopNotificationType.OPERATION_SUCCESS : ControlLoopNotificationType.OPERATION_FAILURE);
1524 // Send the notification
1525 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1527 // Ensure the operation is complete
1528 if ($operation.isOperationComplete()) {
1530 // It is complete, remove it from memory
1531 retract($operation);
1533 // We must also retract the timer object
1534 // NOTE: We could write a Rule to do this
1537 // Complete the operation
1538 modify($manager) {finishOperation($operation)};
1541 // Just doing this will kick off the LOCKED rule again
1542 modify($operation) {};
1545 // Its not finished yet (i.e. expecting more Response objects)
1546 // Or possibly it is a leftover response that we timed the request out previously
1548 "policyResult is null"
1549 + "\nIt's not finished yet (i.e. expecting more Response objects)"
1550 + "\nOr possibly it is a leftover response that we timed the request out previously");
1553 // We are going to retract these objects from memory
1560 * This manages a single timer.
1561 * Due to a bug in the drools code, the drools timer needed to be split from most of the objects in the when clause
1564 rule "${policyName}.TIMER.FIRED"
1565 timer (expr: $timeout)
1567 $timer : ControlLoopTimer($timeout : delay, !expired)
1569 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1570 logger.info("This is ${policyName}.TIMER.FIRED");
1571 modify($timer){setExpired(true)};
1576 * This is the timer that manages the timeout for an individual operation.
1579 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
1581 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1582 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1583 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1584 requestId == $event.getRequestId() )
1585 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1586 onset.getRequestId() == $event.getRequestId() )
1587 $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1588 requestId == $event.getRequestId().toString(), expired, timerType == "Operation" )
1591 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1592 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1593 logger.debug("{}: {}: event={} manager={} operation={} opTimer={}",
1594 $params.getClosedLoopControlName(), drools.getRule().getName(),
1595 $event, $manager, $operation, $operation, $opTimer);
1598 // Tell it it has timed out
1600 $operation.setOperationHasTimedOut();
1602 // Create a notification for it ("DB Write - end operation")
1604 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1605 notification.setFrom("policy");
1606 notification.setPolicyName(drools.getRule().getName());
1607 notification.setPolicyScope("${policyScope}");
1608 notification.setPolicyVersion("${policyVersion}");
1609 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1610 notification.setMessage($operation.getOperationHistory());
1611 notification.setHistory($operation.getHistory());
1613 // Let interested parties know
1615 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1617 // Get rid of the timer
1621 // Ensure the operation is complete
1623 if ($operation.isOperationComplete() == true) {
1625 // It is complete, remove it from memory
1627 retract($operation);
1629 // Complete the operation
1631 modify($manager) {finishOperation($operation)};
1634 // Just doing this will kick off the LOCKED rule again
1636 modify($operation) {};
1642 * This is the timer that manages the overall control loop timeout.
1645 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
1647 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1648 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1649 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1650 requestId == $event.getRequestId() )
1651 $clTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1652 requestId == $event.getRequestId().toString(), expired, timerType == "ClosedLoop" )
1655 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1656 logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1658 logger.debug("{}: {}: event={}",
1659 $params.getClosedLoopControlName(), drools.getRule().getName(),
1662 // Tell the Event Manager it has timed out
1664 VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
1665 if (notification != null) {
1666 notification.setFrom("policy");
1667 notification.setPolicyName(drools.getRule().getName());
1668 notification.setPolicyScope("${policyScope}");
1669 notification.setPolicyVersion("${policyVersion}");
1671 // Let interested parties know
1673 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1676 // Retract the event
1683 * This rule cleans up the manager and other objects after an event has
1687 rule "${policyName}.EVENT.MANAGER.CLEANUP"
1689 $manager : ControlLoopEventManager( $clName : getClosedLoopControlName(), $requestId : getRequestId() )
1690 $operations : LinkedList()
1691 from collect( ControlLoopOperationManager( onset.closedLoopControlName == $clName,
1692 onset.getRequestId() == $requestId ) )
1693 $timers : LinkedList()
1694 from collect( ControlLoopTimer( closedLoopControlName == $clName,
1695 requestId == $requestId.toString() ) )
1696 not( VirtualControlLoopEvent( closedLoopControlName == $clName, requestId == $requestId ) )
1699 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1700 logger.info("{}: {}", $clName, drools.getRule().getName());
1702 logger.debug("{}: {}: manager={} timers={} operations={}",
1703 $clName, drools.getRule().getName(),
1704 $manager, $timers.size(), $operations.size());
1707 // Retract lock by invoking unlock()
1709 Lock lock = $manager.unlockCurrentOperation();
1715 // Retract EVERYTHING
1720 for(Object manager: $operations) {
1721 retract((ControlLoopOperationManager) manager);
1723 for(Object timer: $timers) {
1724 retract((ControlLoopTimer) timer);
1730 * This rule will clean up any rogue onsets where there is no
1731 * ControlLoopParams object corresponding to the onset event.
1734 rule "${policyName}.EVENT.CLEANUP"
1736 $event : VirtualControlLoopEvent( $clName: closedLoopControlName )
1737 not ( Params( getClosedLoopControlName() == $clName) )
1740 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1741 logger.info("{}: {}", $clName, drools.getRule().getName());
1742 logger.debug("{}: {}: orphan onset event={}",
1743 $clName, drools.getRule().getName(), $event);
1749 * Creates a cleaner for every Params object.
1750 * This has a higher salience so that it is fired before PARAMS.FINISHED in ANY policy.
1752 rule "${policyName}.PARAMS.CLEANING"
1756 ParamsInitCleaner( )
1759 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1760 logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(),
1761 $params.getControlLoopYaml());
1763 ParamsCleaner cleaner = new ParamsCleaner();
1764 cleaner.setClosedLoopControlName($params.getClosedLoopControlName());
1765 cleaner.setControlLoopYaml($params.getControlLoopYaml());
1770 * Finished creating cleaner objects, so remove the trigger.
1771 * This has a higher salience so that it is fired before processing any events.
1773 rule "${policyName}.PARAMS.FINISHED"
1776 $initCleaner: ParamsInitCleaner( )
1779 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1780 logger.info("{}: {}", $initCleaner.getClosedLoopControlName(), drools.getRule().getName());
1782 retract($initCleaner);
1786 * Identifies Params objects that are still active, removing their associated cleaners.
1787 * This should only leave one active Params object for each policy.
1788 * This has a higher salience so that it is fired before PARAMS.DELETE in ANY policy.
1790 rule "${policyName}.PARAMS.ACTIVE"
1793 $params: Params( getClosedLoopControlName() == "${closedLoopControlName}",
1794 getControlLoopYaml() == "${controlLoopYaml}" )
1795 $cleaner: ParamsCleaner( getClosedLoopControlName() == "${closedLoopControlName}",
1796 getControlLoopYaml() == "${controlLoopYaml}" )
1799 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1800 logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(),
1801 $params.getControlLoopYaml());
1807 * Delete Params objects that are not active (i.e., those that still have an associated
1809 * This has a higher salience so that it is fired before PARAMS.CLEANED in ANY policy.
1811 rule "${policyName}.PARAMS.DELETE"
1815 $cleaner: ParamsCleaner( getClosedLoopControlName() == $params.getClosedLoopControlName(),
1816 getControlLoopYaml() == $params.getControlLoopYaml() )
1819 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1820 logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(),
1821 $params.getControlLoopYaml());
1827 * Finished clean-up, so delete the cleaner objects.
1828 * This has a higher salience so that it is fired before processing any events.
1830 rule "${policyName}.PARAMS.CLEANED"
1833 $cleaner: ParamsCleaner( )
1836 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1837 logger.info("{}: {} : YAML=[{}]", $cleaner.getClosedLoopControlName(), drools.getRule().getName(),
1838 $cleaner.getControlLoopYaml());