91fc2228587c82a9d73dfaf34aa22d45e30c0b43
[policy/drools-applications.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.policy.controlloop;
23
24 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
25
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.ControlLoopNotificationType;
30 import org.onap.policy.controlloop.ControlLoopLogger;
31 import org.onap.policy.controlloop.policy.PolicyResult;
32 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
33 import org.onap.policy.controlloop.policy.Policy;
34 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
35 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NewEventStatus;
36 import org.onap.policy.controlloop.eventmanager.ControlLoopOperationManager;
37 import org.onap.policy.controlloop.eventmanager.LockCallbackWorkingMemory;
38 import org.onap.policy.controlloop.actor.so.SoActorServiceProvider;
39 import org.onap.policy.controlloop.actor.cds.CdsActorServiceProvider;
40 import org.onap.policy.controlloop.actor.cds.CdsActorServiceProvider.CdsActorServiceManager;
41 import org.onap.policy.controlloop.actor.cds.constants.CdsActorConstants;
42 import org.onap.policy.aai.AaiNqResponseWrapper;
43 import org.onap.policy.aai.AaiCqResponse;
44 import org.onap.policy.appc.Request;
45 import org.onap.policy.appc.Response;
46 import org.onap.policy.appc.CommonHeader;
47 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
48 import org.onap.policy.cds.CdsResponse;
49 import org.onap.policy.cds.client.CdsProcessorGrpcClient;
50 import org.onap.policy.cds.properties.CdsServerProperties;
51 import org.onap.policy.drools.utils.Pair;
52 import org.onap.policy.sdnr.PciRequestWrapper;
53 import org.onap.policy.sdnr.PciResponseWrapper;
54 import org.onap.policy.sdnr.PciRequest;
55 import org.onap.policy.sdnr.PciResponse;
56 import org.onap.policy.vfc.VfcRequest;
57 import org.onap.policy.vfc.VfcResponse;
58 import org.onap.policy.vfc.VfcManager;
59 import org.onap.policy.so.SoManager;
60 import org.onap.policy.so.SoRequest;
61 import org.onap.policy.so.SoResponseWrapper;
62 import org.onap.policy.sdnc.SdncRequest;
63 import org.onap.policy.sdnc.SdncManager;
64 import org.onap.policy.sdnc.SdncResponse;
65 import org.onap.policy.drools.core.lock.Lock;
66 import org.onap.policy.guard.PolicyGuardRequest;
67 import org.onap.policy.guard.PolicyGuardResponse;
68 import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes;
69 import org.onap.policy.guard.PolicyGuardXacmlHelper;
70
71 import org.yaml.snakeyaml.Yaml;
72 import org.yaml.snakeyaml.constructor.Constructor;
73
74 import org.slf4j.LoggerFactory;
75 import org.slf4j.Logger;
76
77 import java.time.Instant;
78 import java.util.LinkedList;
79 import java.util.Iterator;
80
81 import org.onap.policy.drools.system.PolicyEngineConstants;
82
83 /*
84  * This structure mimics the Params structure.
85  * Its only purpose is to allow management of
86  * rules by the PAP component..
87  * It has no use at runtime since the rules go by
88  * Params for matching purposes.
89  */
90 declare PapParams
91   closedLoopControlName : String
92   controlLoopYaml : String
93 end
94
95 /*
96  * Control Loop Identity
97  */
98 declare Params
99   closedLoopControlName : String
100   controlLoopYaml : String
101 end
102
103 /*
104  * Used to trigger clean up Params that no longer have associated rules.
105  */
106 declare ParamsInitCleaner
107   closedLoopControlName : String    // only used when logging
108 end
109
110 /*
111  * Used to clean up Params that no longer have associated rules.
112  */
113 declare ParamsCleaner
114   closedLoopControlName : String
115   controlLoopYaml : String
116 end
117
118 /*
119  * This object is to provide support for timeouts
120  * due to a bug in drools' built-in timers
121  */
122 declare ControlLoopTimer
123     closedLoopControlName : String
124     requestId : String
125     delay : String
126     expired : boolean
127     //timerType is the type of timer: either "ClosedLoop" or "Operation"
128     timerType : String
129 end
130
131 /*
132 *
133 * Called to insert the parameters into working memory for this Closed Loop policy.  This is called
134 * once each time a closed loop is added or its YAML is updated.
135 * This has a higher salience so we can ensure that the Params is created before we have a chance to
136 * discard any events.
137 *
138 */
139 rule "${policyName}.SETUP"
140     salience 1
141     when
142         not( Params( getClosedLoopControlName() == "${closedLoopControlName}",
143             getControlLoopYaml() == "${controlLoopYaml}" ) )
144     then
145
146     Params params = new Params();
147     params.setClosedLoopControlName("${closedLoopControlName}");
148     params.setControlLoopYaml("${controlLoopYaml}");
149     insert(params);
150
151     ParamsInitCleaner initCleaner = new ParamsInitCleaner();
152     initCleaner.setClosedLoopControlName("${closedLoopControlName}");
153     insert(initCleaner);
154
155     // Note: globals have bad behavior when persistence is used,
156     //       hence explicitly getting the logger vs using a global
157
158     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
159     logger.info("{}: {} : YAML=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(),
160         params.getControlLoopYaml());
161 end
162
163 /*
164 *
165 * This rule responds to DCAE Events where there is no manager yet. Either it is
166 * the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled)
167 *
168 */
169 rule "${policyName}.EVENT"
170     when
171         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
172         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
173         not ( ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
174             requestId == $event.getRequestId() ) )
175     then
176
177     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
178     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
179
180     try {
181
182         //
183         // Check the event, because we need it to not be null when
184         // we create the ControlLoopEventManager. The ControlLoopEventManager
185         // will do extra syntax checking as well check if the closed loop is disabled.
186         //
187         if ($event.getRequestId() == null) {
188             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
189             notification.setNotification(ControlLoopNotificationType.REJECTED);
190             notification.setFrom("policy");
191             notification.setMessage("Missing requestId");
192             notification.setPolicyName(drools.getRule().getName());
193             notification.setPolicyScope("${policyScope}");
194             notification.setPolicyVersion("${policyVersion}");
195
196             //
197             // Let interested parties know
198             //
199             PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
200
201             //
202             // Retract it from memory
203             //
204             retract($event);
205         } else if ($event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET) {
206             throw new ControlLoopException($event.getClosedLoopEventStatus() + " received with no prior onset");
207         } else {
208             //
209             // Create an EventManager
210             //
211             ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(),
212                 $event.getRequestId());
213             //
214             // Determine if EventManager can actively process the event
215             // (i.e. syntax, is_closed_loop_disabled checks etc.)
216             //
217             VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event);
218             notification.setFrom("pdp-0001-controller=controlloop"); // Engine.getInstanceName()
219             notification.setPolicyName(drools.getRule().getName());
220             notification.setPolicyScope("${policyScope}");
221             notification.setPolicyVersion("${policyVersion}");
222             //
223             // Are we actively pursuing this event?
224             //
225             if (notification.getNotification() == ControlLoopNotificationType.ACTIVE) {
226                 //
227                 // Insert Event Manager into memory, this will now kick off processing.
228                 //
229                 insert(manager);
230                 //
231                 // Let interested parties know
232                 //
233                 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
234                 //
235                 // Setup the Overall Control Loop timer
236                 //
237                 ControlLoopTimer clTimer = new ControlLoopTimer();
238                 clTimer.setTimerType("ClosedLoop");
239                 clTimer.setClosedLoopControlName($event.getClosedLoopControlName());
240                 clTimer.setRequestId($event.getRequestId().toString());
241                 clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s");
242                 //
243                 // Insert it
244                 //
245                 insert(clTimer);
246             } else {
247                 //
248                 // Let interested parties know
249                 //
250                 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
251                 //
252                 // Retract it from memory
253                 //
254                 retract($event);
255             }
256
257             //
258             // Now that the manager is inserted into Drools working memory, we'll wait for
259             // another rule to fire in order to continue processing. This way we can also
260             // then screen for additional ONSET and ABATED events for this RequestId.
261             //
262         }
263     } catch (Exception e) {
264         logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
265
266         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
267         notification.setNotification(ControlLoopNotificationType.REJECTED);
268         notification.setMessage("Exception occurred: " + e.getMessage());
269         notification.setPolicyName(drools.getRule().getName());
270         notification.setPolicyScope("${policyScope}");
271         notification.setPolicyVersion("${policyVersion}");
272         //
273         //
274         //
275         PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
276         //
277         // Retract the event
278         //
279         retract($event);
280     }
281 end
282
283 /*
284 *
285 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
286 * is now created. We can start processing the yaml specification via the Event Manager.
287 *
288 */
289 rule "${policyName}.EVENT.MANAGER"
290     when
291         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
292         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
293         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
294             requestId == $event.getRequestId() )
295         $clTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
296             requestId == $event.getRequestId().toString(), timerType == "ClosedLoop", !expired )
297     then
298
299     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
300     logger.info("{}: {}: event={} manager={} clTimer={}",
301                 $params.getClosedLoopControlName(), drools.getRule().getName(),
302                 $event, $manager, $clTimer);
303
304     try {
305         //
306         // Check which event this is.
307         //
308         ControlLoopEventManager.NewEventStatus eventStatus = $manager.onNewEvent($event);
309         //
310         // Check what kind of event this is
311         //
312         if (eventStatus == NewEventStatus.SUBSEQUENT_ONSET) {
313             //
314             // We don't care about subsequent onsets
315             //
316             logger.info("{}: {}: subsequent onset",
317                         $params.getClosedLoopControlName(), drools.getRule().getName());
318             retract($event);
319             return;
320         }
321         if (eventStatus == NewEventStatus.SYNTAX_ERROR) {
322             //
323             // Ignore any bad syntax events
324             //
325             logger.warn("{}: {}: syntax error",
326                         $params.getClosedLoopControlName(), drools.getRule().getName());
327             retract($event);
328             return;
329         }
330         //
331         // We only want the initial ONSET event in memory,
332         // all the other events need to be retracted to support
333         // cleanup and avoid the other rules being fired for this event.
334         //
335         if (eventStatus != NewEventStatus.FIRST_ONSET) {
336             logger.warn("{}: {}: not first onset",
337                         $params.getClosedLoopControlName(), drools.getRule().getName());
338             retract($event);
339         }
340
341         logger.debug("{}: {}: target={}", $params.getClosedLoopControlName(),
342                      drools.getRule().getName(), $event.getTarget());
343         //
344         // Now start seeing if we need to process this event
345         //
346
347         //
348         // Check if this is a Final Event
349         //
350         VirtualControlLoopNotification notification = $manager.isControlLoopFinal();
351
352
353         if (notification != null) {
354             //
355             // Its final, but are we waiting for abatement?
356             //
357             if ($manager.getNumAbatements() > 0) {
358                 logger.info("{}: {}: abatement received for {}.  Closing the control loop",
359                             $params.getClosedLoopControlName(), drools.getRule().getName(),
360                             $event.getRequestId());
361
362                 /// DB Write---end event processing for this RequestId()
363                 $manager.commitAbatement("Event Abated","Closed");
364
365                 notification.setFrom("policy");
366                 notification.setPolicyName(drools.getRule().getName());
367                 notification.setPolicyScope("${policyScope}");
368                 notification.setPolicyVersion("${policyVersion}");
369                 //
370                 // In this case, we are done
371                 //
372                 PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
373                 //
374                 // Unlock the target
375                 //
376                 Lock lock = $manager.unlockCurrentOperation();
377                 if(lock != null) {
378                     logger.debug("{}: {}: retracting lock={}", $params.getClosedLoopControlName(),
379                                 drools.getRule().getName(), lock);
380                     retract(lock);
381                 }
382                 //
383                 // Retract everything from memory
384                 //
385                 logger.info("{}: {}: retracting onset, manager, and timer",
386                             $params.getClosedLoopControlName(), drools.getRule().getName());
387
388                 retract($manager.getOnsetEvent());
389
390                 // don't retract manager, etc. - a clean-up rule will do that
391
392                 //
393                 // TODO - what if we get subsequent Events for this RequestId?
394                 // By default, it will all start over again. May be confusing for Ruby.
395                 // Or, we could track this and then subsequently ignore the events
396                 //
397             } else {
398                 //
399                 // Check whether we need to wait for abatement
400                 //
401                 if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.getNotification() == ControlLoopNotificationType.FINAL_SUCCESS) {
402                   logger.info("{}: {}: waiting for abatement ..",
403                               $params.getClosedLoopControlName(), drools.getRule().getName());
404                 } else {
405                   logger.info("{}: {}: no abatement expect for {}.  Closing the control loop",
406                               $params.getClosedLoopControlName(), drools.getRule().getName(),
407                               $event.getRequestId());
408
409                   notification.setFrom("policy");
410                   notification.setPolicyName(drools.getRule().getName());
411                   notification.setPolicyScope("${policyScope}");
412                   notification.setPolicyVersion("${policyVersion}");
413
414                   //
415                   // In this case, we are done
416                   //
417                   PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
418                   //
419                   // Unlock the target
420                   //
421                   Lock lock = $manager.unlockCurrentOperation();
422                   if(lock != null) {
423                       logger.debug("{}: {}: retracting lock={}", $params.getClosedLoopControlName(),
424                                   drools.getRule().getName(), lock);
425                       retract(lock);
426                   }
427                   //
428                   // Retract everything from memory
429                   //
430                   logger.info("{}: {}: retracting onset, manager, and timer",
431                               $params.getClosedLoopControlName(), drools.getRule().getName());
432
433                   retract($manager.getOnsetEvent());
434
435                 // don't retract manager, etc. - a clean-up rule will do that
436                 }
437             }
438         } else {
439             //
440             // NOT final, so let's ask for the next operation
441             //
442             ControlLoopOperationManager operation = $manager.processControlLoop();
443             if (operation != null) {
444               //
445               // Let's ask for a lock right away
446               //
447               logger.info("{}: {}: requesting lock for operation={}",
448                             $params.getClosedLoopControlName(), drools.getRule().getName(),
449                             operation);
450
451               Pair<Lock,Lock> oldNew = $manager.lockCurrentOperation(
452                         new LockCallbackWorkingMemory($params.getClosedLoopControlName(), drools.getWorkingMemory()));
453               if(oldNew.first() != null) {
454                   logger.debug("{}: {}: retracting lock={}", $params.getClosedLoopControlName(),
455                               drools.getRule().getName(), oldNew.first());
456                   retract(oldNew.first());
457               }
458               if(oldNew.second() != null) {
459                   logger.debug("{}: {}: inserting lock={}", $params.getClosedLoopControlName(),
460                               drools.getRule().getName(), oldNew.second());
461                   insert(oldNew.second());
462               }
463
464               //
465               // insert the operation into memory
466               //
467               insert(operation);
468               //
469               // insert operation timeout object
470               //
471               ControlLoopTimer opTimer = new ControlLoopTimer();
472               opTimer.setTimerType("Operation");
473               opTimer.setClosedLoopControlName($event.getClosedLoopControlName());
474               opTimer.setRequestId($event.getRequestId().toString());
475               Integer timeout = operation.getOperationTimeout();
476               opTimer.setDelay(timeout > 0 ? timeout.toString() + "s" : $clTimer.getDelay());
477               insert(opTimer);
478
479             } else {
480                 //
481                 // Probably waiting for abatement
482                 //
483               logger.info("{}: {}: no operation, probably waiting for abatement",
484                           $params.getClosedLoopControlName(), drools.getRule().getName());
485             }
486         }
487     } catch (Exception e) {
488          logger.warn("{}: {}: unexpected",
489                   $params.getClosedLoopControlName(),
490                   drools.getRule().getName(), e);
491
492          VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
493          notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
494          notification.setMessage(e.getMessage());
495          notification.setFrom("policy");
496          notification.setPolicyName(drools.getRule().getName());
497          notification.setPolicyScope("${policyScope}");
498          notification.setPolicyVersion("${policyVersion}");
499
500          PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
501
502          retract($event);
503
504          // don't retract manager, etc. - a clean-up rule will do that
505     }
506
507 end
508
509 /*
510 *
511 * Lock denied
512 *
513 */
514 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCK.DENIED"
515     when
516         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
517         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
518         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
519             requestId == $event.getRequestId() )
520         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
521             onset.getRequestId() == $event.getRequestId(), "None".equalsIgnoreCase(getGuardApprovalStatus()) )
522         $lock : Lock (ownerKey == $event.getRequestId().toString(), isUnavailable())
523     then
524
525     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
526     logger.info("{}: {}: event={} manager={} operation={} lock={}",
527                 $params.getClosedLoopControlName(), drools.getRule().getName(),
528                 $event, $manager, $operation, $lock);
529
530     logger.debug("The target resource {} is already processing",
531                         $event.getAai().get($event.getTarget()));
532     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
533     notification.setNotification(ControlLoopNotificationType.REJECTED);
534     notification.setMessage("The target " + $event.getAai().get($event.getTarget())
535                         + " is already locked");
536     notification.setFrom("policy");
537     notification.setPolicyName(drools.getRule().getName());
538     notification.setPolicyScope("${policyScope}");
539     notification.setPolicyVersion("${policyVersion}");
540
541     PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
542
543     retract($event);
544
545     // don't retract manager, etc. - a clean-up rule will do that
546 end
547
548 /*
549 *
550 * Guard Permitted, let's send request to the actor.
551 *
552 */
553 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED"
554     when
555         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
556         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
557         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
558             requestId == $event.getRequestId() )
559         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
560             onset.getRequestId() == $event.getRequestId(), "Permit".equalsIgnoreCase(getGuardApprovalStatus()) )
561         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
562             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
563     then
564
565     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
566     logger.info("{}: {}: event={} manager={} operation={}",
567                 $params.getClosedLoopControlName(), drools.getRule().getName(),
568                 $event, $manager, $operation);
569
570     Object request = null;
571     boolean caughtException = false;
572
573     try {
574         request = $operation.startOperation($event);
575
576         if (request != null) {
577           logger.debug("{}: {}: starting operation ..",
578                        $params.getClosedLoopControlName(), drools.getRule().getName());
579           //
580           // Tell interested parties we are performing this Operation
581           //
582           VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
583           notification.setNotification(ControlLoopNotificationType.OPERATION);
584           notification.setMessage($operation.getOperationMessage());
585           notification.setHistory($operation.getHistory());
586           notification.setFrom("policy");
587           notification.setPolicyName(drools.getRule().getName());
588           notification.setPolicyScope("${policyScope}");
589           notification.setPolicyVersion("${policyVersion}");
590
591           PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
592
593           switch ($operation.policy.getActor()){
594
595               case "APPC":
596                   if (request instanceof Request) {
597                       PolicyEngineConstants.getManager().deliver("APPC-CL", request);
598                   }
599                   else if (request instanceof AppcLcmDmaapWrapper) {
600                       PolicyEngineConstants.getManager().deliver("APPC-LCM-READ", request);
601                   }
602                   break;
603               case "SO":
604                   // at this point the AAI named query request should have already been made,
605                   // the response recieved and used
606                   // in the construction of the SO Request which is stored in operationRequest
607
608                   if(request instanceof SoRequest) {
609                       // Call SO. The response will be inserted into memory once it's received
610                       class mySoCallback implements SoManager.SoCallback {
611                           public void onSoResponseWrapper(SoResponseWrapper wrapper) {
612                               drools.getWorkingMemory().insert(wrapper);
613                           }
614                       }
615                       SoActorServiceProvider.sendRequest($event.getRequestId().toString(),
616                           new mySoCallback(),
617                           request,
618                           PolicyEngineConstants.getManager().getEnvironmentProperty("so.url"),
619                           PolicyEngineConstants.getManager().getEnvironmentProperty("so.username"),
620                           PolicyEngineConstants.getManager().getEnvironmentProperty("so.password"));
621                   }
622                   break;
623               case "VFC":
624                   if (request instanceof VfcRequest) {
625                       // Start VFC thread
626                       class myVfcCallback implements VfcManager.VfcCallback {
627
628                           public void onResponse(VfcResponse responseError) {
629                               drools.getWorkingMemory().insert(responseError);
630                           }
631                       };
632                       // Start VFC thread
633                       Thread t = new Thread(new VfcManager(new myVfcCallback(),
634                           (VfcRequest)request,
635                           PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.url"),
636                           PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.username"),
637                           PolicyEngineConstants.getManager().getEnvironmentProperty("vfc.password")));
638                       t.start();
639                   }
640                   break;
641
642               case "SDNC":
643                   if (request instanceof SdncRequest) {
644                      // Start SDNC thread
645                       class mySdncCallback implements SdncManager.SdncCallback {
646                           public void onCallback(SdncResponse response) {
647                               drools.getWorkingMemory().insert(response);
648                           }
649                       }
650                       // Start SDNC thread
651                       Thread t = new Thread(new SdncManager(new mySdncCallback(),
652                           (SdncRequest)request,
653                           PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.url"),
654                           PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.username"),
655                           PolicyEngineConstants.getManager().getEnvironmentProperty("sdnc.password")));
656                       t.start();
657                   }
658                   break;
659               case "SDNR":
660                   if (request instanceof PciRequestWrapper) {
661                       PolicyEngineConstants.getManager().deliver("SDNR-CL", request);
662                   }
663                   break;
664
665              case "CDS":
666
667                   if(request instanceof ExecutionServiceInput) {
668
669                       // Instantiate cds actor, service manager and grpc properties
670
671                       CdsActorServiceProvider cdsActor = new CdsActorServiceProvider();
672                       CdsActorServiceProvider.CdsActorServiceManager cdsActorServiceManager = cdsActor.new CdsActorServiceManager();
673
674                       CdsServerProperties props = new CdsServerProperties();
675                       props.setHost(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcHost"));
676                       props.setPort(Integer.parseInt(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcPort")));
677                       props.setUsername(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcUsername"));
678                       props.setPassword(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcPassword"));
679                       props.setTimeout(Integer.parseInt(PolicyEngineConstants.getManager().getEnvironmentProperty("cds.grpcTimeout")));
680
681                       // Send cds grpc request
682                       try (CdsProcessorGrpcClient client = new CdsProcessorGrpcClient(cdsActorServiceManager, props)) {
683                           CdsResponse response =
684                                 cdsActorServiceManager.sendRequestToCds(client, props, (ExecutionServiceInput) request);
685                           logger.info("CDS response: {}", response);
686                           insert(response);
687                       }
688
689                   }
690                   break;
691
692           }
693         } else {
694           //
695           // What happens if its null?
696           //
697             logger.warn("{}: {}: unexpected null operation request",
698                       $params.getClosedLoopControlName(),
699                       drools.getRule().getName());
700             if ("SO".equals($operation.policy.getActor())) {
701                 retract($opTimer);
702                 retract($operation);
703                 modify($manager) {finishOperation($operation)};
704             }
705             else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) {
706                 retract($opTimer);
707                 retract($operation);
708                 modify($manager) {finishOperation($operation)};
709             }
710             else if ("sdnc".equalsIgnoreCase($operation.policy.getActor())) {
711                 retract($opTimer);
712                 retract($operation);
713                 modify($manager) {finishOperation($operation)};
714             }
715         }
716
717     } catch (Exception e) {
718         String msg = e.getMessage();
719         logger.warn("{}: {}: operation={}:  AAI failure: {}",
720                     $params.getClosedLoopControlName(), drools.getRule().getName(),
721                     $operation, msg, e);
722         $operation.setOperationHasException(msg);
723
724         if(request != null) {
725             //
726             // Create a notification for it ("DB Write - end operation")
727             //
728             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
729             notification.setFrom("policy");
730             notification.setPolicyName(drools.getRule().getName());
731             notification.setPolicyScope("${policyScope}");
732             notification.setPolicyVersion("${policyVersion}");
733             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
734             notification.setMessage($operation.getOperationHistory());
735             notification.setHistory($operation.getHistory());
736
737             PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
738         }
739
740         retract($opTimer);
741         retract($operation);
742         caughtException = true;
743     }
744
745     // Having the modify statement in the catch clause doesn't work for whatever reason
746     if (caughtException) {
747         modify($manager) {finishOperation($operation)};
748     }
749 end
750
751
752 /*
753 *
754 * We were able to acquire a lock so now let's ask Xacml Guard whether
755 * we are allowed to proceed with the request to the actor.
756 *
757 */
758 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
759     when
760         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
761         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
762         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
763             requestId == $event.getRequestId() )
764         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
765             onset.getRequestId() == $event.getRequestId(), "None".equalsIgnoreCase(getGuardApprovalStatus()) )
766         $lock : Lock (ownerKey == $event.getRequestId().toString(), isActive())
767     then
768
769     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
770     logger.info("{}: {}: event={} manager={} operation={} lock={}",
771                 $params.getClosedLoopControlName(), drools.getRule().getName(),
772                 $event, $manager, $operation, $lock);
773
774     //
775     // Sending notification that we are about to query Guard ("DB write - start operation")
776     //
777     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
778     notification.setNotification(ControlLoopNotificationType.OPERATION);
779     notification.setMessage("Sending guard query for " + $operation.policy.getActor() + " "
780         + $operation.policy.getRecipe());
781     notification.setHistory($operation.getHistory());
782     notification.setFrom("policy");
783     notification.setPolicyName(drools.getRule().getName());
784     notification.setPolicyScope("${policyScope}");
785     notification.setPolicyVersion("${policyVersion}");
786
787     PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
788
789     //
790     // Now send Guard Request to XACML Guard. In order to bypass the call to Guard,
791     // just change guardEnabled to false.
792     //
793     // In order to use REST XACML, provide a URL instead of "" as a second argument
794     // to the CallGuardTask() and set the first argument to null
795     // (instead of XacmlPdpEngine).
796     //
797
798     // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled
799     boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngineConstants.getManager().getEnvironmentProperty("guard.disabled"));
800     boolean cqEnabled = "true".equalsIgnoreCase(PolicyEngineConstants.getManager().getEnvironmentProperty("aai.customQuery"));
801
802     if(guardEnabled){
803
804         Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
805                                                         drools.getWorkingMemory(),
806                                                         $event.getClosedLoopControlName(),
807                                                         $operation.policy.getActor().toString(),
808                                                         $operation.policy.getRecipe(),
809                                                         $operation.getTargetEntity(),
810                                                         $event.getRequestId().toString(),
811                                                         () -> {
812                                                              if (!cqEnabled) {
813                                                                  AaiNqResponseWrapper resp = $manager.getNqVserverFromAai();
814                                                                  return(resp == null ? null : resp.countVfModules());
815                                                              } else {
816                                                                  try {
817                                                                      AaiCqResponse resp_cq  = $manager.getCqResponse($event);
818                                                                      if (resp_cq == null){
819                                                                          return null;
820                                                                      } else {
821                                                                          String custId = $operation.policy.getTarget().getModelCustomizationId();
822                                                                          String invId = $operation.policy.getTarget().getModelInvariantId();
823                                                                          String verId = $operation.policy.getTarget().getModelVersionId();
824                                                                          return resp_cq.getVfModuleCount(custId, invId, verId);
825                                                                      }
826                                                                  } catch (Exception e){
827                                                                      logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
828                                                                  }
829                                                                  return null;
830                                                              }
831                                                         }));
832         t.start();
833     }
834     else{
835         insert(new PolicyGuardResponse("Permit", $event.getRequestId(), $operation.policy.getRecipe()));
836     }
837
838 end
839
840 //
841 // This rule will be triggered when a thread talking to the XACML Guard inserts a
842 // guardResponse object into the working memory
843 //
844 rule "${policyName}.GUARD.RESPONSE"
845     when
846         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
847         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
848             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
849         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
850             requestId == $event.getRequestId() )
851         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
852             onset.getRequestId() == $event.getRequestId() )
853         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
854             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
855         $guardResponse : PolicyGuardResponse(requestId == $event.getRequestId(), $operation.policy.recipe == operation)
856     then
857
858     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
859     logger.info("{}: {}: event={} manager={} operation={} opTimer={} guardResponse={}",
860                  $params.getClosedLoopControlName(), drools.getRule().getName(),
861                  $event, $manager, $operation, $opTimer, $guardResponse);
862
863
864     //we will permit the operation if there was no Guard for it
865     if("Indeterminate".equalsIgnoreCase($guardResponse.getResult())){
866         $guardResponse.setResult("Permit");
867     }
868
869     //
870     // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
871     //
872     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
873     notification.setNotification(ControlLoopNotificationType.OPERATION);
874     notification.setMessage("Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe()
875         + " is " + $guardResponse.getResult());
876     notification.setHistory($operation.getHistory());
877     notification.setFrom("policy");
878     notification.setPolicyName(drools.getRule().getName());
879     notification.setPolicyScope("${policyScope}");
880     notification.setPolicyVersion("${policyVersion}");
881
882     PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
883
884     if("Permit".equalsIgnoreCase($guardResponse.getResult())){
885
886         modify($operation){setGuardApprovalStatus($guardResponse.getResult())};
887     }
888     else {
889         //This is the Deny case
890         $operation.startOperation($event);
891         $operation.setOperationHasGuardDeny();
892         retract($opTimer);
893         retract($operation);
894         modify($manager) {finishOperation($operation)};
895     }
896
897     retract($guardResponse);
898
899 end
900
901 /*
902 *
903 * This rule responds to APPC Response Events
904 *
905 * I would have like to be consistent and write the Response like this:
906 * $response : Response( CommonHeader.RequestId == $onset.getRequestId() )
907 *
908 * However, no compile error was given. But a runtime error was given. I think
909 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
910 *
911 */
912 rule "${policyName}.APPC.RESPONSE"
913     when
914         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
915         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
916             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
917         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
918             requestId == $event.getRequestId() )
919         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
920             onset.getRequestId() == $event.getRequestId() )
921         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
922             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
923         $response : Response( getCommonHeader().RequestId == $event.getRequestId() )
924     then
925
926     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
927     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
928     logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
929                  $params.getClosedLoopControlName(), drools.getRule().getName(),
930                  $event, $manager, $operation, $opTimer, $response);
931     //
932     // Get the result of the operation
933     //
934     PolicyResult policyResult = $operation.onResponse($response);
935     if (policyResult != null) {
936         logger.debug("{}: {}: operation finished - result={}",
937                     $params.getClosedLoopControlName(), drools.getRule().getName(),
938                     policyResult);
939         //
940         // This Operation has completed, construct a notification showing our results. (DB write - end operation)
941         //
942         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
943         notification.setFrom("policy");
944         notification.setPolicyName(drools.getRule().getName());
945         notification.setPolicyScope("${policyScope}");
946         notification.setPolicyVersion("${policyVersion}");
947         notification.setMessage($operation.getOperationHistory());
948         notification.setHistory($operation.getHistory());
949         if (policyResult.equals(PolicyResult.SUCCESS)) {
950             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
951             //
952             // Let interested parties know
953             //
954             PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
955         } else {
956             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
957             //
958             // Let interested parties know
959             //
960             PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
961         }
962         //
963         // Ensure the operation is complete
964         //
965         if ($operation.isOperationComplete() == true) {
966             //
967             // It is complete, remove it from memory
968             //
969             retract($operation);
970             //
971             // We must also retract the timer object
972             // NOTE: We could write a Rule to do this
973             //
974             retract($opTimer);
975             //
976             // Complete the operation
977             //
978             modify($manager) {finishOperation($operation)};
979         } else {
980             //
981             // Just doing this will kick off the LOCKED rule again
982             //
983             modify($operation) {};
984         }
985     } else {
986         //
987         // Its not finished yet (i.e. expecting more Response objects)
988         //
989         // Or possibly it is a leftover response that we timed the request out previously
990         //
991     }
992     //
993     // We are going to retract these objects from memory
994     //
995     retract($response);
996 end
997
998 /*
999 *
1000 * The problem with Responses is that they don't have a controlLoopControlName
1001 * field in them, so the only way to attach them is via RequestId. If we have multiple
1002 * control loop .drl's loaded in the same container, we need to be sure the cleanup
1003 * rules don't remove Responses for other control loops.
1004 *
1005 */
1006 rule "${policyName}.APPC.RESPONSE.CLEANUP"
1007     when
1008         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1009         $response : Response($id : getCommonHeader().RequestId )
1010         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
1011     then
1012
1013     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1014     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1015     logger.debug("{}: {}: orphan appc response={}",
1016                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
1017
1018     //
1019     // Retract it
1020     //
1021     retract($response);
1022 end
1023
1024 /*
1025 *
1026 * This rule responds to APPC Response Events using the new LCM interface provided by appc
1027 *
1028 */
1029 rule "${policyName}.APPC.LCM.RESPONSE"
1030     when
1031         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1032         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1033             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1034         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1035             requestId == $event.getRequestId() )
1036         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1037             onset.getRequestId() == $event.getRequestId() )
1038         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1039             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1040         $response : AppcLcmDmaapWrapper( getBody().getOutput().getCommonHeader().getRequestId() == $event.getRequestId() )
1041     then
1042
1043     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1044     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1045     logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1046                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1047                 $event, $manager, $operation, $operation, $opTimer, $response);
1048
1049     //
1050     // Get the result of the operation
1051     //
1052     PolicyResult policyResult = $operation.onResponse($response);
1053     if (policyResult != null) {
1054       logger.debug("{}: {}: operation finished - result={}",
1055                   $params.getClosedLoopControlName(), drools.getRule().getName(),
1056                   policyResult);
1057
1058       //
1059       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
1060       //
1061       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1062       notification.setFrom("policy");
1063       notification.setPolicyName(drools.getRule().getName());
1064       notification.setPolicyScope("${policyScope}");
1065       notification.setPolicyVersion("${policyVersion}");
1066       notification.setMessage($operation.getOperationHistory());
1067       notification.setHistory($operation.getHistory());
1068       if (policyResult.equals(PolicyResult.SUCCESS)) {
1069           notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1070       } else {
1071           notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1072       }
1073       PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1074       //
1075       // Ensure the operation is complete
1076       //
1077       if ($operation.isOperationComplete() == true) {
1078           //
1079           // It is complete, remove it from memory
1080           //
1081           retract($operation);
1082           //
1083           // We must also retract the timer object
1084           // NOTE: We could write a Rule to do this
1085           //
1086           retract($opTimer);
1087           //
1088           // Complete the operation
1089           //
1090           modify($manager) {finishOperation($operation)};
1091       } else {
1092           //
1093           // Just doing this will kick off the LOCKED rule again
1094           //
1095           modify($operation) {};
1096       }
1097     } else {
1098         //
1099         // Its not finished yet (i.e. expecting more Response objects)
1100         //
1101         // Or possibly it is a leftover response that we timed the request out previously
1102         //
1103     }
1104     //
1105     // We are going to retract these objects from memory
1106     //
1107     retract($response);
1108 end
1109
1110 /*
1111 *
1112 * Clean Up any lingering LCM reponses
1113 *
1114 */
1115 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
1116     when
1117         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1118         $response : AppcLcmDmaapWrapper($id : getBody().getOutput().getCommonHeader().getRequestId() )
1119         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
1120     then
1121
1122     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1123     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1124     logger.debug("{}: {}: orphan appc response={}",
1125                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
1126     //
1127     // Retract it
1128     //
1129     retract($response);
1130 end
1131
1132 /*
1133 *
1134 * This rule responds to SDNR Response Events using the new interface provided by SDNR
1135 *
1136 */
1137 rule "${policyName}.SDNR.RESPONSE"
1138     when
1139         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1140         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1141             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1142         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1143             requestId == $event.getRequestId() )
1144         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1145             onset.getRequestId() == $event.getRequestId() )
1146         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1147             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1148         $response : PciResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.getRequestId() )
1149     then
1150
1151     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1152     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1153     logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1154                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1155                 $event, $manager, $operation, $operation, $opTimer, $response);
1156
1157     //
1158     // Get the result of the operation
1159     //
1160     PolicyResult policyResult = $operation.onResponse($response);
1161     if (policyResult != null) {
1162       logger.debug("{}: {}: operation finished - result={}",
1163                   $params.getClosedLoopControlName(), drools.getRule().getName(),
1164                   policyResult);
1165
1166       //
1167       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
1168       //
1169       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1170       notification.setFrom("policy");
1171       notification.setPolicyName(drools.getRule().getName());
1172       notification.setPolicyScope("${policyScope}");
1173       notification.setPolicyVersion("${policyVersion}");
1174       notification.setMessage($operation.getOperationHistory());
1175       notification.setHistory($operation.getHistory());
1176       if (policyResult.equals(PolicyResult.SUCCESS)) {
1177           notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1178       } else {
1179           notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1180       }
1181       PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1182       //
1183       // Ensure the operation is complete
1184       //
1185       if ($operation.isOperationComplete()) {
1186           //
1187           // It is complete, remove it from memory
1188           //
1189           retract($operation);
1190           //
1191           // We must also retract the timer object
1192           // NOTE: We could write a Rule to do this
1193           //
1194           retract($opTimer);
1195           //
1196           // Complete the operation
1197           //
1198           modify($manager) {finishOperation($operation)};
1199       } else {
1200           //
1201           // Just doing this will kick off the LOCKED rule again
1202           //
1203           modify($operation) {};
1204       }
1205     } else {
1206         //
1207         // Its not finished yet (i.e. expecting more Response objects)
1208         //
1209         // Or possibly it is a leftover response that we timed the request out previously
1210         //
1211     }
1212     //
1213     // We are going to retract these objects from memory
1214     //
1215     retract($response);
1216 end
1217
1218 /*
1219 *
1220 * Clean Up any lingering SDNR reponses
1221 *
1222 */
1223 rule "${policyName}.SDNR.RESPONSE.CLEANUP"
1224     when
1225         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1226         $response : PciResponseWrapper($id : getBody().getCommonHeader().getRequestId )
1227         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) )
1228     then
1229
1230     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1231     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1232     logger.debug("{}: {}: orphan SDNR response={}",
1233                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
1234     //
1235     // Retract it
1236     //
1237     retract($response);
1238 end
1239
1240 /*
1241 *
1242 * This rule responds to SO Response Events
1243 *
1244 */
1245 rule "${policyName}.SO.RESPONSE"
1246     when
1247         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1248         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1249             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1250         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1251             requestId == $event.getRequestId() )
1252         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1253             onset.getRequestId() == $event.getRequestId() )
1254         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1255             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1256         $response : SoResponseWrapper(requestId.toString() == $event.getRequestId().toString() )
1257     then
1258
1259     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1260     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1261     logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1262                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1263                 $event, $manager, $operation, $operation, $opTimer, $response);
1264
1265     // Get the result of the operation
1266     //
1267     PolicyResult policyResult = $operation.onResponse($response);
1268     if (policyResult != null) {
1269         logger.debug("{}: {}: operation finished - result={}",
1270                     $params.getClosedLoopControlName(), drools.getRule().getName(),
1271                     policyResult);
1272
1273         //
1274         // This Operation has completed, construct a notification showing our results
1275         //
1276         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1277         notification.setFrom("policy");
1278         notification.setPolicyName(drools.getRule().getName());
1279         notification.setPolicyScope("${policyScope}");
1280         notification.setPolicyVersion("${policyVersion}");
1281         notification.setMessage($operation.getOperationHistory());
1282         notification.setHistory($operation.getHistory());
1283         if (policyResult.equals(PolicyResult.SUCCESS)) {
1284             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1285         } else {
1286             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1287
1288         }
1289         PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1290         //
1291         // Ensure the operation is complete
1292         //
1293         if ($operation.isOperationComplete() == true) {
1294             //
1295             // It is complete, remove it from memory
1296             //
1297             retract($operation);
1298             //
1299             // We must also retract the timer object
1300             // NOTE: We could write a Rule to do this
1301             //
1302             retract($opTimer);
1303             //
1304             // Complete the operation
1305             //
1306             modify($manager) {finishOperation($operation)};
1307         } else {
1308             //
1309             // Just doing this will kick off the LOCKED rule again
1310             //
1311             modify($operation) {};
1312         }
1313     } else {
1314         //
1315         // Its not finished yet (i.e. expecting more Response objects)
1316         //
1317         // Or possibly it is a leftover response that we timed the request out previously
1318         //
1319     }
1320     //
1321     // We are going to retract these objects from memory
1322     //
1323     retract($response);
1324
1325 end
1326
1327 /*
1328 *
1329 * This rule responds to VFC Response Events
1330 *
1331 */
1332 rule "${policyName}.VFC.RESPONSE"
1333     when
1334         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1335         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1336             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1337         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1338             requestId == $event.getRequestId() )
1339         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1340             onset.getRequestId() == $event.getRequestId() )
1341         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1342             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1343         $response : VfcResponse( requestId.toString() == $event.getRequestId().toString() )
1344     then
1345         Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1346         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1347         logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1348                     $params.getClosedLoopControlName(), drools.getRule().getName(),
1349                     $event, $manager, $operation, $operation, $opTimer, $response);
1350
1351         // Get the result of the operation
1352         //
1353         PolicyResult policyResult = $operation.onResponse($response);
1354         if (policyResult != null) {
1355             //
1356             // This Operation has completed, construct a notification showing our results
1357             //
1358             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1359             notification.setFrom("policy");
1360             notification.setPolicyName(drools.getRule().getName());
1361             notification.setPolicyScope("${policyScope}");
1362             notification.setPolicyVersion("${policyVersion}");
1363             notification.setMessage($operation.getOperationHistory());
1364             notification.setHistory($operation.getHistory());
1365             //
1366             // Ensure the operation is complete
1367             //
1368             if ($operation.isOperationComplete() == true) {
1369                 //
1370                 // It is complete, remove it from memory
1371                 //
1372                 retract($operation);
1373                 //
1374                 // We must also retract the timer object
1375                 // NOTE: We could write a Rule to do this
1376                 //
1377                 retract($opTimer);
1378                 //
1379                 // Complete the operation
1380                 //
1381                 modify($manager) {finishOperation($operation)};
1382             } else {
1383                 //
1384                 // Just doing this will kick off the LOCKED rule again
1385                 //
1386                 modify($operation) {};
1387             }
1388         } else {
1389             //
1390             // Its not finished yet (i.e. expecting more Response objects)
1391             //
1392             // Or possibly it is a leftover response that we timed the request out previously
1393             //
1394         }
1395         //
1396         // We are going to retract these objects from memory
1397         //
1398         retract($response);
1399
1400 end
1401
1402 /*
1403 *
1404 * This rule responds to SDNC Response Events
1405 *
1406 */
1407
1408 rule "${policyName}.SDNC.RESPONSE"
1409     when
1410         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1411         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1412             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1413         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1414             requestId == $event.getRequestId() )
1415         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1416             onset.getRequestId() == $event.getRequestId() )
1417         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1418             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1419         $response : SdncResponse( requestId.toString() == $event.getRequestId().toString() )
1420     then
1421         Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1422         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1423         logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1424                     $params.getClosedLoopControlName(), drools.getRule().getName(),
1425                     $event, $manager, $operation, $operation, $opTimer, $response);
1426
1427         // Get the result of the operation
1428         //
1429         PolicyResult policyResult = $operation.onResponse($response);
1430         if (policyResult != null) {
1431             //
1432             // This Operation has completed, construct a notification showing our results
1433             //
1434             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1435             notification.setFrom("policy");
1436             notification.setPolicyName(drools.getRule().getName());
1437             notification.setPolicyScope("${policyScope}");
1438             notification.setPolicyVersion("${policyVersion}");
1439             notification.setMessage($operation.getOperationHistory());
1440             notification.setHistory($operation.getHistory());
1441             //
1442             // Ensure the operation is complete
1443             //
1444             if ($operation.isOperationComplete()) {
1445                 //
1446                 // It is complete, remove it from memory
1447                 //
1448                 retract($operation);
1449                 //
1450                 // We must also retract the timer object
1451                 // NOTE: We could write a Rule to do this
1452                 //
1453                 retract($opTimer);
1454                 //
1455                 // Complete the operation
1456                 //
1457                 modify($manager) {finishOperation($operation)};
1458             } else {
1459                 //
1460                 // Just doing this will kick off the LOCKED rule again
1461                 //
1462                 modify($operation) {};
1463             }
1464         } else {
1465             //
1466             // Its not finished yet (i.e. expecting more Response objects)
1467             //
1468             // Or possibly it is a leftover response that we timed the request out previously
1469             //
1470         }
1471         //
1472         // We are going to retract these objects from memory
1473         //
1474         retract($response);
1475
1476 end
1477
1478
1479 /**
1480  * This rule responds to CDS Response Events
1481  */
1482 rule "${policyName}.CDS.RESPONSE"
1483     when
1484         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1485         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(),
1486             closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1487         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1488             requestId == $event.getRequestId() )
1489         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1490             onset.getRequestId() == $event.getRequestId() )
1491         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1492             requestId == $event.getRequestId().toString(), timerType == "Operation", !expired )
1493         $response : CdsResponse( requestId == $event.getRequestId().toString() )
1494
1495     then
1496
1497         Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1498         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1499         logger.debug("{}: {}: event={} manager={} operation={} opTimer={} response={}",
1500                     $params.getClosedLoopControlName(), drools.getRule().getName(),
1501                     $event, $manager, $operation, $operation, $opTimer, $response);
1502
1503         // Get the result of the operation
1504         PolicyResult policyResult = $operation.onResponse($response);
1505
1506         if (policyResult != null) {
1507             logger.debug("{}: {}: operation finished - result={}",
1508                     $params.getClosedLoopControlName(), drools.getRule().getName(),
1509                     policyResult);
1510
1511             // The operation has completed, construct a notification showing our results
1512             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1513             notification.setFrom("policy");
1514             notification.setPolicyName(drools.getRule().getName());
1515             notification.setPolicyScope("${policyScope}");
1516             notification.setPolicyVersion("${policyVersion}");
1517             notification.setMessage($operation.getOperationHistory());
1518             notification.setHistory($operation.getHistory());
1519             notification.setNotification(
1520                 ($response != null && CdsActorConstants.SUCCESS.equals($response.getStatus()))
1521                     ? ControlLoopNotificationType.OPERATION_SUCCESS : ControlLoopNotificationType.OPERATION_FAILURE);
1522
1523             // Send the notification
1524             PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1525
1526             // Ensure the operation is complete
1527             if ($operation.isOperationComplete()) {
1528
1529                 // It is complete, remove it from memory
1530                 retract($operation);
1531
1532                 // We must also retract the timer object
1533                 // NOTE: We could write a Rule to do this
1534                 retract($opTimer);
1535
1536                 // Complete the operation
1537                 modify($manager) {finishOperation($operation)};
1538
1539             } else {
1540                 // Just doing this will kick off the LOCKED rule again
1541                 modify($operation) {};
1542             }
1543         } else {
1544             // Its not finished yet (i.e. expecting more Response objects)
1545             // Or possibly it is a leftover response that we timed the request out previously
1546             logger.info(
1547                 "policyResult is null"
1548                     + "\nIt's not finished yet (i.e. expecting more Response objects)"
1549                     + "\nOr possibly it is a leftover response that we timed the request out previously");
1550         }
1551
1552         // We are going to retract these objects from memory
1553         retract($response);
1554
1555 end
1556
1557 /*
1558 *
1559 * This manages a single timer.
1560 * Due to a bug in the drools code, the drools timer needed to be split from most of the objects in the when clause
1561 *
1562 */
1563 rule "${policyName}.TIMER.FIRED"
1564     timer (expr: $timeout)
1565     when
1566         $timer : ControlLoopTimer($timeout : delay, !expired)
1567     then
1568         Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1569         logger.info("This is ${policyName}.TIMER.FIRED");
1570         modify($timer){setExpired(true)};
1571     end
1572
1573 /*
1574 *
1575 * This is the timer that manages the timeout for an individual operation.
1576 *
1577 */
1578 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
1579     when
1580         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1581         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1582         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1583             requestId == $event.getRequestId() )
1584         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(),
1585             onset.getRequestId() == $event.getRequestId() )
1586         $opTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1587             requestId == $event.getRequestId().toString(), expired, timerType == "Operation" )
1588     then
1589
1590     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1591     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1592     logger.debug("{}: {}: event={} manager={} operation={} opTimer={}",
1593                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1594                 $event, $manager, $operation, $operation, $opTimer);
1595
1596     //
1597     // Tell it it has timed out
1598     //
1599     $operation.setOperationHasTimedOut();
1600     //
1601     // Create a notification for it ("DB Write - end operation")
1602     //
1603     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1604     notification.setFrom("policy");
1605     notification.setPolicyName(drools.getRule().getName());
1606     notification.setPolicyScope("${policyScope}");
1607     notification.setPolicyVersion("${policyVersion}");
1608     notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1609     notification.setMessage($operation.getOperationHistory());
1610     notification.setHistory($operation.getHistory());
1611     //
1612     // Let interested parties know
1613     //
1614     PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1615     //
1616     // Get rid of the timer
1617     //
1618     retract($opTimer);
1619     //
1620     // Ensure the operation is complete
1621     //
1622     if ($operation.isOperationComplete() == true) {
1623         //
1624         // It is complete, remove it from memory
1625         //
1626         retract($operation);
1627         //
1628         // Complete the operation
1629         //
1630         modify($manager) {finishOperation($operation)};
1631     } else {
1632         //
1633         // Just doing this will kick off the LOCKED rule again
1634         //
1635         modify($operation) {};
1636     }
1637 end
1638
1639 /*
1640 *
1641 * This is the timer that manages the overall control loop timeout.
1642 *
1643 */
1644 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
1645     when
1646         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1647         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1648         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(),
1649             requestId == $event.getRequestId() )
1650         $clTimer : ControlLoopTimer( closedLoopControlName == $event.getClosedLoopControlName(),
1651             requestId == $event.getRequestId().toString(), expired, timerType == "ClosedLoop" )
1652     then
1653
1654     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1655     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1656
1657     logger.debug("{}: {}: event={}",
1658               $params.getClosedLoopControlName(), drools.getRule().getName(),
1659               $event);
1660     //
1661     // Tell the Event Manager it has timed out
1662     //
1663     VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
1664     if (notification != null) {
1665         notification.setFrom("policy");
1666         notification.setPolicyName(drools.getRule().getName());
1667         notification.setPolicyScope("${policyScope}");
1668         notification.setPolicyVersion("${policyVersion}");
1669         //
1670         // Let interested parties know
1671         //
1672         PolicyEngineConstants.getManager().deliver("POLICY-CL-MGT", notification);
1673     }
1674     //
1675     // Retract the event
1676     //
1677     retract($event);
1678 end
1679
1680 /*
1681 *
1682 * This rule cleans up the manager and other objects after an event has
1683 * been retracted.
1684 *
1685 */
1686 rule "${policyName}.EVENT.MANAGER.CLEANUP"
1687     when
1688         $manager : ControlLoopEventManager( $clName : getClosedLoopControlName(), $requestId : getRequestId() )
1689         $operations : LinkedList()
1690                         from collect( ControlLoopOperationManager( onset.closedLoopControlName == $clName,
1691                             onset.getRequestId() == $requestId ) )
1692         $timers : LinkedList()
1693                         from collect( ControlLoopTimer( closedLoopControlName == $clName,
1694                             requestId == $requestId.toString() ) )
1695         not( VirtualControlLoopEvent( closedLoopControlName == $clName, requestId == $requestId ) )
1696     then
1697
1698     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1699     logger.info("{}: {}", $clName, drools.getRule().getName());
1700
1701     logger.debug("{}: {}: manager={} timers={} operations={}",
1702               $clName, drools.getRule().getName(),
1703               $manager, $timers.size(), $operations.size());
1704
1705     //
1706     // Retract lock by invoking unlock()
1707     //
1708     Lock lock = $manager.unlockCurrentOperation();
1709     if(lock != null) {
1710         retract(lock);
1711     }
1712
1713     //
1714     // Retract EVERYTHING
1715     //
1716
1717     retract($manager);
1718
1719     for(Object manager: $operations) {
1720         retract((ControlLoopOperationManager) manager);
1721     }
1722     for(Object timer: $timers) {
1723         retract((ControlLoopTimer) timer);
1724     }
1725 end
1726
1727 /*
1728 *
1729 * This rule will clean up any rogue onsets where there is no
1730 * ControlLoopParams object corresponding to the onset event.
1731 *
1732 */
1733 rule "${policyName}.EVENT.CLEANUP"
1734     when
1735         $event : VirtualControlLoopEvent( $clName: closedLoopControlName )
1736         not ( Params( getClosedLoopControlName() == $clName) )
1737     then
1738
1739     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1740     logger.info("{}: {}", $clName, drools.getRule().getName());
1741     logger.debug("{}: {}: orphan onset event={}",
1742                 $clName, drools.getRule().getName(), $event);
1743
1744     retract($event);
1745 end
1746
1747 /*
1748 * Creates a cleaner for every Params object.
1749 * This has a higher salience so that it is fired before PARAMS.FINISHED in ANY policy.
1750 */
1751 rule "${policyName}.PARAMS.CLEANING"
1752     salience 2
1753     when
1754         $params: Params( )
1755         ParamsInitCleaner( )
1756     then
1757
1758     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1759     logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(),
1760         $params.getControlLoopYaml());
1761
1762     ParamsCleaner cleaner = new ParamsCleaner();
1763     cleaner.setClosedLoopControlName($params.getClosedLoopControlName());
1764     cleaner.setControlLoopYaml($params.getControlLoopYaml());
1765     insert(cleaner);
1766 end
1767
1768 /*
1769 * Finished creating cleaner objects, so remove the trigger.
1770 * This has a higher salience so that it is fired before processing any events.
1771 */
1772 rule "${policyName}.PARAMS.FINISHED"
1773     salience 1
1774     when
1775         $initCleaner: ParamsInitCleaner( )
1776     then
1777
1778     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1779     logger.info("{}: {}", $initCleaner.getClosedLoopControlName(), drools.getRule().getName());
1780
1781     retract($initCleaner);
1782 end
1783
1784 /*
1785 * Identifies Params objects that are still active, removing their associated cleaners.
1786 * This should only leave one active Params object for each policy.
1787 * This has a higher salience so that it is fired before PARAMS.DELETE in ANY policy.
1788 */
1789 rule "${policyName}.PARAMS.ACTIVE"
1790     salience 3
1791     when
1792         $params: Params( getClosedLoopControlName() == "${closedLoopControlName}",
1793                             getControlLoopYaml() == "${controlLoopYaml}" )
1794         $cleaner: ParamsCleaner( getClosedLoopControlName() == "${closedLoopControlName}",
1795                             getControlLoopYaml() == "${controlLoopYaml}"  )
1796     then
1797
1798     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1799     logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(),
1800         $params.getControlLoopYaml());
1801
1802     retract($cleaner);
1803 end
1804
1805 /*
1806 * Delete Params objects that are not active (i.e., those that still have an associated
1807 * cleaner object).
1808 * This has a higher salience so that it is fired before PARAMS.CLEANED in ANY policy.
1809 */
1810 rule "${policyName}.PARAMS.DELETE"
1811     salience 2
1812     when
1813         $params: Params( )
1814         $cleaner: ParamsCleaner( getClosedLoopControlName() == $params.getClosedLoopControlName(),
1815                             getControlLoopYaml() == $params.getControlLoopYaml()  )
1816     then
1817
1818     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1819     logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(),
1820         $params.getControlLoopYaml());
1821
1822     retract($params);
1823 end
1824
1825 /*
1826 * Finished clean-up, so delete the cleaner objects.
1827 * This has a higher salience so that it is fired before processing any events.
1828 */
1829 rule "${policyName}.PARAMS.CLEANED"
1830     salience 1
1831     when
1832         $cleaner: ParamsCleaner( )
1833     then
1834
1835     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1836     logger.info("{}: {} : YAML=[{}]", $cleaner.getClosedLoopControlName(), drools.getRule().getName(),
1837         $cleaner.getControlLoopYaml());
1838
1839     retract($cleaner);
1840 end