71715c07598e78bea0e2e1f6c566b3f30bb779c7
[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     
525     try {
526         request = $operation.startOperation($event);
527         
528             if (request != null) {
529               logger.debug("{}: {}: starting operation ..", 
530                            $params.getClosedLoopControlName(), drools.getRule().getName());
531               //
532               // Tell interested parties we are performing this Operation
533               //
534               VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
535               notification.setNotification(ControlLoopNotificationType.OPERATION);
536               notification.setMessage($operation.getOperationMessage());
537               notification.setHistory($operation.getHistory());
538               notification.setFrom("policy");
539               notification.setPolicyName(drools.getRule().getName());
540               notification.setPolicyScope("${policyScope}");
541               notification.setPolicyVersion("${policyVersion}");
542               
543               PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
544               
545               switch ($operation.policy.getActor()){
546                   
547                   case "APPC":
548               
549                       if (request instanceof Request) {
550                           PolicyEngine.manager.deliver("APPC-CL", request);
551                       }
552                       else if (request instanceof LcmRequestWrapper) {
553                           PolicyEngine.manager.deliver("APPC-LCM-READ", request);
554                       }
555                       break;
556                   case "SO":
557                       // at this point the AAI named query request should have already been made, the response recieved and used
558                       // in the construction of the SO Request which is stored in operationRequest
559                       
560                       if(request instanceof SORequest) {
561                           // Call SO. The response will be inserted into memory once it's received 
562                           SOActorServiceProvider.sendRequest($event.getRequestId().toString(), drools.getWorkingMemory(), request);                        
563                       }
564                       break;
565                   case "VFC":
566                       if (request instanceof VFCRequest) {
567                           // Start VFC thread
568                           Thread t = new Thread(new VFCManager(drools.getWorkingMemory(), (VFCRequest)request));
569                           t.start();
570                       }          
571                       break;
572               }
573             } else {
574               //
575               // What happens if its null?
576               //
577                 logger.warn("{}: {}: unexpected null operation request", 
578                           $params.getClosedLoopControlName(), 
579                           drools.getRule().getName());
580                 if ("SO".equals($operation.policy.getActor())) {
581                     retract($opTimer);
582                     retract($operation);
583                     modify($manager) {finishOperation($operation)};
584                 }
585                 else if ("vfc".equalsIgnoreCase($operation.policy.getActor())) {
586                     retract($opTimer);
587                     retract($operation);
588                     modify($manager) {finishOperation($operation)};
589                 }
590             }
591             
592     } catch (Exception e) {
593         String msg = e.getMessage();
594         logger.warn("{}: {}: operation={}:  AAI failure: {}", 
595                     $params.getClosedLoopControlName(), drools.getRule().getName(),
596                     $operation, msg, e);
597         $operation.setOperationHasException(msg);
598         
599         if(request != null) {
600                 //
601                 // Create a notification for it ("DB Write - end operation")
602                 //
603                 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
604                 notification.setFrom("policy");
605                 notification.setPolicyName(drools.getRule().getName());
606                 notification.setPolicyScope("${policyScope}");
607                 notification.setPolicyVersion("${policyVersion}");
608                 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
609                 notification.setMessage($operation.getOperationHistory());
610                 notification.setHistory($operation.getHistory());
611           
612             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
613         }
614     
615         retract($opTimer);
616         retract($operation);
617         caughtException = true;
618     }
619     
620     // Having the modify statement in the catch clause doesn't work for whatever reason
621     if (caughtException) {
622         modify($manager) {finishOperation($operation)};
623     }
624 end
625
626
627 /*
628 *
629 * We were able to acquire a lock so now let's ask Xacml Guard whether 
630 * we are allowed to proceed with the request to the actor.
631 *
632 */
633 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
634     when
635         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
636         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
637         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
638         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId(), getGuardApprovalStatus() == "NONE" )
639         $lock : TargetLock (requestID == $event.getRequestId())
640     then
641
642     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
643     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
644                 $params.getClosedLoopControlName(), drools.getRule().getName(),
645                 $event, $manager, $operation, $lock);
646     
647     //
648     // Sending notification that we are about to query Guard ("DB write - start operation")
649     //
650     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
651     notification.setNotification(ControlLoopNotificationType.OPERATION);
652     notification.setMessage("Sending guard query for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe());
653     notification.setHistory($operation.getHistory());
654     notification.setFrom("policy");
655     notification.setPolicyName(drools.getRule().getName());
656     notification.setPolicyScope("${policyScope}");
657     notification.setPolicyVersion("${policyVersion}");
658     
659     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
660         
661     //
662     // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, 
663     // just change guardEnabled to false.
664     // 
665     // In order to use REST XACML, provide a URL instead of "" as a second argument 
666     // to the CallGuardTask() and set the first argument to null 
667     // (instead of XacmlPdpEngine).
668     //
669     
670     // NOTE: The environment properties uses "guard.disabled" but the boolean is guardEnabled
671     boolean guardEnabled = "false".equalsIgnoreCase(PolicyEngine.manager.getEnvironmentProperty("guard.disabled"));
672     
673     if(guardEnabled){
674     
675         Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
676                                                         drools.getWorkingMemory(),
677                                                         $event.getClosedLoopControlName(),
678                                                         $operation.policy.getActor().toString(),
679                                                         $operation.policy.getRecipe(),
680                                                         $operation.getTargetEntity(),
681                                                         $event.getRequestId().toString()
682                                                         ));
683         t.start();
684     }
685     else{
686         insert(new PolicyGuardResponse("Permit", $event.getRequestId(), $operation.policy.getRecipe()));
687     }
688
689 end
690
691 //
692 // This rule will be triggered when a thread talking to the XACML Guard inserts a 
693 // guardResponse object into the working memory
694 //
695 rule "${policyName}.GUARD.RESPONSE"
696     when
697         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
698         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
699         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() ) 
700         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
701         $lock : TargetLock (requestID == $event.getRequestId())
702         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
703         $guardResponse : PolicyGuardResponse(requestID == $event.getRequestId(), $operation.policy.recipe == operation)
704     then
705
706     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
707     logger.info("{}: {}: event={} manager={} operation={} lock={} opTimer={} guardResponse={}", 
708                  $params.getClosedLoopControlName(), drools.getRule().getName(),
709                  $event, $manager, $operation, $lock, $opTimer, $guardResponse);
710         
711         
712     //we will permit the operation if there was no Guard for it
713     if("Indeterminate".equalsIgnoreCase($guardResponse.getResult())){
714         $guardResponse.setResult("Permit");
715     }
716     
717     //
718     // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
719     //
720     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
721     notification.setNotification(ControlLoopNotificationType.OPERATION);
722     notification.setMessage("Guard result for " + $operation.policy.getActor() + " " + $operation.policy.getRecipe() + " is " + $guardResponse.getResult());
723     notification.setHistory($operation.getHistory());
724     notification.setFrom("policy");
725     notification.setPolicyName(drools.getRule().getName());
726     notification.setPolicyScope("${policyScope}");
727     notification.setPolicyVersion("${policyVersion}");
728     
729     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
730     
731     if("Permit".equalsIgnoreCase($guardResponse.getResult())){
732     
733         modify($operation){setGuardApprovalStatus($guardResponse.getResult())};
734     }
735     else {
736         //This is the Deny case
737         $operation.startOperation($event);
738         $operation.setOperationHasGuardDeny();
739         retract($opTimer);
740         retract($operation);
741         modify($manager) {finishOperation($operation)};
742     }
743     
744     retract($guardResponse);
745             
746 end
747
748 /*
749 *
750 * This rule responds to APPC Response Events
751 *
752 * I would have like to be consistent and write the Response like this:
753 * $response : Response( CommonHeader.RequestId == $onset.getRequestId() )
754 *
755 * However, no compile error was given. But a runtime error was given. I think
756 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
757 *
758 */
759 rule "${policyName}.APPC.RESPONSE"
760     when
761         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
762         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
763         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
764         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
765         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
766         $lock : TargetLock (requestID == $event.getRequestId())
767         $response : Response( getCommonHeader().RequestId == $event.getRequestId() )
768     then
769
770     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
771     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
772     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
773                  $params.getClosedLoopControlName(), drools.getRule().getName(),
774                  $event, $manager, $operation, $lock, $opTimer, $response);
775     //
776     // Get the result of the operation
777     //
778     PolicyResult policyResult = $operation.onResponse($response);
779     if (policyResult != null) {
780         logger.debug("{}: {}: operation finished - result={}", 
781                     $params.getClosedLoopControlName(), drools.getRule().getName(),
782                     policyResult);
783         //
784         // This Operation has completed, construct a notification showing our results. (DB write - end operation)
785         //
786         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
787         notification.setFrom("policy");
788         notification.setPolicyName(drools.getRule().getName());
789         notification.setPolicyScope("${policyScope}");
790         notification.setPolicyVersion("${policyVersion}");
791         notification.setMessage($operation.getOperationHistory());
792         notification.setHistory($operation.getHistory());
793         if (policyResult.equals(PolicyResult.SUCCESS)) {
794             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
795             //
796             // Let interested parties know
797             //
798             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
799         } else {
800             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
801             //
802             // Let interested parties know
803             //
804             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
805         }
806         //
807         // Ensure the operation is complete
808         //
809         if ($operation.isOperationComplete() == true) {
810             //
811             // It is complete, remove it from memory
812             //
813             retract($operation);
814             //
815             // We must also retract the timer object
816             // NOTE: We could write a Rule to do this
817             //
818             retract($opTimer);
819             //
820             // Complete the operation
821             //
822             modify($manager) {finishOperation($operation)};
823         } else {
824             //
825             // Just doing this will kick off the LOCKED rule again
826             //
827             modify($operation) {};
828         }
829     } else {
830         //
831         // Its not finished yet (i.e. expecting more Response objects)
832         //
833         // Or possibly it is a leftover response that we timed the request out previously
834         //
835     }
836     //
837     // We are going to retract these objects from memory
838     //
839     retract($response);
840 end
841
842 /*
843 *
844 * The problem with Responses is that they don't have a controlLoopControlName
845 * field in them, so the only way to attach them is via RequestId. If we have multiple
846 * control loop .drl's loaded in the same container, we need to be sure the cleanup
847 * rules don't remove Responses for other control loops.
848 *
849 */
850 rule "${policyName}.APPC.RESPONSE.CLEANUP"
851     when
852         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
853         $response : Response($id : getCommonHeader().RequestId )
854         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
855     then
856
857     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
858     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
859     logger.debug("{}: {}: orphan appc response={}", 
860                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
861         
862     //
863     // Retract it
864     //
865     retract($response);
866 end
867
868 /*
869 *
870 * This rule responds to APPC Response Events using the new LCM interface provided by appc
871 *
872 */
873 rule "${policyName}.APPC.LCM.RESPONSE"
874     when
875         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
876         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
877         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
878         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
879         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
880         $lock : TargetLock (requestID == $event.getRequestId())
881         $response : LcmResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.getRequestId() )
882     then
883
884     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
885     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
886     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
887                 $params.getClosedLoopControlName(), drools.getRule().getName(),
888                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
889     
890     //
891     // Get the result of the operation
892     //
893     PolicyResult policyResult = $operation.onResponse($response);
894     if (policyResult != null) {
895       logger.debug("{}: {}: operation finished - result={}", 
896                   $params.getClosedLoopControlName(), drools.getRule().getName(),
897                   policyResult);
898       
899       //
900       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
901       //
902       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
903       notification.setFrom("policy");
904       notification.setPolicyName(drools.getRule().getName());
905       notification.setPolicyScope("${policyScope}");
906       notification.setPolicyVersion("${policyVersion}");
907       notification.setMessage($operation.getOperationHistory());
908       notification.setHistory($operation.getHistory());
909       if (policyResult.equals(PolicyResult.SUCCESS)) {
910           notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
911       } else {
912           notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
913       }
914       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
915       //
916       // Ensure the operation is complete
917       //
918       if ($operation.isOperationComplete() == true) {
919           //
920           // It is complete, remove it from memory
921           //
922           retract($operation);
923           //
924           // We must also retract the timer object
925           // NOTE: We could write a Rule to do this
926           //
927           retract($opTimer);
928           //
929           // Complete the operation
930           //
931           modify($manager) {finishOperation($operation)};
932       } else {
933           //
934           // Just doing this will kick off the LOCKED rule again
935           //
936           modify($operation) {};
937       }
938     } else {
939         //
940         // Its not finished yet (i.e. expecting more Response objects)
941         //
942         // Or possibly it is a leftover response that we timed the request out previously
943         //
944     }
945     //
946     // We are going to retract these objects from memory
947     //
948     retract($response);
949 end
950
951 /*
952 *
953 * Clean Up any lingering LCM reponses
954 *
955 */
956 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
957     when
958         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
959         $response : LcmResponseWrapper($id : getBody().getCommonHeader().getRequestId )
960         not ( VirtualControlLoopEvent( requestId == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
961     then
962     
963     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
964     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
965     logger.debug("{}: {}: orphan appc response={}", 
966                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
967     //
968     // Retract it
969     //
970     retract($response);
971 end
972
973 /*
974 *
975 * This rule responds to SO Response Events
976 *
977 */
978 rule "${policyName}.SO.RESPONSE"
979     when
980         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
981         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
982         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
983         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
984         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
985         $lock : TargetLock (requestID == $event.getRequestId())
986         $response : SOResponseWrapper(requestID.toString() == $event.getRequestId().toString() )
987     then
988                         
989     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
990     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
991     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
992                 $params.getClosedLoopControlName(), drools.getRule().getName(),
993                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
994         
995     // Get the result of the operation
996     //
997     PolicyResult policyResult = $operation.onResponse($response);
998     if (policyResult != null) {
999         logger.debug("{}: {}: operation finished - result={}", 
1000                     $params.getClosedLoopControlName(), drools.getRule().getName(),
1001                     policyResult);
1002       
1003         //
1004         // This Operation has completed, construct a notification showing our results
1005         //
1006         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1007         notification.setFrom("policy");
1008         notification.setPolicyName(drools.getRule().getName());
1009         notification.setPolicyScope("${policyScope}");
1010         notification.setPolicyVersion("${policyVersion}");
1011         notification.setMessage($operation.getOperationHistory());
1012         notification.setHistory($operation.getHistory());
1013         if (policyResult.equals(PolicyResult.SUCCESS)) {
1014             notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
1015         } else {
1016             notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1017
1018         }
1019         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1020         //
1021         // Ensure the operation is complete
1022         //
1023         if ($operation.isOperationComplete() == true) {
1024             //
1025             // It is complete, remove it from memory
1026             //
1027             retract($operation);
1028             //
1029             // We must also retract the timer object
1030             // NOTE: We could write a Rule to do this
1031             //
1032             retract($opTimer);
1033             //
1034             // Complete the operation
1035             //
1036             modify($manager) {finishOperation($operation)};
1037         } else {
1038             //
1039             // Just doing this will kick off the LOCKED rule again
1040             //
1041             modify($operation) {};
1042         }
1043     } else {
1044         //
1045         // Its not finished yet (i.e. expecting more Response objects)
1046         //
1047         // Or possibly it is a leftover response that we timed the request out previously
1048         //
1049     }
1050     //
1051     // We are going to retract these objects from memory
1052     //
1053     retract($response);
1054
1055 end
1056
1057 /*
1058 *
1059 * This rule responds to VFC Response Events
1060 *
1061 */
1062 rule "${policyName}.VFC.RESPONSE"
1063         when
1064                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1065                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1066                 $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
1067                 $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
1068                 $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString() )
1069         $lock : TargetLock (requestID == $event.getRequestId())
1070                 $response : VFCResponse( requestId.toString() == $event.getRequestId().toString() )     
1071         then
1072                 Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1073         logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1074         logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
1075                         $params.getClosedLoopControlName(), drools.getRule().getName(),
1076                         $event, $manager, $operation, $lock, $operation, $opTimer, $response);
1077                 
1078                 // Get the result of the operation
1079                 //
1080                 PolicyResult policyResult = $operation.onResponse($response);
1081                 if (policyResult != null) {
1082                         //
1083                         // This Operation has completed, construct a notification showing our results
1084                         //
1085                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1086                         notification.setFrom("policy");
1087                         notification.setPolicyName(drools.getRule().getName());
1088                         notification.setPolicyScope("${policyScope}");
1089                         notification.setPolicyVersion("${policyVersion}");
1090                         notification.setMessage($operation.getOperationHistory());
1091                         notification.setHistory($operation.getHistory());
1092                         //
1093                         // Ensure the operation is complete
1094                         //
1095                         if ($operation.isOperationComplete() == true) {
1096                                 //
1097                                 // It is complete, remove it from memory
1098                                 //
1099                                 retract($operation);
1100                                 //
1101                                 // We must also retract the timer object
1102                                 // NOTE: We could write a Rule to do this
1103                                 //
1104                                 retract($opTimer);
1105                                 //
1106                                 // Complete the operation
1107                                 //
1108                                 modify($manager) {finishOperation($operation)};
1109                         } else {
1110                                 //
1111                                 // Just doing this will kick off the LOCKED rule again
1112                                 //
1113                                 modify($operation) {};
1114                         }
1115                 } else {
1116                         //
1117                         // Its not finished yet (i.e. expecting more Response objects)
1118                         //
1119                         // Or possibly it is a leftover response that we timed the request out previously
1120                         //
1121                 }
1122                 //
1123                 // We are going to retract these objects from memory
1124                 //
1125                 retract($response);
1126
1127 end
1128
1129 /*
1130 *
1131 * This is the timer that manages the timeout for an individual operation.
1132 *
1133 */
1134 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
1135     timer (expr: $to )
1136     when
1137         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1138         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1139         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
1140         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.getClosedLoopControlName(), onset.getRequestId() == $event.getRequestId() )
1141         $opTimer : OperationTimer( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString(), $to : getDelay() )
1142         $lock : TargetLock (requestID == $event.getRequestId())
1143     then
1144     
1145     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1146     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1147     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={}", 
1148                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1149                 $event, $manager, $operation, $lock, $operation, $opTimer);
1150     
1151     //
1152     // Tell it its timed out
1153     //
1154     $operation.setOperationHasTimedOut();
1155     //
1156     // Create a notification for it ("DB Write - end operation")
1157     //
1158     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1159     notification.setFrom("policy");
1160     notification.setPolicyName(drools.getRule().getName());
1161     notification.setPolicyScope("${policyScope}");
1162     notification.setPolicyVersion("${policyVersion}");
1163     notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
1164     notification.setMessage($operation.getOperationHistory());
1165     notification.setHistory($operation.getHistory());
1166     //
1167     // Let interested parties know
1168     //
1169     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1170     //
1171     // Get rid of the timer
1172     //
1173     retract($opTimer);
1174     //
1175     // Ensure the operation is complete
1176     //
1177     if ($operation.isOperationComplete() == true) {
1178         //
1179         // It is complete, remove it from memory
1180         //
1181         retract($operation);
1182         //
1183         // Complete the operation
1184         //
1185         modify($manager) {finishOperation($operation)};
1186     } else {
1187         //
1188         // Just doing this will kick off the LOCKED rule again
1189         //
1190         modify($operation) {};
1191     }
1192 end
1193
1194 /*
1195 *
1196 * This is the timer that manages the overall control loop timeout.
1197 *
1198 */
1199 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
1200     timer (expr: $to )
1201     when
1202         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1203         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1204         $manager : ControlLoopEventManager( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId() )
1205         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.getClosedLoopControlName(), requestID == $event.getRequestId().toString(), $to : getDelay() )
1206     then
1207     
1208     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1209     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1210
1211     logger.debug("{}: {}: event={}", 
1212               $params.getClosedLoopControlName(), drools.getRule().getName(),
1213               $event);
1214     //
1215     // Tell the Event Manager it has timed out
1216     //
1217     VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
1218     if (notification != null) {
1219         notification.setFrom("policy");
1220         notification.setPolicyName(drools.getRule().getName());
1221         notification.setPolicyScope("${policyScope}");
1222         notification.setPolicyVersion("${policyVersion}");
1223         //
1224         // Let interested parties know
1225         //
1226         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1227     }
1228     //
1229     // Retract the event
1230     //
1231     retract($event);
1232 end
1233
1234 /*
1235 *
1236 * This rule cleans up the manager and other objects after an event has
1237 * been retracted.
1238 *
1239 */
1240 rule "${policyName}.EVENT.MANAGER.CLEANUP"
1241     when
1242         $manager : ControlLoopEventManager( $clName : getClosedLoopControlName(), $requestId : getRequestID() )
1243         $clTimer : ControlLoopTimer ( closedLoopControlName == $clName, requestID == $requestId.toString() )
1244         $operations : LinkedList()
1245                         from collect( ControlLoopOperationManager( onset.closedLoopControlName == $clName, onset.getRequestId() == $requestId ) )
1246         $opTimers : LinkedList()
1247                         from collect( OperationTimer( closedLoopControlName == $clName, requestID == $requestId.toString() ) )
1248         $locks : LinkedList()
1249                         from collect( TargetLock (requestID == $requestId) )
1250         not( VirtualControlLoopEvent( closedLoopControlName == $clName, requestId == $requestId ) )
1251     then
1252     
1253     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1254     logger.info("{}: {}", $clName, drools.getRule().getName());
1255
1256     logger.debug("{}: {}: manager={} clTimer={} operations={}", 
1257               $clName, drools.getRule().getName(),
1258               $manager, $clTimer, $operations.size());
1259     
1260     //
1261     // Retract EVERYTHING
1262     //
1263     retract($manager);
1264     retract($clTimer);
1265     
1266     for(Object manager: $operations) {
1267         retract((ControlLoopOperationManager) manager);
1268     }
1269     for(Object opTimer: $opTimers) {
1270         retract((OperationTimer) opTimer);
1271     }
1272     for(Object lock: $locks) {
1273         TargetLock tgt = (TargetLock) lock;
1274         //
1275         // Ensure we release the lock
1276         //
1277         PolicyGuard.unlockTarget(tgt);
1278         retract(tgt);
1279     }
1280 end
1281
1282 /*
1283 *
1284 * This rule will clean up any rogue onsets where there is no 
1285 * ControlLoopParams object corresponding to the onset event.
1286 *
1287 */
1288 rule "${policyName}.EVENT.CLEANUP"
1289     when
1290         $event : VirtualControlLoopEvent( $clName: closedLoopControlName )
1291         not ( Params( getClosedLoopControlName() == $clName) )
1292     then
1293  
1294     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1295     logger.info("{}: {}", $clName, drools.getRule().getName());
1296     logger.debug("{}: {}: orphan onset event={}", 
1297                 $clName, drools.getRule().getName(), $event);
1298
1299     retract($event);
1300 end
1301
1302 /*
1303 *
1304 * When rules are deleted, the associated Params (and its subordinate objects)
1305 * remain in working memory, because there are no longer any rules to clean
1306 * them up.  However, ANY time new rules are loaded, this rule will trigger
1307 * a clean-up of ALL Params, regardless of their name & yaml, thus removing
1308 * any that no longer have associated rules.
1309 * This has a higher salience so that we immediately check Params when the
1310 * rules change, before processing any events.
1311 *
1312 */
1313 rule "${policyName}.PARAMS.CHECKUP"
1314     salience 2
1315     when
1316         Params( $clName: closedLoopControlName, $yaml: controlLoopYaml )
1317     then
1318  
1319     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1320     logger.info("{}: {} : YAML=[{}]", $clName, drools.getRule().getName(), $yaml);
1321     
1322     ParamsCleaner cleaner = new ParamsCleaner();
1323     cleaner.setClosedLoopControlName($clName);
1324     cleaner.setControlLoopYaml($yaml);
1325     
1326     insert(cleaner);
1327 end
1328
1329 /*
1330 *
1331 * This rule removes "cleaner" objects for rules that are still active, thus
1332 * preventing the associated Params objects from being removed.  Any cleaners
1333 * that are left after this rule has fired will cause their corresponding Params
1334 * to be removed.
1335 * This has a higher salience so that we discard the cleaner before it has
1336 * a chance to force the removal of the associated Params.
1337 *
1338 */
1339 rule "${policyName}.CLEANER.ACTIVE"
1340     salience 2
1341     when
1342         $cleaner: ParamsCleaner( getClosedLoopControlName() == "${closedLoopControlName}", getControlLoopYaml() == "${controlLoopYaml}" )
1343     then
1344  
1345     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1346     logger.info("{}: {} : YAML=[{}]", $cleaner.getClosedLoopControlName(), drools.getRule().getName(), $cleaner.getControlLoopYaml());
1347     
1348     retract($cleaner);
1349 end
1350
1351 /*
1352 *
1353 * This rule removes Params objects that no longer have associated rules; if a
1354 * Params still had associated rules, then the cleaner would have been removed
1355 * by those rules and thus this rule would not fire.
1356 * This has a higher salience so that we remove old Params before it causes any
1357 * events to be processed.
1358 *
1359 */
1360 rule "${policyName}.PARAMS.CLEANUP"
1361     salience 1
1362     when
1363         $params: Params( $clName: closedLoopControlName, $yaml: controlLoopYaml )
1364         ParamsCleaner( getClosedLoopControlName() == $clName, getControlLoopYaml() == $yaml )
1365     then
1366  
1367     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1368     logger.info("{}: {} : YAML=[{}]", $params.getClosedLoopControlName(), drools.getRule().getName(), $params.getControlLoopYaml());
1369     
1370     retract($params);
1371     
1372     // Note: the cleaner may be needed for cleaning additional params, thus
1373     // we do not retract it here - we'll leave that to another rule
1374 end
1375
1376 /*
1377 *
1378 * This rule removes "cleaner" objects when they're no longer needed.
1379 *
1380 */
1381 rule "${policyName}.CLEANER.CLEANUP"
1382     when
1383         $cleaner: ParamsCleaner( )
1384     then
1385  
1386     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1387     logger.info("{}: {} : YAML=[{}]", $cleaner.getClosedLoopControlName(), drools.getRule().getName(), $cleaner.getControlLoopYaml());
1388     
1389     retract($cleaner);
1390 end