9cf395d720604b51f98d44cf5b412ccace113186
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
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.mso.MSOActorServiceProvider;
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.VFCManager;
45 import org.onap.policy.mso.SOManager;
46 import org.onap.policy.mso.SORequest;
47 import org.onap.policy.mso.SORequestStatus;
48 import org.onap.policy.mso.SORequestDetails;
49 import org.onap.policy.mso.SOModelInfo;
50 import org.onap.policy.mso.SOCloudConfiguration;
51 import org.onap.policy.mso.SORequestInfo;
52 import org.onap.policy.mso.SORequestParameters;
53 import org.onap.policy.mso.SORelatedInstanceListElement;
54 import org.onap.policy.mso.SORelatedInstance;
55 import org.onap.policy.mso.SOResponse;
56 import org.onap.policy.guard.PolicyGuard;
57 import org.onap.policy.guard.PolicyGuard.LockResult;
58 import org.onap.policy.guard.TargetLock;
59 import org.onap.policy.guard.GuardResult;
60 import org.onap.policy.guard.PolicyGuardRequest;
61 import org.onap.policy.guard.PolicyGuardResponse;
62 import org.onap.policy.guard.PolicyGuardXacmlRequestAttributes;
63 import org.onap.policy.guard.PolicyGuardXacmlHelper;
64
65 import org.yaml.snakeyaml.Yaml;
66 import org.yaml.snakeyaml.constructor.Constructor;
67
68 import org.slf4j.LoggerFactory;
69 import org.slf4j.Logger;
70
71 import java.time.Instant;
72 import java.util.LinkedList;
73 import java.util.Iterator;
74
75 import org.onap.policy.drools.system.PolicyEngine;
76
77 declare Params
78   closedLoopControlName : String
79   controlLoopYaml : String
80 end
81
82
83 declare OperationTimer
84   closedLoopControlName : String
85   requestID : String
86   delay : String
87 end
88
89 declare ControlLoopTimer
90   closedLoopControlName : String
91   requestID : String
92   delay : String
93 end
94
95 /*
96 *
97 * Called once and only once to insert the parameters into working memory for this Closed Loop policy.
98 *
99 */
100 rule "${policyName}.SETUP"
101     when
102     then
103     
104     Params params = new Params();
105     params.setClosedLoopControlName("${closedLoopControlName}");
106     params.setControlLoopYaml("${controlLoopYaml}");
107     insert(params);
108
109
110     // Note: globals have bad behavior when persistence is used,
111     //       hence explicitly getting the logger vs using a global
112     
113     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
114     logger.info("{}: {} : YAML=[{}]", params.getClosedLoopControlName(), drools.getRule().getName(), params.getControlLoopYaml());
115 end
116
117 /*
118 *
119 * This rule responds to DCAE Events where there is no manager yet. Either it is
120 * the first ONSET, or a subsequent badly formed Event (i.e. Syntax error, or is-closed-loop-disabled)
121 *
122 */
123 rule "${policyName}.EVENT"
124     when
125         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
126         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
127         not ( ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) )
128     then
129  
130     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
131     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
132     
133     try {
134       
135         //
136         // Check the event, because we need it to not be null when
137         // we create the ControlLoopEventManager. The ControlLoopEventManager
138         // will do extra syntax checking as well check if the closed loop is disabled.
139         //
140         if ($event.requestID == null) {
141             VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
142             notification.notification = ControlLoopNotificationType.REJECTED;
143             notification.from = "policy";
144             notification.message = "Missing requestID";
145             notification.policyName = drools.getRule().getName();
146             notification.policyScope = "${policyScope}";
147             notification.policyVersion = "${policyVersion}";
148             
149             //
150             // Let interested parties know
151             //
152             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
153             
154             //
155             // Retract it from memory
156             //
157             retract($event);
158         } else {
159             //
160             // Create an EventManager
161             //
162             ControlLoopEventManager manager = new ControlLoopEventManager($params.getClosedLoopControlName(), $event.requestID);
163             //
164             // Determine if EventManager can actively process the event (i.e. syntax, is_closed_loop_disabled checks etc.)
165             //
166             VirtualControlLoopNotification notification = manager.activate($params.getControlLoopYaml(), $event);
167             notification.from = "pdp-0001-controller=controlloop"; // Engine.getInstanceName()
168             notification.policyName = drools.getRule().getName();
169             notification.policyScope = "${policyScope}";
170             notification.policyVersion = "${policyVersion}";
171             //
172             // Are we actively pursuing this event?
173             //
174             if (notification.notification == ControlLoopNotificationType.ACTIVE) {
175                 //
176                 // Insert Event Manager into memory, this will now kick off processing.
177                 //
178                 insert(manager);
179                 //
180                 // Let interested parties know
181                 //
182                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
183                 //
184                 // Setup the Overall Control Loop timer
185                 //
186                 ControlLoopTimer clTimer = new ControlLoopTimer();
187                 clTimer.setClosedLoopControlName($event.closedLoopControlName);
188                 clTimer.setRequestID($event.requestID.toString());
189                 clTimer.setDelay(manager.getControlLoopTimeout(1500) + "s");
190                 //
191                 // Insert it
192                 //
193                 insert(clTimer);
194             } else {
195                 //
196                 // Let interested parties know
197                 //
198                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
199                 //
200                 // Retract it from memory
201                 //
202                 retract($event);
203             }
204             
205             //
206             // Now that the manager is inserted into Drools working memory, we'll wait for
207             // another rule to fire in order to continue processing. This way we can also
208             // then screen for additional ONSET and ABATED events for this RequestID.
209             //
210         }
211     } catch (Exception e) {
212         logger.warn("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName(), e);
213         
214         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
215         notification.notification = ControlLoopNotificationType.REJECTED;
216         notification.message = "Exception occurred " + e.getMessage();
217         notification.policyName = drools.getRule().getName();
218         notification.policyScope = "${policyScope}";
219         notification.policyVersion = "${policyVersion}";
220         //
221         //
222         //
223         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
224         //
225         // Retract the event
226         //
227         retract($event);
228     }
229 end
230
231 /*
232 *
233 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
234 * is now created. We can start processing the yaml specification via the Event Manager.
235 *
236 */
237 rule "${policyName}.EVENT.MANAGER"
238     when
239         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
240         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
241         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
242         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
243     then
244
245     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
246     logger.info("{}: {}: event={} manager={} clTimer={}", 
247                 $params.getClosedLoopControlName(), drools.getRule().getName(),
248                 $event, $manager, $clTimer);
249     //
250     // Check which event this is.
251     //
252     ControlLoopEventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);
253
254     //
255     // Check what kind of event this is
256     //
257     if (eventStatus == NEW_EVENT_STATUS.SUBSEQUENT_ONSET) {
258         //
259         // We don't care about subsequent onsets
260         //
261         logger.info("{}: {}: subsequent onset", 
262                     $params.getClosedLoopControlName(), drools.getRule().getName());
263         retract($event);
264         return;
265     }
266     if (eventStatus == NEW_EVENT_STATUS.SYNTAX_ERROR) {
267         //
268         // Ignore any bad syntax events
269         //
270         logger.warn("{}: {}: syntax error", 
271                     $params.getClosedLoopControlName(), drools.getRule().getName());
272         retract($event);
273         return;
274     }
275     //
276     // We only want the initial ONSET event in memory,
277     // all the other events need to be retracted to support
278     // cleanup and avoid the other rules being fired for this event.
279     //
280     if (eventStatus != NEW_EVENT_STATUS.FIRST_ONSET) {
281         logger.warn("{}: {}: no first onset", 
282                     $params.getClosedLoopControlName(), drools.getRule().getName());
283         retract($event);
284     }
285     
286     logger.debug("{}: {}: target={}", $params.getClosedLoopControlName(), 
287                  drools.getRule().getName(), $event.target);
288     //
289     // Now start seeing if we need to process this event
290     //
291     try {
292         //
293         // Check if this is a Final Event
294         //
295         VirtualControlLoopNotification notification = $manager.isControlLoopFinal();
296     
297     
298         if (notification != null) {
299             //
300             // Its final, but are we waiting for abatement?
301             //
302             if ($manager.getNumAbatements() > 0) {
303                 logger.info("{}: {}: abatement received for {}.  Closing the control loop", 
304                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
305                             $event.requestID);
306                 notification.from = "policy";
307                 notification.policyName = drools.getRule().getName();
308                 notification.policyScope = "${policyScope}";
309                 notification.policyVersion = "${policyVersion}";
310                 //
311                 // In this case, we are done
312                 //
313                 PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
314                 //
315                 // Unlock the target
316                 //
317                 TargetLock lock = $manager.unlockCurrentOperation();
318                 if (lock != null) {
319                     logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
320                                  drools.getRule().getName(), lock);
321                     retract(lock);
322                 }
323                 //
324                 // Retract everything from memory
325                 //
326                 logger.info("{}: {}: retracting onset, manager, and timer", 
327                             $params.getClosedLoopControlName(), drools.getRule().getName());
328                 
329                 retract($manager.getOnsetEvent());
330                 retract($manager);
331                 retract($clTimer);
332                 //
333                 // TODO - what if we get subsequent Events for this RequestID?
334                 // By default, it will all start over again. May be confusing for Ruby.
335                 // Or, we could track this and then subsequently ignore the events
336                 //
337             } else {
338                 //
339                 // Check whether we need to wait for abatement
340                 //
341                 if ($manager.getProcessor().getControlLoop().getAbatement() == true && notification.notification == ControlLoopNotificationType.FINAL_SUCCESS) {
342                   logger.info("{}: {}: waiting for abatement ..", 
343                               $params.getClosedLoopControlName(), drools.getRule().getName());
344                 } else {
345                   logger.info("{}: {}: no abatement expect for {}.  Closing the control loop", 
346                               $params.getClosedLoopControlName(), drools.getRule().getName(), 
347                               $event.requestID);
348                   
349                   notification.from = "policy";
350                   notification.policyName = drools.getRule().getName();
351                   notification.policyScope = "${policyScope}";
352                   notification.policyVersion = "${policyVersion}";
353                   
354                   //
355                   // In this case, we are done
356                   //
357                   PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
358                   //
359                   // Unlock the target
360                   //
361                   TargetLock lock = $manager.unlockCurrentOperation();
362                   if (lock != null) {
363                       logger.debug("{}: {}: retracting lock=", $params.getClosedLoopControlName(), 
364                                   drools.getRule().getName(), lock);
365                       retract(lock);
366                   }
367                   //
368                   // Retract everything from memory
369                   //
370                   logger.info("{}: {}: retracting onset, manager, and timer", 
371                               $params.getClosedLoopControlName(), drools.getRule().getName());
372                   
373                   retract($manager.getOnsetEvent());
374                   retract($manager);
375                   retract($clTimer);
376                 }
377             }
378         } else {
379             //
380             // NOT final, so let's ask for the next operation
381             //
382             ControlLoopOperationManager operation = $manager.processControlLoop();
383             if (operation != null) {
384               logger.info("{}: {}: starting operation={}", 
385                           $params.getClosedLoopControlName(), drools.getRule().getName(), 
386                           operation);
387               //
388               // insert into memory
389               //
390               insert(operation);
391               //
392               // insert operation timeout object
393               //
394               OperationTimer opTimer = new OperationTimer();
395               opTimer.setClosedLoopControlName($event.closedLoopControlName);
396               opTimer.setRequestID($event.requestID.toString());
397               opTimer.setDelay(operation.getOperationTimeout().toString() + "s");
398               insert(opTimer);
399       
400               //
401               // Let's ask for a lock right away
402               //
403               LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation();
404               if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) {
405                 logger.info("{}: {}: guard lock acquired={}", 
406                             $params.getClosedLoopControlName(), drools.getRule().getName(), 
407                             result.getB());
408                 
409                 //
410                 // Insert into memory
411                 //
412                 insert(result.getB());
413               }
414             } else {
415                 //
416                 // Probably waiting for abatement
417                 //
418               logger.info("{}: {}: no operation, probably waiting for abatement", 
419                           $params.getClosedLoopControlName(), drools.getRule().getName());
420             }
421         }
422     } catch (Exception e) {
423       logger.warn("{}: {}: unexpected", 
424                   $params.getClosedLoopControlName(), 
425                   drools.getRule().getName(), e);
426
427       //
428       // TODO should we abort if we get an exception?
429       //
430     }
431         
432 end
433
434
435
436 /*
437 *
438
439 *
440 */
441 rule "${policyName}.EVENT.MANAGER.OPERATION.NOT_LOCKED.TIMEOUT"
442     timer (int: 5s 5s)
443     when
444         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
445         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
446         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
447         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
448         not ( TargetLock (requestID == $event.requestID) )
449     then
450
451     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
452     logger.info("{}: {}: event={} manager={} operation={}", 
453                 $params.getClosedLoopControlName(), drools.getRule().getName(),
454                 $event, $manager, $operation);
455     
456     //
457     // Need to ask for a Lock
458     //
459     LockResult<GuardResult, TargetLock> result = $manager.lockCurrentOperation();
460     if (result.getA().equals(GuardResult.LOCK_ACQUIRED)) {
461       logger.info("{}: {}: guard lock acquired={}", 
462                   $params.getClosedLoopControlName(), drools.getRule().getName(), 
463                   result.getB());
464       
465         //
466         // Insert into memory
467         //
468         insert(result.getB());
469     }
470     
471 end
472
473 /*
474 *
475 * Guard Permitted, let's send request to the actor.
476 *
477 */
478 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_PERMITTED"
479     when
480         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
481         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
482         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
483         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "Permit" )
484         $lock : TargetLock (requestID == $event.requestID)
485     then
486
487     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
488     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
489                 $params.getClosedLoopControlName(), drools.getRule().getName(),
490                 $event, $manager, $operation, $lock);    
491
492     Object request = $operation.getOperationRequest();
493     
494     if (request != null) {
495       logger.debug("{}: {}: starting operation ..", 
496                    $params.getClosedLoopControlName(), drools.getRule().getName());
497       //
498       // Tell interested parties we are performing this Operation
499       //
500       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
501       notification.notification = ControlLoopNotificationType.OPERATION;
502       notification.message = $operation.getOperationMessage();
503       notification.history = $operation.getHistory();
504       notification.from = "policy";
505       notification.policyName = drools.getRule().getName();
506       notification.policyScope = "${policyScope}";
507       notification.policyVersion = "${policyVersion}";
508       
509       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
510       
511       switch ($operation.policy.getActor()){
512           
513           case "APPC":
514       
515               if (request instanceof Request || request instanceof LCMRequestWrapper) {
516                   PolicyEngine.manager.deliver("APPC-CL", request);
517               }
518               break;
519           case "SO":
520               // at this point the AAI named query request should have already been made, the response recieved and used
521               // in the construction of the SO Request which is stored in operationRequest
522               
523               if(request instanceof SORequest) {
524                   // Call SO. The response will be inserted into memory once it's received 
525                   MSOActorServiceProvider.sendRequest(drools.getWorkingMemory(), request);                        
526               }
527               break;
528           case "VFC":
529               if (request instanceof VFCRequest) {
530                   // Start VFC thread
531                   VFCManager vfcManager = new VFCManager((VFCRequest) request);
532                   vfcManager.setVFCParams(
533                       PolicyEngine.manager.getEnvironmentProperty("vfc.url"),
534                       PolicyEngine.manager.getEnvironmentProperty("vfc.user"),
535                       PolicyEngine.manager.getEnvironmentProperty("vfc.password"));
536                   
537                   Thread t = new Thread(vfcManager);
538                   t.start();
539               }          
540               break;
541       }
542     } else {
543       //
544       // What happens if its null?
545       //
546       logger.warn("{}: {}: unexpected null operation request", 
547                   $params.getClosedLoopControlName(), 
548                   drools.getRule().getName());
549     }
550 end
551
552
553 /*
554 *
555 * We were able to acquire a lock so now let's ask Xacml Guard whether 
556 * we are allowed to proceed with the request to the actor.
557 *
558 */
559 rule "${policyName}.EVENT.MANAGER.OPERATION.LOCKED.GUARD_NOT_YET_QUERIED"
560     when
561         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
562         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
563         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
564         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID, getGuardApprovalStatus() == "NONE" )
565         $lock : TargetLock (requestID == $event.requestID)
566     then
567
568     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
569     logger.info("{}: {}: event={} manager={} operation={} lock={}", 
570                 $params.getClosedLoopControlName(), drools.getRule().getName(),
571                 $event, $manager, $operation, $lock);
572
573     //
574     // We are starting the operation but the actor won't be contacted until Guard is queried and permitted.
575     //
576     $operation.startOperation($event);
577     
578     //
579     // Sending notification that we are about to query Guard ("DB write - start operation")
580     //
581     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
582     notification.notification = ControlLoopNotificationType.OPERATION;
583     notification.message = $operation.getOperationMessage();
584     notification.history = $operation.getHistory();
585     notification.from = "policy";
586     notification.policyName = drools.getRule().getName();
587     notification.policyScope = "${policyScope}";
588     notification.policyVersion = "${policyVersion}";
589     
590     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
591         
592     //
593     // Now send Guard Request to XACML Guard. In order to bypass the call to Guard, 
594     // just change guardEnabled to false.
595     // 
596     // In order to use REST XACML, provide a URL instead of "" as a second argument 
597     // to the CallGuardTask() and set the first argument to null 
598     // (instead of XacmlPdpEngine).
599     //
600     boolean guardEnabled = false;
601     
602     if(guardEnabled){
603     
604         Thread t = new Thread(new org.onap.policy.guard.CallGuardTask(
605                                                         null, 
606                                                         PolicyEngine.manager.getEnvironmentProperty("guard.url"), 
607                                                         drools.getWorkingMemory(),
608                                                         $event.closedLoopControlName,
609                                                         $operation.policy.getActor().toString(),
610                                                         $operation.policy.getRecipe(),
611                                                         $manager.getTargetInstance($operation.policy),
612                                                         //$event.target,
613                                                         $event.requestID.toString()
614                                                         ));
615         t.start();
616     }
617     else{
618         insert(new PolicyGuardResponse("Permit", $event.requestID, $operation.policy.getRecipe()));
619     }
620
621 end
622
623 //
624 // This rule will be triggered when a thread talking to the XACML Guard inserts a 
625 // guardResponse object into the working memory
626 //
627 rule "${policyName}.GUARD.RESPONSE"
628     when
629         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
630         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
631         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID ) 
632         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
633         $lock : TargetLock (requestID == $event.requestID)
634         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
635         $guardResponse : PolicyGuardResponse(requestID == $event.requestID, $operation.policy.recipe == operation)
636     then
637
638     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
639     logger.info("{}: {}: event={} manager={} operation={} lock={} opTimer={} guardResponse={}", 
640                  $params.getClosedLoopControlName(), drools.getRule().getName(),
641                  $event, $manager, $operation, $lock, $opTimer, $guardResponse);
642         
643         
644     //we will permit the operation if there was no Guard for it
645     if($guardResponse.result == "Indeterminate"){
646         $guardResponse.result = "Permit";
647     }
648     
649     //
650     // This notification has Guard result in "message". ("DB write - end operation in case of Guard Deny")
651     //
652     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
653     notification.notification = ControlLoopNotificationType.OPERATION;
654     notification.message = $operation.getOperationMessage($guardResponse.result);
655     notification.history = $operation.getHistory();
656     notification.from = "policy";
657     notification.policyName = drools.getRule().getName();
658     notification.policyScope = "${policyScope}";
659     notification.policyVersion = "${policyVersion}";
660     
661     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
662     
663     if($guardResponse.result == "Permit"){
664     
665         modify($operation){setGuardApprovalStatus($guardResponse.result)};
666     }
667     else {
668         //This is the Deny case
669         $operation.setOperationHasGuardDeny();
670         retract($opTimer);
671         retract($operation);
672         modify($manager) {finishOperation($operation)};
673     }
674     
675     retract($guardResponse);
676             
677 end
678
679 /*
680 *
681 * This rule responds to APPC Response Events
682 *
683 * I would have like to be consistent and write the Response like this:
684 * $response : Response( CommonHeader.RequestID == $onset.requestID )
685 *
686 * However, no compile error was given. But a runtime error was given. I think
687 * because drools is confused between the classname CommonHeader vs the property CommonHeader.
688 *
689 */
690 rule "${policyName}.APPC.RESPONSE"
691     when
692         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
693         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
694         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
695         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
696         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
697         $lock : TargetLock (requestID == $event.requestID)
698         $response : Response( getCommonHeader().RequestID == $event.requestID )
699     then
700
701     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
702     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
703     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
704                  $params.getClosedLoopControlName(), drools.getRule().getName(),
705                  $event, $manager, $operation, $lock, $opTimer, $response);
706     //
707     // Get the result of the operation
708     //
709     PolicyResult policyResult = $operation.onResponse($response);
710     if (policyResult != null) {
711         logger.debug("{}: {}: operation finished - result={}", 
712                     $params.getClosedLoopControlName(), drools.getRule().getName(),
713                     policyResult);
714         //
715         // This Operation has completed, construct a notification showing our results. (DB write - end operation)
716         //
717         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
718         notification.from = "policy";
719         notification.policyName = drools.getRule().getName();
720         notification.policyScope = "${policyScope}";
721         notification.policyVersion = "${policyVersion}";
722         notification.message = $operation.getOperationHistory();
723         notification.history = $operation.getHistory();
724         if (policyResult.equals(PolicyResult.SUCCESS)) {
725             notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
726             //
727             // Let interested parties know
728             //
729             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
730         } else {
731             notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
732             //
733             // Let interested parties know
734             //
735             PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
736         }
737         //
738         // Ensure the operation is complete
739         //
740         if ($operation.isOperationComplete() == true) {
741             //
742             // It is complete, remove it from memory
743             //
744             retract($operation);
745             //
746             // We must also retract the timer object
747             // NOTE: We could write a Rule to do this
748             //
749             retract($opTimer);
750             //
751             // Complete the operation
752             //
753             modify($manager) {finishOperation($operation)};
754         } else {
755             //
756             // Just doing this will kick off the LOCKED rule again
757             //
758             modify($operation) {};
759         }
760     } else {
761         //
762         // Its not finished yet (i.e. expecting more Response objects)
763         //
764         // Or possibly it is a leftover response that we timed the request out previously
765         //
766     }
767     //
768     // We are going to retract these objects from memory
769     //
770     retract($response);
771 end
772
773 /*
774 *
775 * The problem with Responses is that they don't have a controlLoopControlName
776 * field in them, so the only way to attach them is via RequestID. If we have multiple
777 * control loop .drl's loaded in the same container, we need to be sure the cleanup
778 * rules don't remove Responses for other control loops.
779 *
780 */
781 rule "${policyName}.APPC.RESPONSE.CLEANUP"
782     when
783         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
784         $response : Response($id : getCommonHeader().RequestID )
785         not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
786     then
787
788     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
789     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
790     logger.debug("{}: {}: orphan appc response={}", 
791                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
792         
793     //
794     // Retract it
795     //
796     retract($response);
797 end
798
799 /*
800 *
801 * This rule responds to APPC Response Events using the new LCM interface provided by appc
802 *
803 */
804 rule "${policyName}.APPC.LCM.RESPONSE"
805     when
806         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
807         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) 
808         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
809         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
810         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
811         $lock : TargetLock (requestID == $event.requestID)
812         $response : LCMResponseWrapper( getBody().getCommonHeader().getRequestId() == $event.requestID )
813     then
814
815     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
816     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
817     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} response={}", 
818                 $params.getClosedLoopControlName(), drools.getRule().getName(),
819                 $event, $manager, $operation, $lock, $operation, $opTimer, $response);
820     
821     //
822     // Get the result of the operation
823     //
824     PolicyResult policyResult = $operation.onResponse($response);
825     if (policyResult != null) {
826       logger.debug("{}: {}: operation finished - result={}", 
827                   $params.getClosedLoopControlName(), drools.getRule().getName(),
828                   policyResult);
829       
830       //
831       // This Operation has completed, construct a notification showing our results. (DB write - end operation)
832       //
833       VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
834       notification.from = "policy";
835       notification.policyName = drools.getRule().getName();
836       notification.policyScope = "${policyScope}";
837       notification.policyVersion = "${policyVersion}";
838       notification.message = $operation.getOperationHistory();
839       notification.history = $operation.getHistory();
840       if (policyResult.equals(PolicyResult.SUCCESS)) {
841           notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
842       } else {
843           notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
844       }
845       PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
846       //
847       // Ensure the operation is complete
848       //
849       if ($operation.isOperationComplete() == true) {
850           //
851           // It is complete, remove it from memory
852           //
853           retract($operation);
854           //
855           // We must also retract the timer object
856           // NOTE: We could write a Rule to do this
857           //
858           retract($opTimer);
859           //
860           // Complete the operation
861           //
862           modify($manager) {finishOperation($operation)};
863       } else {
864           //
865           // Just doing this will kick off the LOCKED rule again
866           //
867           modify($operation) {};
868       }
869     } else {
870         //
871         // Its not finished yet (i.e. expecting more Response objects)
872         //
873         // Or possibly it is a leftover response that we timed the request out previously
874         //
875     }
876     //
877     // We are going to retract these objects from memory
878     //
879     retract($response);
880 end
881
882 /*
883 *
884 * Clean Up any lingering LCM reponses
885 *
886 */
887 rule "${policyName}.APPC.LCM.RESPONSE.CLEANUP"
888     when
889         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
890         $response : LCMResponseWrapper($id : getBody().getCommonHeader().getRequestId )
891         not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
892     then
893     
894     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
895     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
896     logger.debug("{}: {}: orphan appc response={}", 
897                 $params.getClosedLoopControlName(), drools.getRule().getName(), $id);
898     //
899     // Retract it
900     //
901     retract($response);
902 end
903
904 /*
905 *
906 * This rule responds to SO Response Events
907 *
908 */
909 rule "${policyName}.SO.RESPONSE"
910     when
911         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
912         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
913         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName )
914         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
915         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() )
916         $lock : TargetLock (requestID == $event.requestID)
917         $request : SORequest( requestId == $event.requestID.toString() )
918         $response : SOResponse( request.requestId == $event.requestID.toString() )  
919     then
920         
921     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
922     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
923     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={} request={} response={}", 
924                 $params.getClosedLoopControlName(), drools.getRule().getName(),
925                 $event, $manager, $operation, $lock, $operation, $opTimer, $request, $response);
926         
927     // Get the result of the operation
928     //
929     PolicyResult policyResult = $operation.onResponse($response);
930     if (policyResult != null) {
931         logger.debug("{}: {}: operation finished - result={}", 
932                     $params.getClosedLoopControlName(), drools.getRule().getName(),
933                     policyResult);
934       
935         //
936         // This Operation has completed, construct a notification showing our results
937         //
938         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
939         notification.from = "policy";
940         notification.policyName = drools.getRule().getName();
941         notification.policyScope = "${policyScope}";
942         notification.policyVersion = "${policyVersion}";
943         notification.message = $operation.getOperationHistory();
944         notification.history = $operation.getHistory();
945         if (policyResult.equals(PolicyResult.SUCCESS)) {
946             notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
947         } else {
948             notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
949
950         }
951         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
952         //
953         // Ensure the operation is complete
954         //
955         if ($operation.isOperationComplete() == true) {
956             //
957             // It is complete, remove it from memory
958             //
959             retract($operation);
960             //
961             // We must also retract the timer object
962             // NOTE: We could write a Rule to do this
963             //
964             retract($opTimer);
965             //
966             // Complete the operation
967             //
968             modify($manager) {finishOperation($operation)};
969         } else {
970             //
971             // Just doing this will kick off the LOCKED rule again
972             //
973             modify($operation) {};
974         }
975     } else {
976         //
977         // Its not finished yet (i.e. expecting more Response objects)
978         //
979         // Or possibly it is a leftover response that we timed the request out previously
980         //
981     }
982     //
983     // We are going to retract these objects from memory
984     //
985     retract($response);
986
987 end
988
989 /*
990 *
991 * This is the timer that manages the timeout for an individual operation.
992 *
993 */
994 rule "${policyName}.EVENT.MANAGER.OPERATION.TIMEOUT"
995     timer (expr: $to )
996     when
997         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
998         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
999         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
1000         $operation : ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID )
1001         $opTimer : OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() )
1002         $lock : TargetLock (requestID == $event.requestID)
1003     then
1004     
1005     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1006     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1007     logger.debug("{}: {}: event={} manager={} operation={} lock={} opTimer={}", 
1008                 $params.getClosedLoopControlName(), drools.getRule().getName(),
1009                 $event, $manager, $operation, $lock, $operation, $opTimer);
1010     
1011     //
1012     // Tell it its timed out
1013     //
1014     $operation.setOperationHasTimedOut();
1015     //
1016     // Create a notification for it ("DB Write - end operation")
1017     //
1018     VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1019     notification.from = "policy";
1020     notification.policyName = drools.getRule().getName();
1021     notification.policyScope = "${policyScope}";
1022     notification.policyVersion = "${policyVersion}";
1023     notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
1024     notification.message = $operation.getOperationHistory();
1025     notification.history = $operation.getHistory();
1026     //
1027     // Let interested parties know
1028     //
1029     PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1030     //
1031     // Get rid of the timer
1032     //
1033     retract($opTimer);
1034     //
1035     // Ensure the operation is complete
1036     //
1037     if ($operation.isOperationComplete() == true) {
1038         //
1039         // It is complete, remove it from memory
1040         //
1041         retract($operation);
1042         //
1043         // Complete the operation
1044         //
1045         modify($manager) {finishOperation($operation)};
1046     } else {
1047         //
1048         // Just doing this will kick off the LOCKED rule again
1049         //
1050         modify($operation) {};
1051     }
1052 end
1053
1054 /*
1055 *
1056 * This is the timer that manages the overall control loop timeout.
1057 *
1058 */
1059 rule "${policyName}.EVENT.MANAGER.TIMEOUT"
1060     timer (expr: $to )
1061     when
1062         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1063         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName() )
1064         $manager : ControlLoopEventManager( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID )
1065         $clTimer : ControlLoopTimer ( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString(), $to : getDelay() )
1066         $operations : LinkedList()
1067                         from collect( ControlLoopOperationManager( onset.closedLoopControlName == $event.closedLoopControlName, onset.requestID == $event.requestID ) )
1068         $opTimers : LinkedList()
1069                         from collect( OperationTimer( closedLoopControlName == $event.closedLoopControlName, requestID == $event.requestID.toString() ) )
1070         $locks : LinkedList()
1071                         from collect( TargetLock (requestID == $event.requestID) )
1072     then
1073     
1074     Logger logger = LoggerFactory.getLogger(drools.getRule().getPackage());
1075     logger.info("{}: {}", $params.getClosedLoopControlName(), drools.getRule().getName());
1076
1077     if ($operations == null) {
1078       logger.debug("{}: {}: event={} manager={} clTimer={} operations=0", 
1079                   $params.getClosedLoopControlName(), drools.getRule().getName(),
1080                   $event, $manager, $clTimer);
1081     } else {
1082       logger.debug("{}: {}: event={} manager={} clTimer={} operations={}", 
1083                   $params.getClosedLoopControlName(), drools.getRule().getName(),
1084                   $event, $manager, $clTimer, $operations.size());
1085     }
1086     //
1087     // Tell the Event Manager it has timed out
1088     //
1089     VirtualControlLoopNotification notification = $manager.setControlLoopTimedOut();
1090     if (notification != null) {
1091         notification.from = "policy";
1092         notification.policyName = drools.getRule().getName();
1093         notification.policyScope = "${policyScope}";
1094         notification.policyVersion = "${policyVersion}";
1095         //
1096         // Let interested parties know
1097         //
1098         PolicyEngine.manager.deliver("POLICY-CL-MGT", notification);
1099     }
1100     //
1101     // Retract EVERYTHING
1102     //
1103     retract($event);
1104     retract($manager);
1105     retract($clTimer);
1106     if ($operations != null && $operations.size() > 0) {
1107         Iterator<ControlLoopOperationManager> iter = $operations.iterator();
1108         while (iter.hasNext()) {
1109             ControlLoopOperationManager manager = iter.next();
1110             retract(manager);
1111         }
1112     }
1113     if ($opTimers != null && $opTimers.size() > 0) {
1114         Iterator<OperationTimer> iter = $opTimers.iterator();
1115         while (iter.hasNext()) {
1116             OperationTimer opTimer = iter.next();
1117             retract(opTimer);
1118         }
1119     }
1120     if ($locks != null && $locks.size() > 0) {
1121         Iterator<TargetLock> iter = $locks.iterator();
1122         while (iter.hasNext()) {
1123             TargetLock lock = iter.next();
1124             //
1125             // Ensure we release the lock
1126             //
1127             PolicyGuard.unlockTarget(lock);
1128             //
1129             //
1130             //
1131             retract(lock);
1132         }
1133     }
1134 end