c5614e006a67cd62255ecb171dc11306d2787d5e
[policy/drools-applications.git] / archetype-closedloop-demo-rules / src / main / resources / archetype-resources / src / main / resources / ControlLoopDemo__closedLoopControlName__.drl
1 /*-
2  * ============LICENSE_START=======================================================
3  * archetype-closed-loop-demo-rules
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.openecomp.policy.controlloop;
22
23 import java.util.List;
24 import java.util.LinkedList;
25 import java.util.Map;
26 import java.util.HashMap;
27 import java.util.UUID;
28
29 import org.openecomp.policy.controlloop.VirtualControlLoopEvent;
30 import org.openecomp.policy.controlloop.ControlLoopEventStatus;
31 import org.openecomp.policy.controlloop.VirtualControlLoopNotification;
32 import org.openecomp.policy.controlloop.ControlLoopNotificationType;
33 import org.openecomp.policy.controlloop.ControlLoopOperation;
34 import org.openecomp.policy.controlloop.ControlLoopOperationWrapper;
35 import org.openecomp.policy.template.demo.ControlLoopException;
36
37 import org.openecomp.policy.aai.AAINQF199.AAINQF199CloudRegion;
38 import org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperties;
39 import org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperty;
40 import org.openecomp.policy.aai.AAINQF199.AAINQF199GenericVNF;
41 import org.openecomp.policy.aai.AAINQF199.AAINQF199InstanceFilters;
42 import org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItem;
43 import org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItems;
44 import org.openecomp.policy.aai.AAINQF199.AAINQF199Manager;
45 import org.openecomp.policy.aai.AAINQF199.AAINQF199NamedQuery;
46 import org.openecomp.policy.aai.AAINQF199.AAINQF199QueryParameters;
47 import org.openecomp.policy.aai.AAINQF199.AAINQF199Request;
48 import org.openecomp.policy.aai.AAINQF199.AAINQF199RequestWrapper;
49 import org.openecomp.policy.aai.AAINQF199.AAINQF199Response;
50 import org.openecomp.policy.aai.AAINQF199.AAINQF199ResponseWrapper;
51 import org.openecomp.policy.aai.AAINQF199.AAINQF199ServiceInstance;
52 import org.openecomp.policy.aai.AAINQF199.AAINQF199Tenant;
53 import org.openecomp.policy.aai.AAINQF199.AAINQF199VfModule;
54 import org.openecomp.policy.aai.AAINQF199.AAINQF199VServer;
55 import org.openecomp.policy.aai.util.Serialization;
56
57 import org.openecomp.policy.appc.CommonHeader;
58 import org.openecomp.policy.appc.Request;
59 import org.openecomp.policy.appc.Response;
60 import org.openecomp.policy.appc.ResponseCode;
61 import org.openecomp.policy.appc.ResponseStatus;
62 import org.openecomp.policy.appc.ResponseValue;
63
64 import org.openecomp.policy.template.demo.EventManager;
65 import org.openecomp.policy.vnf.trafficgenerator.PGRequest;
66 import org.openecomp.policy.vnf.trafficgenerator.PGStream;
67 import org.openecomp.policy.vnf.trafficgenerator.PGStreams;
68
69 import org.openecomp.policy.mso.MSOManager;
70 import org.openecomp.policy.mso.MSORequest;
71 import org.openecomp.policy.mso.MSORequestStatus;
72 import org.openecomp.policy.mso.MSORequestDetails;
73 import org.openecomp.policy.mso.MSOModelInfo;
74 import org.openecomp.policy.mso.MSOCloudConfiguration;
75 import org.openecomp.policy.mso.MSORequestInfo;
76 import org.openecomp.policy.mso.MSORequestParameters;
77 import org.openecomp.policy.mso.MSORelatedInstanceListElement;
78 import org.openecomp.policy.mso.MSORelatedInstance;
79 import org.openecomp.policy.mso.MSOResponse;
80
81 import org.openecomp.policy.drools.system.PolicyEngine;
82
83 //
84 // These parameters are required to build the runtime policy
85 //
86 declare Params
87     closedLoopControlName : String
88     actor : String
89     aaiURL : String
90     aaiUsername : String
91     aaiPassword : String
92     msoURL : String
93     msoUsername : String
94     msoPassword : String
95     aaiNamedQueryUUID : String
96     aaiPatternMatch : int 
97     notificationTopic : String
98     appcTopic : String
99 end
100
101 /*
102 *
103 * Called once and only once to insert the parameters into working memory for this Closed Loop policy.
104 * NOTE:  If this file is to be used as a template to be used with the policy BRMS GW, please comment out this line 
105 * as the BRMS_GW already generates a SETUP rule
106 *
107 */
108 rule "${policyName}.SETUP"
109         when
110         then
111                 System.out.println("rule SETUP is triggered.");
112                 Params params = new Params();
113                 params.setClosedLoopControlName("${closedLoopControlName}");
114                 params.setActor("${actor}");
115                 params.setAaiURL("${aaiURL}");
116                 params.setAaiUsername("${aaiUsername}");
117                 params.setAaiPassword("${aaiPassword}");
118                 params.setMsoURL("${msoURL}");
119                 params.setMsoUsername("${msoUsername}");
120                 params.setMsoPassword("${msoPassword}");
121                 params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}");
122                 params.setAaiPatternMatch(${aaiPatternMatch});
123                 params.setNotificationTopic("${notificationTopic}");
124                 params.setAppcTopic("${appcTopic}");
125                 //
126                 // This stays in memory as long as the rule is alive and running
127                 //
128                 insert(params);
129 end
130
131
132 /*
133 *
134 * This rule responds to DCAE Events
135 *
136 */
137 rule "${policyName}.EVENT"
138         when
139         $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
140         $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
141         not ( EventManager( closedLoopControlName == $event.closedLoopControlName ))
142         then
143                 System.out.println("rule EVENT is triggered.");
144                 try {
145                         // 
146                         // Check the requestID in the event to make sure it is not null before we create the EventManager. 
147                         // The EventManager will do extra syntax checking as well check if the closed loop is disabled/
148                         //
149                         if ($event.requestID == null) {
150                                 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
151                                 notification.notification = ControlLoopNotificationType.REJECTED;
152                                 notification.from = "policy";
153                                 notification.message = "Missing requestID from DCAE event";
154                                 notification.policyName = drools.getRule().getName();
155                                 notification.policyScope = "${policyScope}";
156                                 notification.policyVersion = "${policyVersion}";
157                                 //
158                                 // Let interested parties know
159                                 //
160                                 try {
161                                         System.out.println(Serialization.gsonPretty.toJson(notification));
162                                         PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
163                                 } catch (Exception e) {
164                                         e.printStackTrace();
165                                         System.out.println("Can't deliver notification: " + notification);
166                                 }
167                                 //
168                                 // Retract it from memory
169                                 //
170                                 retract($event);
171                                 System.out.println("Event with requestID=null has been retracted.");
172                         } else {
173                                 //
174                                 // Create an EventManager
175                                 //
176                                 EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target);
177                                 //
178                                 // Determine if EventManager can actively process the event (i.e. syntax)
179                                 //
180                                 VirtualControlLoopNotification notification = manager.activate($event);
181                                 notification.from = "policy"; 
182                                 notification.policyName = drools.getRule().getName();
183                                 notification.policyScope = "${policyScope}";
184                                 notification.policyVersion = "${policyVersion}";
185                                 //
186                                 // Are we actively pursuing this event?
187                                 //
188                                 if (notification.notification == ControlLoopNotificationType.ACTIVE) {
189                                         //
190                                         // Insert Event Manager into memory, this will now kick off processing.
191                                         //
192                                         insert(manager);
193                                         //
194                                         // Let interested parties know
195                                         //
196                                         try {
197                                                 System.out.println(Serialization.gsonPretty.toJson(notification));
198                                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
199                                         } catch (Exception e) {
200                                                 e.printStackTrace();
201                                                 System.out.println("Can't deliver notification: " + notification);
202                                         }               
203                                 } else {
204                                         //
205                                         // Let interested parties know
206                                         //
207                                         try {
208                                                 System.out.println(Serialization.gsonPretty.toJson(notification));
209                                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
210                                         } catch (Exception e) {
211                                                 e.printStackTrace();
212                                                 System.out.println("Can't deliver notification: " + notification);
213                                         }
214                                         //
215                                         // Retract it from memory
216                                         //
217                                         retract($event);
218                                 }
219                                 //
220                                 // Now that the manager is inserted into Drools working memory, we'll wait for
221                                 // another rule to fire in order to continue processing. This way we can also
222                                 // then screen for additional ONSET and ABATED events for this same RequestIDs 
223                                 // and for different RequestIDs but with the same closedLoopControlName and target.
224                                 //
225                         }
226                 //
227                 } catch (Exception e) {
228                         e.printStackTrace();
229                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
230                         notification.notification = ControlLoopNotificationType.REJECTED;
231                         notification.message = "Exception occurred " + e.getMessage();
232                         notification.policyName = drools.getRule().getName();
233                         notification.policyScope = "${policyScope}";
234                         notification.policyVersion = "${policyVersion}";
235                         //
236                         //
237                         //
238                         try {
239                                 System.out.println(Serialization.gsonPretty.toJson(notification));
240                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
241                         } catch (Exception e1) {
242                                 System.out.println("Can't deliver notification: " + notification);
243                                 e1.printStackTrace();
244                         }
245                         //
246                         // Retract the event
247                         //
248                         retract($event);
249                 }
250 end
251
252 /*
253 *
254 * This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager
255 * is created. We can start the operations for this closed loop.
256 *
257 */
258 rule "${policyName}.EVENT.MANAGER"
259         when
260                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
261                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
262                 $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null)
263         then
264                 System.out.println("rule EVENT.MANAGER is triggered.");
265                 //
266                 // Check which event this is.
267                 //
268                 EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);
269                 //
270                 // We only want the initial ONSET event in memory,
271                 // all the other events need to be retracted to support
272                 // cleanup and avoid the other rules being fired for this event.
273                 //
274                 if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) {
275                         System.out.println("Retracting "+eventStatus+" Event.");
276                         retract($event);
277                         return;
278                 }
279                 //
280                 // Now the event in memory is first onset event
281                 //
282                 try {
283                         //
284                         // Pull the known AAI field from the Event
285                         //
286                         // generic-vnf is needed for vFirewall case
287                         // vserver-name is needed for vLoadBalancer case
288                         //
289                         String genericVNF = $event.AAI.get("generic-vnf.vnf-id");
290                         String vserver = $event.AAI.get("vserver.vserver-name");
291                         //
292                         // Check if we are implementing a simple pattern match.
293                         //
294                         if ($params.getAaiPatternMatch() == 1) {
295                                 //
296                                 // Yes
297                                 //
298                                 //Basic naming characteristics:
299                                 //VF Name (9 char)+VM name (13 char total)+VFC (19 char total)
300                                 //Example: 
301                                 //VF Name (9 characters):    cscf0001v
302                                 //VM Name(13 characters): cscf0001vm001
303                                 //VFC name(19 characters): cscf0001vm001cfg001
304                                 //
305                                 // zdfw1fwl01fwl02 or zdfw1fwl01fwl01  
306                                 // replaced with
307                                 // zdfw1fwl01pgn02 or zdfw1fwl01pgn01
308                                 //
309                                 int index = genericVNF.lastIndexOf("fwl");
310                                 if (index == -1) {
311                                         System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid.");
312                                 } else {
313                                         genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length());
314                                 }
315                                 //
316                                 // Construct an APPC request
317                                 //
318                                 ControlLoopOperation operation = new ControlLoopOperation();
319                                 operation.actor = $params.getActor();
320                                 operation.operation = "ModifyConfig";
321                                 operation.target = $event.target;
322                                 //
323                                 // Create operationWrapper
324                                 //
325                                 ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);
326                                 //
327                                 // insert operationWrapper into memory
328                                 //
329                                 insert(operationWrapper);
330                                 //
331                                 Request request = new Request();
332                                 request.CommonHeader = new CommonHeader();
333                                 request.CommonHeader.RequestID = $event.requestID;
334                                 request.Action = operation.operation;
335                                 request.Payload = new HashMap<String, Object>();
336                                 //
337                                 // Fill in the payload
338                                 //
339                                 request.Payload.put("generic-vnf.vnf-id", genericVNF);
340                                 //
341                                 PGRequest pgRequest = new PGRequest();
342                                 pgRequest.pgStreams = new PGStreams();
343                                 
344                                 PGStream pgStream;
345                                 for(int i = 0; i < 5; i++){
346                                         pgStream = new PGStream();
347                                         pgStream.streamId = "fw_udp"+(i+1);
348                                         pgStream.isEnabled = "true";
349                                         pgRequest.pgStreams.pgStream.add(pgStream);
350                                 }
351                                 request.Payload.put("pg-streams", pgRequest.pgStreams);
352                                 
353                                 if (request != null) {
354                                         //
355                                         // Insert request into memory
356                                         //
357                                         insert(request);
358                                         //
359                                         // Tell interested parties we are performing this Operation
360                                         //
361                                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
362                                         notification.notification = ControlLoopNotificationType.OPERATION;
363                                         // message and history ??
364                                         notification.from = "policy";
365                                         notification.policyName = drools.getRule().getName();
366                                         notification.policyScope = "${policyScope}";
367                                         notification.policyVersion = "${policyVersion}";
368                                         try {
369                                                 System.out.println(Serialization.gsonPretty.toJson(notification));
370                                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
371                                         } catch (Exception e) {
372                                                 System.out.println("Can't deliver notification: " + notification);
373                                                 e.printStackTrace();
374                                         }
375                                         //
376                                         // Now send the operation request
377                                         //
378                                         if (request instanceof Request) {
379                                                 try {
380                                                         System.out.println("APPC request sent:");
381                                                         System.out.println(Serialization.gsonPretty.toJson(request));
382                                                         PolicyEngine.manager.deliver($params.getAppcTopic(), request);
383                                                 } catch (Exception e) {
384                                                         e.printStackTrace();
385                                                         System.out.println("Can't deliver request: " + request);
386                                                 }
387                                         }
388                                 } else {
389                                         //
390                                         // what happens if it is null
391                                         //
392                                 }
393                                 //
394                         } else {
395                                 //
396                                 // create AAI named-query request with UUID started with "F199"
397                                 //
398                                 AAINQF199Request aainqf199request = new AAINQF199Request();
399                                 AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters();
400                                 AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery();
401                                 AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters();
402                                 //
403                                 // queryParameters
404                                 //
405                                 aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); 
406                                 aainqf199queryparam.namedQuery = aainqf199namedquery;
407                                 aainqf199request.queryParameters = aainqf199queryparam;
408                                 //
409                                 // instanceFilters
410                                 //
411                                 Map aainqf199instancefiltermap = new HashMap();
412                                 Map aainqf199instancefiltermapitem = new HashMap();
413                                 aainqf199instancefiltermapitem.put("vserver-name", vserver); 
414                                 aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem);
415                                 aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap);
416                                 aainqf199request.instanceFilters = aainqf199instancefilter;
417                                 //
418                                 // print aainqf199request for debug
419                                 //
420                                 System.out.println("AAI Request sent:");
421                                 System.out.println(Serialization.gsonPretty.toJson(aainqf199request));
422                                 //
423                                 // Create AAINQF199RequestWrapper
424                                 //
425                                 AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request);
426                                 //
427                                 // insert aainqf199request into memory
428                                 //
429                                 insert(aainqf199RequestWrapper);
430                         }
431                         //
432                 } catch (Exception e) {
433                  e.printStackTrace();
434                 }
435 end
436
437 /*
438 *
439 * This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager
440 * is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response.
441 *
442 */
443 rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST"
444         when
445                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
446                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
447                 $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
448                 $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)
449         then
450                 System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered.");
451                 //
452                 // send the request
453                 //
454                 AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(),
455                                                                                                            $aainqf199RequestWrapper.aainqf199request, $event.requestID);
456                 //
457                 // Check AAI response
458                 //
459                 if (aainqf199response == null) {
460                         System.err.println("Failed to get AAI response");
461                         //
462                         // Fail and retract everything
463                         //
464                         retract($event);
465                         retract($manager);
466                         retract($aainqf199RequestWrapper);
467                 } else {
468                         //
469                         // Create AAINQF199ResponseWrapper
470                         //
471                         AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response);
472                         //
473                         // insert aainqf199ResponseWrapper to memeory
474                         //
475                         insert(aainqf199ResponseWrapper);
476                 }
477 end
478
479 /*
480 *
481 * This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now.
482 *
483 */
484 rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE"
485         when 
486                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
487                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
488                 $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
489                 $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)
490                 $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID)
491         then
492                 System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered.");
493                 //
494                 // Extract related fields out of AAINQF199RESPONSE
495                 //
496                 String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, 
497                        vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId,
498                        serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId,
499                        vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, 
500                        vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId;
501                 try {
502                         //
503                         // vnfItem
504                         //
505                         vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID;
506                         vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType;
507                         vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1);
508                         vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId;
509                         vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion;
510                         vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;
511                         vnfItemModelVersion =           $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue;
512                         vnfItemModelNameVersionId =     $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;
513                         //
514                         // serviceItem
515                         //
516                         serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID;
517                         serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId;
518                         serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;
519                         serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue;
520                         serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion;
521                         serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;
522                         //
523                         // Find the index for base vf module and non-base vf module
524                         //
525                         int baseIndex = -1;
526                         int nonBaseIndex = -1;
527                         List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems;
528                         for (AAINQF199InventoryResponseItem m : inventoryItems) {
529                                 if (m.vfModule != null && m.vfModule.isBaseVfModule == true) {
530                                         baseIndex = inventoryItems.indexOf(m);
531                                 } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) {
532                                         nonBaseIndex = inventoryItems.indexOf(m);
533                                 }
534                                 //
535                                 if (baseIndex != -1 && nonBaseIndex != -1) {
536                                         break;
537                                 }
538                         }
539                         //
540                         // Report the error if either base vf module or non-base vf module is not found
541                         //
542                         if (baseIndex == -1 || nonBaseIndex == -1) {
543                                 System.err.println("Either base or non-base vf module is not found from AAI response.");
544                                 retract($aainqf199RequestWrapper);
545                                 retract($aainqf199ResponseWrapper);
546                                 retract($manager);
547                                 retract($event);
548                                 return;
549                         }
550                         //
551                         // This comes from the base module
552                         //
553                         vfModuleItemVfModuleName =                      $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName;
554                         vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS");
555                         //
556                         // vfModuleItem - NOT the base module
557                         //
558                         vfModuleItemPersonaModelId =            $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId;
559                         vfModuleItemPersonaModelVersion =       $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion;
560                         vfModuleItemModelName =                         $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue;
561                         vfModuleItemModelNameVersionId =        $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue;
562                         //
563                         // tenantItem
564                         //
565                         tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId;
566                         //
567                         // cloudRegionItem
568                         //
569                         cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId;
570                         //
571                 } catch (Exception e) {
572                         e.printStackTrace();
573                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
574                         notification.notification = ControlLoopNotificationType.REJECTED;
575                         notification.message = "Exception occurred " + e.getMessage();
576                         notification.policyName = drools.getRule().getName();
577                         notification.policyScope = "${policyScope}";
578                         notification.policyVersion = "${policyVersion}";
579                         //
580                         try {
581                                 System.out.println(Serialization.gsonPretty.toJson(notification));
582                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
583                         } catch (Exception e1) {
584                                 System.out.println("Can't deliver notification: " + notification);
585                                 e1.printStackTrace();
586                         }
587                         //
588                         notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
589                         notification.message = "Invalid named-query response from AAI";
590             //
591             try {
592                 System.out.println(Serialization.gsonPretty.toJson(notification));
593                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
594             } catch (Exception e1) {
595                 System.out.println("Can't deliver notification: " + notification);
596                 e1.printStackTrace();
597             }
598                         //
599                         // Retract everything
600                         //
601                         retract($aainqf199RequestWrapper);
602                         retract($aainqf199ResponseWrapper);
603                         retract($manager);
604                         retract($event);
605                         return;
606                 }       
607                 //
608                 // Extracted fields should not be null
609                 //
610                 if ((vnfItemVnfId == null) || (vnfItemVnfType == null) ||
611                     (vnfItemPersonaModelId == null) || (vnfItemModelName == null) ||
612                     (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) ||
613                     (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) ||
614                     (serviceItemModelType == null) || (serviceItemModelVersion == null) ||
615                     (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) ||
616                     (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) ||
617                     (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) ||
618                     (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) {
619                         //
620                         System.err.println("some fields are missing from AAI response.");
621                         //
622                         // Fail and retract everything
623                         //
624                         retract($aainqf199RequestWrapper);
625                         retract($aainqf199ResponseWrapper);
626                         retract($manager);
627                         retract($event);
628                         return;
629                 }
630                 //
631                 // We don't need them any more
632                 //
633                 retract($aainqf199ResponseWrapper);
634                 retract($aainqf199RequestWrapper);  
635                 //
636                 // check the actor of this closed loop
637                 //
638                 switch ($params.getActor()) {
639                         case "APPC":
640                         {
641                                 //
642                                 // Construct an APPC request
643                                 //
644                                 ControlLoopOperation operation = new ControlLoopOperation();
645                                 operation.actor = $params.getActor();
646                                 operation.operation = "ModifyConfig";
647                                 operation.target = $event.target;
648                                 //
649                                 // Create operationWrapper
650                                 //
651                                 ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);
652                                 //
653                                 // insert operationWrapper into memory
654                                 //
655                                 insert(operationWrapper);
656                                 //
657                                 Request request = new Request();
658                                 request.CommonHeader = new CommonHeader();
659                                 request.CommonHeader.RequestID = $event.requestID;
660                                 request.Action = operation.operation;
661                                 request.Payload = new HashMap<String, Object>();
662                                 //
663                                 // Fill in the payload
664                                 // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case
665                                 //
666                                 String genericVNF = "zdfw1fwl01pgn02";
667                                 request.Payload.put("generic-vnf.vnf-id", genericVNF);
668                                 //
669                                 PGRequest pgRequest = new PGRequest();
670                                 pgRequest.pgStreams = new PGStreams();
671                                 
672                                 PGStream pgStream;
673                                 for(int i = 0; i < 5; i++){
674                                         pgStream = new PGStream();
675                                         pgStream.streamId = "fw_udp"+(i+1);
676                                         pgStream.isEnabled = "true";
677                                         pgRequest.pgStreams.pgStream.add(pgStream);
678                                 }
679                                 request.Payload.put("pg-streams", pgRequest.pgStreams);
680                                 
681                                 if (request != null) {
682                                         //
683                                         // Insert request into memory
684                                         //
685                                         insert(request);
686                                         //
687                                         // Tell interested parties we are performing this Operation
688                                         //
689                                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
690                                         notification.notification = ControlLoopNotificationType.OPERATION;
691                                         // message and history ??
692                                         notification.from = "policy";
693                                         notification.policyName = drools.getRule().getName();
694                                         notification.policyScope = "${policyScope}";
695                                         notification.policyVersion = "${policyVersion}";
696                                         try {
697                                                 System.out.println(Serialization.gsonPretty.toJson(notification));
698                                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
699                                         } catch (Exception e) {
700                                                 System.out.println("Can't deliver notification: " + notification);
701                                                 e.printStackTrace();
702                                         }
703                                         //
704                                         // Now send the operation request
705                                         //
706                                         if (request instanceof Request) {
707                                                 try {
708                                                         System.out.println("APPC request sent:");
709                                                         System.out.println(Serialization.gsonPretty.toJson(request));
710                                                         PolicyEngine.manager.deliver($params.getAppcTopic(), request);
711                                                 } catch (Exception e) {
712                                                         e.printStackTrace();
713                                                         System.out.println("Can't deliver request: " + request);
714                                                 }
715                                         }
716                                 } else {
717                                         //
718                                         // what happens if it is null
719                                         //
720                                 }
721                         }
722                         break;
723                         case "MSO":
724                         {
725                                 //
726                                 // Construct an operation
727                                 //
728                                 ControlLoopOperation operation = new ControlLoopOperation();
729                                 operation.actor = $params.getActor();
730                                 operation.operation = "createModuleInstance";
731                                 operation.target = $event.target;
732                                 //
733                                 // Create operationWrapper
734                                 //
735                                 ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);
736                                 //
737                                 // Construct an MSO request
738                                 //
739                                 MSORequest request = new MSORequest();
740                                 request.requestDetails = new MSORequestDetails();
741                                 request.requestDetails.modelInfo = new MSOModelInfo();
742                                 request.requestDetails.cloudConfiguration = new MSOCloudConfiguration();
743                                 request.requestDetails.requestInfo = new MSORequestInfo();
744                                 request.requestDetails.requestParameters = new MSORequestParameters();
745                                 request.requestDetails.requestParameters.userParams = null;
746                                 //
747                                 // cloudConfiguration
748                                 //
749                                 request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId;
750                                 request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId;
751                                 //
752                                 // modelInfo
753                                 //
754                                 request.requestDetails.modelInfo.modelType = "vfModule";
755                                 request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId;
756                                 request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId;
757                                 request.requestDetails.modelInfo.modelName = vfModuleItemModelName;
758                                 request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion;
759                                 //
760                                 // requestInfo
761                                 //
762                                 request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName;
763                                 request.requestDetails.requestInfo.source = "POLICY";
764                                 request.requestDetails.requestInfo.suppressRollback = false;
765                                 //
766                                 // relatedInstanceList
767                                 //
768                                 MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement();
769                                 MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement();
770                                 relatedInstanceListElement1.relatedInstance = new MSORelatedInstance();
771                                 relatedInstanceListElement2.relatedInstance = new MSORelatedInstance();
772                                 //
773                                 relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId;
774                                 relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo();
775                                 relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service";
776                                 relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId;
777                                 relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId;
778                                 relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName;
779                                 relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion;
780                                 //
781                                 relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId;
782                                 relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo();
783                                 relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf";
784                                 relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId;
785                                 relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId;
786                                 relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName;
787                                 relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion;
788                                 relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType;
789                                 //      
790                                 request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1);
791                                 request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2);
792                                 //
793                                 // print MSO request for debug
794                                 //
795                                 System.out.println("MSO request sent:");
796                                 System.out.println(Serialization.gsonPretty.toJson(request));
797                                 //
798                                 //
799                                 //
800                                 if (request != null) {
801                                         //
802                                         // Tell interested parties we are performing this Operation
803                                         //
804                                         VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
805                                         notification.notification = ControlLoopNotificationType.OPERATION;
806                                         notification.from = "policy";
807                                         notification.policyName = drools.getRule().getName();
808                                         notification.policyScope = "${policyScope}";
809                                         notification.policyVersion = "${policyVersion}";
810                                         try {
811                                                 System.out.println(Serialization.gsonPretty.toJson(notification));
812                                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
813                                         } catch (Exception e) {
814                                                 System.out.println("Can't deliver notification: " + notification);
815                                                 e.printStackTrace();
816                                         }
817                                         //
818                                         // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL
819                                         //
820                                         String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules";
821                                         //
822                                         // Call MSO
823                                         //
824                                         MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request);
825                                         //
826                                         if (response != null) {
827                                                 //
828                                                 // Assign requestId
829                                                 //
830                                                 request.requestId = $event.requestID.toString();                                                
831                                                 response.request.requestId = $event.requestID.toString();
832                                                 //
833                                                 // Insert facts
834                                                 //
835                                                 insert(operationWrapper);
836                                                 insert(request);
837                                                 insert(response);
838                                         } else {
839                                                 //
840                                                 // MSO request not even accepted
841                                                 //
842                                                 notification.message = operationWrapper.operation.toMessage();
843                                                 operationWrapper.operation.message = operationWrapper.operation.toMessage();
844                                                 operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
845                                                 $manager.setControlLoopResult("FAILURE_EXCEPTION");
846                                                 notification.history.add(operationWrapper.operation);
847                                                 notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
848                                                 //
849                                                 // Let interested parties know
850                                                 //
851                                                 try {
852                                                         System.out.println(Serialization.gsonPretty.toJson(notification));
853                                                         PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
854                                                 } catch (Exception e) {
855                                                         System.out.println("Can't deliver notification: " + notification);
856                                                         e.printStackTrace();
857                                                 }
858                             notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
859                         try {
860                                 System.out.println(Serialization.gsonPretty.toJson(notification));
861                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
862                         } catch (Exception e) {
863                                 System.out.println("Can't deliver notification: " + notification);
864                                 e.printStackTrace();
865                         }
866                                                 //
867                                                 // Retract everything
868                                                 //
869                                                 retract($event);
870                                                 retract($manager);
871                                         }
872                                 } else {
873                                         System.err.println("constructed MSO request is invalid.");
874                                 }
875                         }
876                         break; 
877                 } 
878 end
879                 
880 /*
881 *
882 * This rule responds to APPC Response Events
883 *
884 */
885 rule "${policyName}.APPC.RESPONSE"
886         when
887                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
888                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
889                 $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
890                 $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )
891                 $request : Request( getCommonHeader().RequestID == $event.requestID )
892                 $response : Response( getCommonHeader().RequestID == $event.requestID ) 
893         then
894                 System.out.println("rule APPC.RESPONSE is triggered.");
895                 if ($response.Status == null) {
896                         $operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
897                         $manager.setControlLoopResult("FAILURE_EXCEPTION");
898                 } 
899                 //
900                 // Get the Response Code
901                 //
902                 ResponseCode code = ResponseCode.toResponseCode($response.Status.Code);
903                 if (code == null) {
904                         $operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
905                         $manager.setControlLoopResult("FAILURE_EXCEPTION");
906                 }
907                 //
908                 // Construct notification
909                 //
910                 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
911                 notification.from = "policy";
912                 notification.policyName = drools.getRule().getName();
913                 notification.policyScope = "${policyScope}";
914                 notification.policyVersion = "${policyVersion}";
915                 notification.message = $operationWrapper.operation.toMessage();
916                 $operationWrapper.operation.message = $operationWrapper.operation.toMessage();
917                 //
918                 // Ok, let's figure out what APP-C's response is
919                 //
920                 switch (code) {
921                         case ACCEPT:
922                                 $operationWrapper.operation.outcome = "PROCESSING";
923                                 break;
924                         case ERROR:
925                         case REJECT:
926                                 $operationWrapper.operation.outcome = "FAILURE_EXCEPTION";
927                                 $manager.setControlLoopResult("FAILURE_EXCEPTION");
928                                 break;
929                         case SUCCESS:
930                                 $operationWrapper.operation.outcome = "SUCCESS";
931                                 $manager.setControlLoopResult("SUCCESS");
932                                 break;
933                         case FAILURE:
934                                 $operationWrapper.operation.outcome = "FAILURE";
935                                 $manager.setControlLoopResult("FAILURE");
936                                 break;
937                 }
938                 if ($operationWrapper.operation.outcome.equals("SUCCESS")) {
939                         notification.history.add($operationWrapper.operation);
940                         notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
941                         //
942                         // Let interested parties know
943                         //
944                         try {
945                                 System.out.println(Serialization.gsonPretty.toJson(notification));
946                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
947                         } catch (Exception e) {
948                                 System.out.println("Can't deliver notification: " + notification);
949                                 e.printStackTrace();
950                         }
951             notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;
952             try {
953                 System.out.println(Serialization.gsonPretty.toJson(notification));
954                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
955             } catch (Exception e) {
956                 System.out.println("Can't deliver notification: " + notification);
957                 e.printStackTrace();
958             }
959
960                         //
961                         // We are going to retract these objects from memory
962                         //
963                         System.out.println("Retracting everything");
964                         retract($operationWrapper);
965                         retract($request);
966                         retract($response);
967                         retract($event);
968                         retract($manager);
969                 } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) {
970                         retract($response);
971                 } else {
972                         notification.history.add($operationWrapper.operation);
973                         notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
974                         //
975                         // Let interested parties know
976                         //
977                         try {
978                                 System.out.println(Serialization.gsonPretty.toJson(notification));
979                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
980                         } catch (Exception e) {
981                                 System.out.println("Can't deliver notification: " + notification);
982                                 e.printStackTrace();
983                         }
984             notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
985             //
986             // Let interested parties know
987             //
988             try {
989                 System.out.println(Serialization.gsonPretty.toJson(notification));
990                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
991             } catch (Exception e) {
992                 System.out.println("Can't deliver notification: " + notification);
993                 e.printStackTrace();
994             }
995                         //
996                         // We are going to retract these objects from memory
997                         //
998                         System.out.println("Retracting everything");
999                         retract($operationWrapper);
1000                         retract($request);
1001                         retract($response);
1002                         retract($event);
1003                         retract($manager);
1004                 }
1005                 
1006 end             
1007
1008 /*
1009 *
1010 * This rule is used to clean up APPC response
1011 *
1012 */              
1013 rule "${policyName}.APPC.RESPONSE.CLEANUP"
1014         when
1015                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1016         $response : Response($id : getCommonHeader().RequestID )
1017                 not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) 
1018         then
1019                 System.out.println("rule APPC.RESPONSE.CLEANUP is triggered.");
1020                 retract($response);
1021 end
1022
1023 /*
1024 *
1025 * This rule responds to MSO Response Events
1026 *
1027 */
1028 rule "${policyName}.MSO.RESPONSE"
1029         when
1030                 $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" )
1031                 $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1032                 $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )
1033                 $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )
1034                 $request : MSORequest( requestId == $event.requestID.toString() )
1035                 $response : MSOResponse( request.requestId == $event.requestID.toString() )     
1036         then
1037                 System.out.println("rule MSO.RESPONSE is triggered.");
1038                 //
1039                 // Construct notification
1040                 //
1041                 VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);
1042                 notification.from = "policy";
1043                 notification.policyName = drools.getRule().getName();
1044                 notification.policyScope = "${policyScope}";
1045                 notification.policyVersion = "${policyVersion}";
1046                 notification.message = $operationWrapper.operation.toMessage();
1047                 $operationWrapper.operation.message = $operationWrapper.operation.toMessage();
1048                 //
1049                 // The operation can either be succeeded or failed
1050                 // 
1051                 if($response.request.requestStatus.requestState.equals("COMPLETE")) {
1052                         $operationWrapper.operation.outcome = "SUCCESS";
1053                         $manager.setControlLoopResult("SUCCESS");
1054                         notification.history.add($operationWrapper.operation);
1055                         notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;
1056                         //
1057                         // Let interested parties know
1058                         //
1059                         try {
1060                                 System.out.println(Serialization.gsonPretty.toJson(notification));
1061                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
1062                         } catch (Exception e) {
1063                                 System.out.println("Can't deliver notification: " + notification);
1064                                 e.printStackTrace();
1065                         }
1066                         notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;
1067             //
1068             // Let interested parties know
1069             //
1070             try {
1071                 System.out.println(Serialization.gsonPretty.toJson(notification));
1072                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
1073             } catch (Exception e) {
1074                 System.out.println("Can't deliver notification: " + notification);
1075                 e.printStackTrace();
1076             }
1077             //
1078                         // We are going to retract these objects from memory
1079                         //
1080                         System.out.println("Retracting everything");
1081                         retract($operationWrapper);
1082                         retract($request);
1083                         retract($response);
1084                         retract($event);
1085                         retract($manager);
1086                 } else {
1087                         $operationWrapper.operation.outcome = "FAILURE";
1088                         $manager.setControlLoopResult("FAILURE");
1089                         notification.history.add($operationWrapper.operation);
1090                         notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;
1091                         //
1092                         // Let interested parties know
1093                         //
1094                         try {
1095                                 System.out.println(Serialization.gsonPretty.toJson(notification));
1096                                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
1097                         } catch (Exception e) {
1098                                 System.out.println("Can't deliver notification: " + notification);
1099                                 e.printStackTrace();
1100                         }
1101                         notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
1102             //
1103             // Let interested parties know
1104             //
1105             try {
1106                 System.out.println(Serialization.gsonPretty.toJson(notification));
1107                 PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);
1108             } catch (Exception e) {
1109                 System.out.println("Can't deliver notification: " + notification);
1110                 e.printStackTrace();
1111             }
1112             //
1113                         // We are going to retract these objects from memory
1114                         //
1115                         System.out.println("Retracting everything");
1116                         retract($operationWrapper);
1117                         retract($request);
1118                         retract($response);
1119                         retract($event);
1120                         retract($manager);
1121                 }               
1122 end
1123
1124 /*
1125  * Sample Queries for illustration with and without arguments
1126  * The results of the query can be introspected (and retracted if desired)
1127  * through REST API.
1128  */
1129 query "${policyName}.QUERY.EVENT.ONSET"
1130         event : VirtualControlLoopEvent( closedLoopEventStatus == ControlLoopEventStatus.ONSET )
1131 end
1132
1133 query "${policyName}.QUERY.MANAGER.RNA" (String aRequestId, Integer numOnsetsLowerBound, Boolean aActivated)
1134         manager : EventManager( closedLoopControlName == "${closedLoopControlName}", 
1135                                 requestID.toString() == aRequestId, 
1136                                 numOnsets > numOnsetsLowerBound,
1137                                 activated == aActivated )
1138 end