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