888d2b6e531e10b0106db65884ed3e87010ae184
[policy/drools-applications.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop;
22
23 import org.onap.policy.controlloop.VirtualControlLoopEvent;
24 import org.onap.policy.controlloop.VirtualControlLoopNotification;
25 import org.onap.policy.controlloop.ControlLoopEventStatus;
26 import org.onap.policy.controlloop.ControlLoopNotificationType;
27 import org.onap.policy.controlloop.ControlLoopLogger;
28 import org.onap.policy.controlloop.policy.PolicyResult;
29 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
30 import org.onap.policy.controlloop.policy.Policy;
31 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager;
32 import org.onap.policy.controlloop.eventmanager.ControlLoopEventManager.NEW_EVENT_STATUS;
33 import org.onap.policy.controlloop.eventmanager.ControlLoopOperationManager;
34 import org.onap.policy.controlloop.actor.so.SOActorServiceProvider;
35 import org.onap.policy.appc.Request;
36 import org.onap.policy.appc.Response;
37 import org.onap.policy.appc.CommonHeader;
38 import org.onap.policy.appclcm.LcmRequestWrapper;
39 import org.onap.policy.appclcm.LcmResponseWrapper;
40 import org.onap.policy.appclcm.LcmRequest;
41 import org.onap.policy.appclcm.LcmResponse;
42 import org.onap.policy.appclcm.LcmCommonHeader;
43 import org.onap.policy.vfc.VFCRequest;
44 import org.onap.policy.vfc.VFCResponse;
45 import org.onap.policy.vfc.VFCManager;
46 import org.onap.policy.so.SOManager;
47 import org.onap.policy.so.SORequest;
48 import org.onap.policy.so.SORequestStatus;
49 import org.onap.policy.so.SORequestDetails;
50 import org.onap.policy.so.SOModelInfo;
51 import org.onap.policy.so.SOCloudConfiguration;
52 import org.onap.policy.so.SORequestInfo;
53 import org.onap.policy.so.SORequestParameters;
54 import org.onap.policy.so.SORelatedInstanceListElement;
55 import org.onap.policy.so.SORelatedInstance;
56 import org.onap.policy.so.SOResponse;
57 import org.onap.policy.so.SOResponseWrapper;
58 import org.onap.policy.guard.PolicyGuard;
59 import org.onap.policy.guard.PolicyGuard.LockResult;
60 import org.onap.policy.guard.TargetLock;
61 import org.onap.policy.guard.GuardResult;
62 import org.onap.policy.guard.PolicyGuardRequest;
63 import org.onap.policy.guard.PolicyGuardResponse;
64 import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes;
65 import org.onap.policy.guard.PolicyGuardXacmlHelper;
66
67 import org.yaml.snakeyaml.Yaml;
68 import org.yaml.snakeyaml.constructor.Constructor;
69
70 import org.slf4j.LoggerFactory;
71 import org.slf4j.Logger;
72
73 import java.time.Instant;
74 import java.util.LinkedList;
75 import java.util.Iterator;
76
77 import org.onap.policy.drools.system.PolicyEngine;
78
79 /*
80  * This structure mimics the Params structure.
81  * Its only purpose is to allow management of
82  * rules by the PAP component..
83  * It has no use at runtime since the rules go by
84  * Params for matching purposes.
85  */
86 declare PapParams
87   closedLoopControlName : String
88   controlLoopYaml : String
89 end
90
91 /*
92  * Control Loop Identity
93  */
94 declare Params
95   closedLoopControlName : String
96   controlLoopYaml : String
97 end
98
99 /*
100  * Used to clean up Params that no longer have associated rules.
101  */
102 declare ParamsCleaner
103   closedLoopControlName : String
104   controlLoopYaml : String
105 end
106
107
108 /*
109  * Operation Timer
110  */
111 declare OperationTimer
112   closedLoopControlName : String
113   requestID : String
114   delay : String
115 end
116
117 /*
118  * Control Loop Timer
119  */
120 declare ControlLoopTimer
121   closedLoopControlName : String
122   requestID : String
123   delay : String
124 end
125
126 /*
127 *
128 * Called once and only once to insert the parameters into working memory for this Closed Loop policy.
129 * This has a higher salience so we can ensure that the Params is created before we have a chance to
130 * discard any events.
131 *
132 */
133 rule "${policyName}.SETUP"
134     salience 1
135     when
136         not( Params( getClosedLoopControlName() == "${closedLoopControlName}", getControlLoopYaml() == "${controlLoopYaml}" ) )
137     then
138     
139     Params params = new Params();
140     params.setClosedLoopControlName("${closedLoopControlName}");
141     params.setControlLoopYaml("${controlLoopYaml}");
142     insert(params);
143
144     // Note: globals have bad behavior when persistence is used,
145     //       hence explicitly getting the logger vs using a global
146     
147     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
148     logger.info("{}: {} : YAML=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(), params.getControlLoopYaml());
149 end
150
151 /*
152 *
153 * This rule responds to DCAE Events where there is no manager yet. Either it is
154 * the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled)
155 *
156 */
157 rule "${policyName}.EVENT"
158     when
159         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
160         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
161         not ( ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() ) )
162     then
163  
164     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
165     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
166     
167     try {
168       
169         //
170         // Check the event, because we need it to not be null when
171         // we create the ControlLoopEventManager. The ControlLoopEventManager
172         // will do extra syntax checking as well check if the closed loop is disabled.
173         //
174         if ($event.getRequestId() == null) {
175             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
176             notification.setNotification(ControlLoopNotificationType.REJECTED);
177             notification.setFrom("policy");
178             notification.setMessage("Missing requestId");
179             notification.setPolicyName(drools.getRule().getName());
180             notification.setPolicyScope("${policyScope}");
181             notification.setPolicyVersion("${policyVersion}");
182             
183             //
184             // Let interested parties know
185             //
186             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
187             
188             //
189             // Retract it from memory
190             //
191             retract($event);
192         } else if ($event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET) {
193                 throw new ControlLoopException($event.getClosedLoopEventStatus() + " received with no prior onset");
194         } else {
195             //
196             // Create an EventManager
197             //
198             ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.getRequestId());
199             //
200             // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.)
201             //
202             VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event);
203             notification.setFrom("pdp-0001-controller=controlloop"); // Engine.getInstanceName()
204             notification.setPolicyName(drools.getRule().getName());
205             notification.setPolicyScope("${policyScope}");
206             notification.setPolicyVersion("${policyVersion}");
207             //
208             // Are we actively pursuing this event?
209             //
210             if (notification.getNotification() == ControlLoopNotificationType.ACTIVE) {
211                 //
212                 // Insert Event Manager into memory, this will now kick off processing.
213                 //
214                 insert(manager);
215                 //
216                 // Let interested parties know
217                 //
218                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
219                 //
220                 // Setup the Overall Control Loop timer
221                 //
222                 ControlLoopTimer clTimer = new ControlLoopTimer();
223                 clTimer.setClosedLoopControlName($event.getClosedLoopControlName());
224                 clTimer.setRequestID($event.getRequestId().toString());
225                 clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s");
226                 //
227                 // Insert it
228                 //
229                 insert(clTimer);
230             } else {
231                 //
232                 // Let interested parties know
233                 //
234                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
235                 //
236                 // Retract it from memory
237                 //
238                 retract($event);
239             }
240             
241             //
242             // Now that the manager is inserted into Drools working memory, we'll wait for
243             // another rule to fire in order to continue processing. This way we can also
244             // then screen for additional ONSET and ABATED events for this RequestId.
245             //
246         }
247     } catch (Exception e) {
248         logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
249         
250         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
251         notification.setNotification(ControlLoopNotificationType.REJECTED);
252         notification.setMessage("Exception occurred: " + e.getMessage());
253         notification.setPolicyName(drools.getRule().getName());
254         notification.setPolicyScope("${policyScope}");
255         notification.setPolicyVersion("${policyVersion}");
256         //
257         //
258         //
259         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
260         //
261         // Retract the event
262         //
263         retract($event);
264     }
265 end
266
267 /*
268 *
269 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
270 * is now created. We can start processing the yaml specification via the Event Manager.
271 *
272 */
273 rule "${policyName}.EVENT.MANAGER"
274     when
275         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
276         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
277         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
278         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
279     then
280
281     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
282     logger.info("{}: {}: event={} manager={} clTimer={}", 
283                 $params.getClosedLoopControlName(), drools.getRule().getName(),
284                 $event, $manager, $clTimer);
285     
286     try {
287             //
288             // Check which event this is.
289             //
290             ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);
291             //
292             // Check what kind of event this is
293             //
294             if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) {
295                 //
296                 // We don't care about subsequent onsets
297                 //
298                 logger.info("{}: {}: subsequent onset", 
299                             $params.getClosedLoopControlName(), drools.getRule().getName());
300                 retract($event);
301                 return;
302             }
303             if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) {
304                 //
305                 // Ignore any bad syntax events
306                 //
307                 logger.warn("{}: {}: syntax error", 
308                             $params.getClosedLoopControlName(), drools.getRule().getName());
309                 retract($event);
310                 return;
311             }
312             //
313             // We only want the initial ONSET event in memory,
314             // all the other events need to be retracted to support
315             // cleanup and avoid the other rules being fired for this event.
316             //
317             if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) {
318                 logger.warn("{}: {}: not first onset", 
319                             $params.getClosedLoopControlName(), drools.getRule().getName());
320                 retract($event);
321             }
322             
323             logger.debug("{}: {}: target={}", $params.getClosedLoopControlName(), 
324                          drools.getRule().getName(), $event.getTarget());
325             //
326             // Now start seeing if we need to process this event
327             //
328
329         //
330         // Check if this is a Final Event
331         //
332         VirtualControlLoopNotification notification = $manager.isControlLoopFinal();
333     
334     
335         if (notification != null) {
336             //
337             // Its final, but are we waiting for abatement?
338             //
339             if ($manager.getNumAbatements() > 0) {
340                 logger.info("{}: {}: abatement received for {}.  Closing the control loop", 
341                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
342                             $event.getRequestId());
343                 notification.setFrom("policy");
344                 notification.setPolicyName(drools.getRule().getName());
345                 notification.setPolicyScope("${policyScope}");
346                 notification.setPolicyVersion("${policyVersion}");
347                 //
348                 // In this case, we are done
349                 //
350                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
351                 //
352                 // Unlock the target
353                 //
354                 TargetLock lock = $manager.unlockCurrentOperation();
355                 if (lock != null) {
356                     logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
357                                  drools.getRule().getName(), lock);
358                     retract(lock);
359                 }
360                 //
361                 // Retract everything from memory
362                 //
363                 logger.info("{}: {}: retracting onset, manager, and timer", 
364                             $params.getClosedLoopControlName(), drools.getRule().getName());
365                 
366                 retract($manager.getOnsetEvent());
367                 retract($manager);
368                 retract($clTimer);
369                 //
370                 // TODO - what if we get subsequent Events for this RequestId?
371                 // By default, it will all start over again. May be confusing for Ruby.
372                 // Or, we could track this and then subsequently ignore the events
373                 //
374             } else {
375                 //
376                 // Check whether we need to wait for abatement
377                 //
378                 if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.getNotification() == ControlLoopNotificationType.FINAL_SUCCESS) {
379                   logger.info("{}: {}: waiting for abatement ..", 
380                               $params.getClosedLoopControlName(), drools.getRule().getName());
381                 } else {
382                   logger.info("{}: {}: no abatement expect for {}.  Closing the control loop", 
383                               $params.getClosedLoopControlName(), drools.getRule().getName(), 
384                               $event.getRequestId());
385                   
386                   notification.setFrom("policy");
387                   notification.setPolicyName(drools.getRule().getName());
388                   notification.setPolicyScope("${policyScope}");
389                   notification.setPolicyVersion("${policyVersion}");
390                   
391                   //
392                   // In this case, we are done
393                   //
394                   PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
395                   //
396                   // Unlock the target
397                   //
398                   TargetLock lock = $manager.unlockCurrentOperation();
399                   if (lock != null) {
400                       logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
401                                   drools.getRule().getName(), lock);
402                       retract(lock);
403                   }
404                   //
405                   // Retract everything from memory
406                   //
407                   logger.info("{}: {}: retracting onset, manager, and timer", 
408                               $params.getClosedLoopControlName(), drools.getRule().getName());
409                   
410                   retract($manager.getOnsetEvent());
411                   retract($manager);
412                   retract($clTimer);
413                 }
414             }
415         } else {
416             //
417             // NOT final, so let's ask for the next operation
418             //
419             ControlLoopOperationManager operation = $manager.processControlLoop();
420             if (operation != null) {
421               //
422               // Let's ask for a lock right away
423               //
424               LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation();
425               logger.info("{}: {}: guard lock acquired={}", 
426                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
427                             result.getB());
428               if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) {
429                 //
430                 // insert the operation into memory
431                 //
432                 insert(operation);
433                 
434                 //
435                 // insert operation timeout object
436                 //
437                 OperationTimer opTimer = new OperationTimer();
438                 opTimer.setClosedLoopControlName($event.getClosedLoopControlName());
439                 opTimer.setRequestID($event.getRequestId().toString());
440                 opTimer.setDelay(operation.getOperationTimeout().toString() + "s");
441                 insert(opTimer);
442               
443                 //
444                 // Insert lock into memory
445                 //
446                 insert(result.getB());
447               }
448               else {
449                 logger.debug("The target resource {} is already processing",
450                                           $event.getAai().get($event.getTarget()));
451                 notification = new VirtualControlLoopNotification($event);
452                         notification.setNotification(ControlLoopNotificationType.REJECTED);
453                         notification.setMessage("The target " + $event.getAai().get($event.getTarget()) + " is already locked");
454                         notification.setFrom("policy");
455                         notification.setPolicyName(drools.getRule().getName());
456                         notification.setPolicyScope("${policyScope}");
457                         notification.setPolicyVersion("${policyVersion}");
458       
459                         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);                      
460                 
461                 retract($event);
462                 retract($manager);
463                 retract($clTimer);
464                 
465                 if(result.getB() != null) {
466                      retract(result.getB());
467                 }
468               }
469               logger.info("{}: {}: starting operation={}", 
470                           $params.getClosedLoopControlName(), drools.getRule().getName(), 
471                           operation);
472             } else {
473                 //
474                 // Probably waiting for abatement
475                 //
476               logger.info("{}: {}: no operation, probably waiting for abatement", 
477                           $params.getClosedLoopControlName(), drools.getRule().getName());
478             }
479         }
480     } catch (Exception e) {
481         logger.warn("{}: {}: unexpected", 
482                   $params.getClosedLoopControlName(), 
483                   drools.getRule().getName(), e);
484
485         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
486             notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
487             notification.setMessage(e.getMessage());
488             notification.setFrom("policy");
489             notification.setPolicyName(drools.getRule().getName());
490             notification.setPolicyScope("${policyScope}");
491             notification.setPolicyVersion("${policyVersion}");
492   
493                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);                      
494                 
495         retract($event);
496         retract($manager);
497         retract($clTimer);
498     }
499         
500 end
501
502 /*
503 *
504 * Guard Permitted, let's send request to the actor.
505 *
506 */
507 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED"
508     when
509         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
510         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
511         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
512         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId(), "Permit".equalsIgnoreCase(getGuardApprovalStatus()) )
513         $lock : TargetLock (requestID == $event.getRequestId())
514         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
515     then
516
517     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
518     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
519                 $params.getClosedLoopControlName(), drools.getRule().getName(),
520                 $event, $manager, $operation, $lock);    
521
522     Object request = null;
523     boolean caughtException = false;
524     try {
525         request = $operation.startOperation($event);
526     }
527     catch (ControlLoopException e) {
528         String msg = e.getMessage();
529         logger.warn("{}: {}: operation={}:  AAI failure: {}", 
530                     $params.getClosedLoopControlName(), drools.getRule().getName(),
531                     $operation, msg, e);
532         $operation.setOperationHasException(msg);
533         retract($opTimer);
534         retract($operation);
535         caughtException = true;
536     }
537     
538     // Having the modify statement in the catch clause doesn't work for whatever reason
539     if (caughtException) {
540         modify($manager) {finishOperation($operation)};
541     }
542     else if (request != null) {
543       logger.debug("{}: {}: starting operation ..", 
544                    $params.getClosedLoopControlName(), drools.getRule().getName());
545       //
546       // Tell interested parties we are performing this Operation
547       //
548       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
549       notification.setNotification(ControlLoopNotificationType.OPERATION);
550       notification.setMessage($operation.getOperationMessage());
551       notification.setHistory($operation.getHistory());
552       notification.setFrom("policy");
553       notification.setPolicyName(drools.getRule().getName());
554       notification.setPolicyScope("${policyScope}");
555       notification.setPolicyVersion("${policyVersion}");
556       
557       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
558       
559       switch ($operation.policy.getActor()){
560           
561           case "APPC":
562       
563               if (request instanceof Request) {
564                   PolicyEngine.manager.deliver("APPC-CL", request);
565               }
566               else if (request instanceof LcmRequestWrapper) {
567                   PolicyEngine.manager.deliver("APPC-LCM-READ", request);
568               }
569               break;
570           case "SO":
571               // at this point the AAI named query request should have already been made, the response recieved and used
572               // in the construction of the SO Request which is stored in operationRequest
573               
574               if(request instanceof SORequest) {
575                   // Call SO. The response will be inserted into memory once it's received 
576                   SOActorServiceProvider.sendRequest($event.getRequestId().toString(), drools.getWorkingMemory(), request);                        
577               }
578               break;
579           case "VFC":
580               if (request instanceof VFCRequest) {
581                   // Start VFC thread
582                   Thread t = new Thread(new VFCManager(drools.getWorkingMemory(), (VFCRequest)request));
583                   t.start();
584               }          
585               break;
586       }
587     } else {
588       //
589       // What happens if its null?
590       //
591                 logger.warn("{}: {}: unexpected null operation request", 
592                   $params.getClosedLoopControlName(), 
593                   drools.getRule().getName());
594                 if ("SO".equals($operation.policy.getActor())) {
595                     retract($opTimer);
596                         retract($operation);
597                         modify($manager) {finishOperation($operation)};
598                 }
599                 else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) {
600                     retract($opTimer);
601                         retract($operation);
602                         modify($manager) {finishOperation($operation)};
603                 }
604
605     }
606 end
607
608
609 /*
610 *
611 * We were able to acquire a lock so now let's ask Xacml Guard whether 
612 * we are allowed to proceed with the request to the actor.
613 *
614 */
615 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
616     when
617         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
618         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
619         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
620         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId(), getGuardApprovalStatus() == "NONE" )
621         $lock : TargetLock (requestID == $event.getRequestId())
622     then
623
624     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
625     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
626                 $params.getClosedLoopControlName(), drools.getRule().getName(),
627                 $event, $manager, $operation, $lock);
628     
629     //
630     // Sending notification that we are about to query Guard ("DB write - start operation")
631     //
632     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
633     notification.setNotification(ControlLoopNotificationType.OPERATION);
634     notification.setMessage("Sending guard query for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe());
635     notification.setHistory($operation.getHistory());
636     notification.setFrom("policy");
637     notification.setPolicyName(drools.getRule().getName());
638     notification.setPolicyScope("${policyScope}");
639     notification.setPolicyVersion("${policyVersion}");
640     
641     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
642         
643     //
644     // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, 
645     // just change guardEnabled to false.
646     // 
647     // In order to use REST XACML, provide a URL instead of "" as a second argument 
648     // to the CallGuardTask() and set the first argument to null 
649     // (instead of XacmlPdpEngine).
650     //
651     
652     // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled
653     boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
654     
655     if(guardEnabled){
656     
657         Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
658                                                         drools.getWorkingMemory(),
659                                                         $event.getClosedLoopControlName(),
660                                                         $operation.policy.getActor().toString(),
661                                                         $operation.policy.getRecipe(),
662                                                         $operation.getTargetEntity(),
663                                                         $event.getRequestId().toString()
664                                                         ));
665         t.start();
666     }
667     else{
668         insert(new PolicyGuardResponse("Permit", $event.getRequestId(), $operation.policy.getRecipe()));
669     }
670
671 end
672
673 //
674 // This rule will be triggered when a thread talking to the XACML Guard inserts a 
675 // guardResponse object into the working memory
676 //
677 rule "${policyName}.GUARD.RESPONSE"
678     when
679         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
680         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
681         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() ) 
682         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
683         $lock : TargetLock (requestID == $event.getRequestId())
684         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
685         $guardResponse : PolicyGuardResponse(requestID == $event.getRequestId(), $operation.policy.recipe == operation)
686     then
687
688     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
689     logger.info("{}: {}: event={} manager={} operation={} lock={} opTimer={} guardResponse={}", 
690                  $params.getClosedLoopControlName(), drools.getRule().getName(),
691                  $event, $manager, $operation, $lock, $opTimer, $guardResponse);
692         
693         
694     //we will permit the operation if there was no Guard for it
695     if("Indeterminate".equalsIgnoreCase($guardResponse.getResult())){
696         $guardResponse.setResult("Permit");
697     }
698     
699     //
700     // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
701     //
702     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
703     notification.setNotification(ControlLoopNotificationType.OPERATION);
704     notification.setMessage("Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe() + " is " + $guardResponse.getResult());
705     notification.setHistory($operation.getHistory());
706     notification.setFrom("policy");
707     notification.setPolicyName(drools.getRule().getName());
708     notification.setPolicyScope("${policyScope}");
709     notification.setPolicyVersion("${policyVersion}");
710     
711     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
712     
713     if("Permit".equalsIgnoreCase($guardResponse.getResult())){
714     
715         modify($operation){setGuardApprovalStatus($guardResponse.getResult())};
716     }
717     else {
718         //This is the Deny case
719         $operation.startOperation($event);
720         $operation.setOperationHasGuardDeny();
721         retract($opTimer);
722         retract($operation);
723         modify($manager) {finishOperation($operation)};
724     }
725     
726     retract($guardResponse);
727             
728 end
729
730 /*
731 *
732 * This rule responds to APPC Response Events
733 *
734 * I would have like to be consistent and write the Response like this:
735 * $response : Response( CommonHeader.RequestId == $onset.getRequestId() )
736 *
737 * However, no compile error was given. But a runtime error was given. I think
738 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
739 *
740 */
741 rule "${policyName}.APPC.RESPONSE"
742     when
743         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
744         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
745         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
746         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
747         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
748         $lock : TargetLock (requestID == $event.getRequestId())
749         $response : Response( getCommonHeader().RequestId == $event.getRequestId() )
750     then
751
752     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
753     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
754     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
755                  $params.getClosedLoopControlName(), drools.getRule().getName(),
756                  $event, $manager, $operation, $lock, $opTimer, $response);
757     //
758     // Get the result of the operation
759     //
760     PolicyResult policyResult = $operation.onResponse($response);
761     if (policyResult != null) {
762         logger.debug("{}: {}: operation finished - result={}", 
763                     $params.getClosedLoopControlName(), drools.getRule().getName(),
764                     policyResult);
765         //
766         // This Operation has completed, construct a notification showing our results. (DB write - end operation)
767         //
768         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
769         notification.setFrom("policy");
770         notification.setPolicyName(drools.getRule().getName());
771         notification.setPolicyScope("${policyScope}");
772         notification.setPolicyVersion("${policyVersion}");
773         notification.setMessage($operation.getOperationHistory());
774         notification.setHistory($operation.getHistory());
775         if (policyResult.equals(PolicyResult.SUCCESS)) {
776             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
777             //
778             // Let interested parties know
779             //
780             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
781         } else {
782             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
783             //
784             // Let interested parties know
785             //
786             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
787         }
788         //
789         // Ensure the operation is complete
790         //
791         if ($operation.isOperationComplete() == true) {
792             //
793             // It is complete, remove it from memory
794             //
795             retract($operation);
796             //
797             // We must also retract the timer object
798             // NOTE: We could write a Rule to do this
799             //
800             retract($opTimer);
801             //
802             // Complete the operation
803             //
804             modify($manager) {finishOperation($operation)};
805         } else {
806             //
807             // Just doing this will kick off the LOCKED rule again
808             //
809             modify($operation) {};
810         }
811     } else {
812         //
813         // Its not finished yet (i.e. expecting more Response objects)
814         //
815         // Or possibly it is a leftover response that we timed the request out previously
816         //
817     }
818     //
819     // We are going to retract these objects from memory
820     //
821     retract($response);
822 end
823
824 /*
825 *
826 * The problem with Responses is that they don't have a controlLoopControlName
827 * field in them, so the only way to attach them is via RequestId. If we have multiple
828 * control loop .drl's loaded in the same container, we need to be sure the cleanup
829 * rules don't remove Responses for other control loops.
830 *
831 */
832 rule "${policyName}.APPC.RESPONSE.CLEANUP"
833     when
834         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
835         $response : Response($id : getCommonHeader().RequestId )
836         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
837     then
838
839     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
840     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
841     logger.debug("{}: {}: orphan appc response={}", 
842                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
843         
844     //
845     // Retract it
846     //
847     retract($response);
848 end
849
850 /*
851 *
852 * This rule responds to APPC Response Events using the new LCM interface provided by appc
853 *
854 */
855 rule "${policyName}.APPC.LCM.RESPONSE"
856     when
857         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
858         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
859         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
860         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
861         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
862         $lock : TargetLock (requestID == $event.getRequestId())
863         $response : LcmResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.getRequestId() )
864     then
865
866     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
867     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
868     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
869                 $params.getClosedLoopControlName(), drools.getRule().getName(),
870                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
871     
872     //
873     // Get the result of the operation
874     //
875     PolicyResult policyResult = $operation.onResponse($response);
876     if (policyResult != null) {
877       logger.debug("{}: {}: operation finished - result={}", 
878                   $params.getClosedLoopControlName(), drools.getRule().getName(),
879                   policyResult);
880       
881       //
882       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
883       //
884       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
885       notification.setFrom("policy");
886       notification.setPolicyName(drools.getRule().getName());
887       notification.setPolicyScope("${policyScope}");
888       notification.setPolicyVersion("${policyVersion}");
889       notification.setMessage($operation.getOperationHistory());
890       notification.setHistory($operation.getHistory());
891       if (policyResult.equals(PolicyResult.SUCCESS)) {
892           notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
893       } else {
894           notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
895       }
896       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
897       //
898       // Ensure the operation is complete
899       //
900       if ($operation.isOperationComplete() == true) {
901           //
902           // It is complete, remove it from memory
903           //
904           retract($operation);
905           //
906           // We must also retract the timer object
907           // NOTE: We could write a Rule to do this
908           //
909           retract($opTimer);
910           //
911           // Complete the operation
912           //
913           modify($manager) {finishOperation($operation)};
914       } else {
915           //
916           // Just doing this will kick off the LOCKED rule again
917           //
918           modify($operation) {};
919       }
920     } else {
921         //
922         // Its not finished yet (i.e. expecting more Response objects)
923         //
924         // Or possibly it is a leftover response that we timed the request out previously
925         //
926     }
927     //
928     // We are going to retract these objects from memory
929     //
930     retract($response);
931 end
932
933 /*
934 *
935 * Clean Up any lingering LCM reponses
936 *
937 */
938 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
939     when
940         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
941         $response : LcmResponseWrapper($id : getBody().getCommonHeader().getRequestId )
942         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
943     then
944     
945     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
946     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
947     logger.debug("{}: {}: orphan appc response={}", 
948                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
949     //
950     // Retract it
951     //
952     retract($response);
953 end
954
955 /*
956 *
957 * This rule responds to SO Response Events
958 *
959 */
960 rule "${policyName}.SO.RESPONSE"
961     when
962         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
963         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
964         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
965         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
966         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
967         $lock : TargetLock (requestID == $event.getRequestId())
968         $response : SOResponseWrapper(requestID.toString() == $event.getRequestId().toString() )
969     then
970                         
971     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
972     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
973     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
974                 $params.getClosedLoopControlName(), drools.getRule().getName(),
975                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
976         
977     // Get the result of the operation
978     //
979     PolicyResult policyResult = $operation.onResponse($response);
980     if (policyResult != null) {
981         logger.debug("{}: {}: operation finished - result={}", 
982                     $params.getClosedLoopControlName(), drools.getRule().getName(),
983                     policyResult);
984       
985         //
986         // This Operation has completed, construct a notification showing our results
987         //
988         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
989         notification.setFrom("policy");
990         notification.setPolicyName(drools.getRule().getName());
991         notification.setPolicyScope("${policyScope}");
992         notification.setPolicyVersion("${policyVersion}");
993         notification.setMessage($operation.getOperationHistory());
994         notification.setHistory($operation.getHistory());
995         if (policyResult.equals(PolicyResult.SUCCESS)) {
996             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
997         } else {
998             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
999
1000         }
1001         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1002         //
1003         // Ensure the operation is complete
1004         //
1005         if ($operation.isOperationComplete() == true) {
1006             //
1007             // It is complete, remove it from memory
1008             //
1009             retract($operation);
1010             //
1011             // We must also retract the timer object
1012             // NOTE: We could write a Rule to do this
1013             //
1014             retract($opTimer);
1015             //
1016             // Complete the operation
1017             //
1018             modify($manager) {finishOperation($operation)};
1019         } else {
1020             //
1021             // Just doing this will kick off the LOCKED rule again
1022             //
1023             modify($operation) {};
1024         }
1025     } else {
1026         //
1027         // Its not finished yet (i.e. expecting more Response objects)
1028         //
1029         // Or possibly it is a leftover response that we timed the request out previously
1030         //
1031     }
1032     //
1033     // We are going to retract these objects from memory
1034     //
1035     retract($response);
1036
1037 end
1038
1039 /*
1040 *
1041 * This rule responds to VFC Response Events
1042 *
1043 */
1044 rule "${policyName}.VFC.RESPONSE"
1045         when
1046                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1047                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1048                 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
1049                 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
1050                 $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
1051         $lock : TargetLock (requestID == $event.getRequestId())
1052                 $response : VFCResponse( requestId.toString() == $event.getRequestId().toString() )     
1053         then
1054                 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1055         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1056         logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
1057                         $params.getClosedLoopControlName(), drools.getRule().getName(),
1058                         $event, $manager, $operation, $lock, $operation, $opTimer, $response);
1059                 
1060                 // Get the result of the operation
1061                 //
1062                 PolicyResult policyResult = $operation.onResponse($response);
1063                 if (policyResult != null) {
1064                         //
1065                         // This Operation has completed, construct a notification showing our results
1066                         //
1067                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1068                         notification.setFrom("policy");
1069                         notification.setPolicyName(drools.getRule().getName());
1070                         notification.setPolicyScope("${policyScope}");
1071                         notification.setPolicyVersion("${policyVersion}");
1072                         notification.setMessage($operation.getOperationHistory());
1073                         notification.setHistory($operation.getHistory());
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
1109 end
1110
1111 /*
1112 *
1113 * This is the timer that manages the timeout for an individual operation.
1114 *
1115 */
1116 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
1117     timer (expr: $to )
1118     when
1119         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1120         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1121         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
1122         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
1123         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString(), $to : getDelay() )
1124         $lock : TargetLock (requestID == $event.getRequestId())
1125     then
1126     
1127     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1128     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1129     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={}", 
1130                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1131                 $event, $manager, $operation, $lock, $operation, $opTimer);
1132     
1133     //
1134     // Tell it its timed out
1135     //
1136     $operation.setOperationHasTimedOut();
1137     //
1138     // Create a notification for it ("DB Write - end operation")
1139     //
1140     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1141     notification.setFrom("policy");
1142     notification.setPolicyName(drools.getRule().getName());
1143     notification.setPolicyScope("${policyScope}");
1144     notification.setPolicyVersion("${policyVersion}");
1145     notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1146     notification.setMessage($operation.getOperationHistory());
1147     notification.setHistory($operation.getHistory());
1148     //
1149     // Let interested parties know
1150     //
1151     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1152     //
1153     // Get rid of the timer
1154     //
1155     retract($opTimer);
1156     //
1157     // Ensure the operation is complete
1158     //
1159     if ($operation.isOperationComplete() == true) {
1160         //
1161         // It is complete, remove it from memory
1162         //
1163         retract($operation);
1164         //
1165         // Complete the operation
1166         //
1167         modify($manager) {finishOperation($operation)};
1168     } else {
1169         //
1170         // Just doing this will kick off the LOCKED rule again
1171         //
1172         modify($operation) {};
1173     }
1174 end
1175
1176 /*
1177 *
1178 * This is the timer that manages the overall control loop timeout.
1179 *
1180 */
1181 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
1182     timer (expr: $to )
1183     when
1184         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1185         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1186         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
1187         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString(), $to : getDelay() )
1188     then
1189     
1190     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1191     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1192
1193     logger.debug("{}: {}: event={}", 
1194               $params.getClosedLoopControlName(), drools.getRule().getName(),
1195               $event);
1196     //
1197     // Tell the Event Manager it has timed out
1198     //
1199     VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
1200     if (notification != null) {
1201         notification.setFrom("policy");
1202         notification.setPolicyName(drools.getRule().getName());
1203         notification.setPolicyScope("${policyScope}");
1204         notification.setPolicyVersion("${policyVersion}");
1205         //
1206         // Let interested parties know
1207         //
1208         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1209     }
1210     //
1211     // Retract the event
1212     //
1213     retract($event);
1214 end
1215
1216 /*
1217 *
1218 * This rule cleans up the manager and other objects after an event has
1219 * been retracted.
1220 *
1221 */
1222 rule "${policyName}.EVENT.MANAGER.CLEANUP"
1223     when
1224         $manager : ControlLoopEventManager( $clName : getClosedLoopControlName(), $requestId : getRequestID() )
1225         $clTimer : ControlLoopTimer ( closedLoopControlName == $clName, requestID == $requestId.toString() )
1226         $operations : LinkedList()
1227                         from collect( ControlLoopOperationManager( onset.closedLoopControlName == $clName, onset.getRequestId() == $requestId ) )
1228         $opTimers : LinkedList()
1229                         from collect( OperationTimer( closedLoopControlName == $clName, requestID == $requestId.toString() ) )
1230         $locks : LinkedList()
1231                         from collect( TargetLock (requestID == $requestId) )
1232         not( VirtualControlLoopEvent( closedLoopControlName == $clName, requestId == $requestId ) )
1233     then
1234     
1235     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1236     logger.info("{}: {}", $clName, drools.getRule().getName());
1237
1238     logger.debug("{}: {}: manager={} clTimer={} operations={}", 
1239               $clName, drools.getRule().getName(),
1240               $manager, $clTimer, $operations.size());
1241     
1242     //
1243     // Retract EVERYTHING
1244     //
1245     retract($manager);
1246     retract($clTimer);
1247     
1248     for(Object manager: $operations) {
1249         retract((ControlLoopOperationManager) manager);
1250     }
1251     for(Object opTimer: $opTimers) {
1252         retract((OperationTimer) opTimer);
1253     }
1254     for(Object lock: $locks) {
1255         TargetLock tgt = (TargetLock) lock;
1256         //
1257         // Ensure we release the lock
1258         //
1259         PolicyGuard.unlockTarget(tgt);
1260         retract(tgt);
1261     }
1262 end
1263
1264 /*
1265 *
1266 * This rule will clean up any rogue onsets where there is no 
1267 * ControlLoopParams object corresponding to the onset event.
1268 *
1269 */
1270 rule "${policyName}.EVENT.CLEANUP"
1271     when
1272         $event : VirtualControlLoopEvent( $clName: closedLoopControlName )
1273         not ( Params( getClosedLoopControlName() == $clName) )
1274     then
1275  
1276     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1277     logger.info("{}: {}", $clName, drools.getRule().getName());
1278     logger.debug("{}: {}: orphan onset event={}", 
1279                 $clName, drools.getRule().getName(), $event);
1280
1281     retract($event);
1282 end
1283
1284 /*
1285 *
1286 * When rules are deleted, the associated Params (and its subordinate objects)
1287 * remain in working memory, because there are no longer any rules to clean
1288 * them up.  However, ANY time new rules are loaded, this rule will trigger
1289 * a clean-up of ALL Params, regardless of their name & yaml, thus removing
1290 * any that no longer have associated rules.
1291 * This has a higher salience so that we immediately check Params when the
1292 * rules change, before processing any events.
1293 *
1294 */
1295 rule "${policyName}.PARAMS.CHECKUP"
1296     salience 2
1297     when
1298         Params( $clName: closedLoopControlName, $yaml: controlLoopYaml )
1299     then
1300  
1301     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1302     logger.info("{}: {} : YAML=[{}]", $clName, drools.getRule().getName(), $yaml);
1303     
1304     ParamsCleaner cleaner = new ParamsCleaner();
1305     cleaner.setClosedLoopControlName($clName);
1306     cleaner.setControlLoopYaml($yaml);
1307     
1308     insert(cleaner);
1309 end
1310
1311 /*
1312 *
1313 * This rule removes "cleaner" objects for rules that are still active, thus
1314 * preventing the associated Params objects from being removed.  Any cleaners
1315 * that are left after this rule has fired will cause their corresponding Params
1316 * to be removed.
1317 * This has a higher salience so that we discard the cleaner before it has
1318 * a chance to force the removal of the associated Params.
1319 *
1320 */
1321 rule "${policyName}.CLEANER.ACTIVE"
1322     salience 2
1323     when
1324         $cleaner: ParamsCleaner( getClosedLoopControlName() == "${closedLoopControlName}", getControlLoopYaml() == "${controlLoopYaml}" )
1325     then
1326  
1327     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1328     logger.info("{}: {} : YAML=[{}]", $cleaner.getClosedLoopControlName(), drools.getRule().getName(), $cleaner.getControlLoopYaml());
1329     
1330     retract($cleaner);
1331 end
1332
1333 /*
1334 *
1335 * This rule removes Params objects that no longer have associated rules; if a
1336 * Params still had associated rules, then the cleaner would have been removed
1337 * by those rules and thus this rule would not fire.
1338 * This has a higher salience so that we remove old Params before it causes any
1339 * events to be processed.
1340 *
1341 */
1342 rule "${policyName}.PARAMS.CLEANUP"
1343     salience 1
1344     when
1345         $params: Params( $clName: closedLoopControlName, $yaml: controlLoopYaml )
1346         ParamsCleaner( getClosedLoopControlName() == $clName, getControlLoopYaml() == $yaml )
1347     then
1348  
1349     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1350     logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(), $params.getControlLoopYaml());
1351     
1352     retract($params);
1353     
1354     // Note: the cleaner may be needed for cleaning additional params, thus
1355     // we do not retract it here - we'll leave that to another rule
1356 end
1357
1358 /*
1359 *
1360 * This rule removes "cleaner" objects when they're no longer needed.
1361 *
1362 */
1363 rule "${policyName}.CLEANER.CLEANUP"
1364     when
1365         $cleaner: ParamsCleaner( )
1366     then
1367  
1368     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1369     logger.info("{}: {} : YAML=[{}]", $cleaner.getClosedLoopControlName(), drools.getRule().getName(), $cleaner.getControlLoopYaml());
1370     
1371     retract($cleaner);
1372 end