bfb8c13fe39932d5f653e708a7dc7155c9f07afc
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * controlloop event manager
4  * ================================================================================
5  * Copyright (C) 2017-2019 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.eventmanager;
22
23 import java.io.Serializable;
24 import java.io.UnsupportedEncodingException;
25 import java.net.URLDecoder;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.NoSuchElementException;
33 import java.util.UUID;
34
35 import org.onap.policy.aai.AaiGetVnfResponse;
36 import org.onap.policy.aai.AaiGetVserverResponse;
37 import org.onap.policy.aai.AaiManager;
38 import org.onap.policy.aai.AaiNqInstanceFilters;
39 import org.onap.policy.aai.AaiNqNamedQuery;
40 import org.onap.policy.aai.AaiNqQueryParameters;
41 import org.onap.policy.aai.AaiNqRequest;
42 import org.onap.policy.aai.AaiNqResponse;
43 import org.onap.policy.aai.AaiNqResponseWrapper;
44 import org.onap.policy.aai.AaiNqVServer;
45 import org.onap.policy.aai.util.AaiException;
46 import org.onap.policy.controlloop.ControlLoopEventStatus;
47 import org.onap.policy.controlloop.ControlLoopException;
48 import org.onap.policy.controlloop.ControlLoopNotificationType;
49 import org.onap.policy.controlloop.ControlLoopOperation;
50 import org.onap.policy.controlloop.VirtualControlLoopEvent;
51 import org.onap.policy.controlloop.VirtualControlLoopNotification;
52 import org.onap.policy.controlloop.policy.FinalResult;
53 import org.onap.policy.controlloop.policy.Policy;
54 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.onap.policy.guard.GuardResult;
57 import org.onap.policy.guard.LockCallback;
58 import org.onap.policy.guard.PolicyGuard;
59 import org.onap.policy.guard.PolicyGuard.LockResult;
60 import org.onap.policy.guard.TargetLock;
61 import org.onap.policy.rest.RestManager;
62 import org.onap.policy.so.util.Serialization;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 public class ControlLoopEventManager implements LockCallback, Serializable {
67     public static final String PROV_STATUS_ACTIVE = "ACTIVE";
68     private static final String VM_NAME = "VM_NAME";
69     private static final String VNF_NAME = "VNF_NAME";
70     public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
71     public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
72     public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
73     public static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled";
74     public static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled";
75     public static final String GENERIC_VNF_PROV_STATUS = "generic-vnf.prov-status";
76     public static final String VSERVER_PROV_STATUS = "vserver.prov-status";
77
78     private static final String AAI_URL = "aai.url";
79     private static final String AAI_USERNAME_PROPERTY = "aai.username";
80     private static final String AAI_PASS_PROPERTY = "aai.password";
81
82     private static final String QUERY_AAI_ERROR_MSG = "Exception from queryAai: ";
83
84     /**
85      * Additional time, in seconds, to add to a "lock" request. This ensures that the lock
86      * won't expire right before an operation completes.
87      */
88     private static final int ADDITIONAL_LOCK_SEC = 60;
89
90     private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class);
91
92     private static final long serialVersionUID = -1216568161322872641L;
93     public final String closedLoopControlName;
94     private final UUID requestId;
95
96     private String controlLoopResult;
97     private ControlLoopProcessor processor = null;
98     private VirtualControlLoopEvent onset;
99     private Integer numOnsets = 0;
100     private Integer numAbatements = 0;
101     private VirtualControlLoopEvent abatement;
102     private FinalResult controlLoopTimedOut = null;
103
104     private boolean isActivated = false;
105     private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
106     private ControlLoopOperationManager currentOperation = null;
107     private ControlLoopOperationManager lastOperationManager = null;
108     private transient TargetLock targetLock = null;
109     private AaiGetVnfResponse vnfResponse = null;
110     private AaiGetVserverResponse vserverResponse = null;
111     private boolean useTargetLock = true;
112
113     /**
114      * Wrapper for AAI vserver named-query response. This is initialized in a lazy
115      * fashion.
116      */
117     private AaiNqResponseWrapper nqVserverResponse = null;
118
119     private static Collection<String> requiredAAIKeys = new ArrayList<>();
120
121     static {
122         requiredAAIKeys.add("AICVServerSelfLink");
123         requiredAAIKeys.add("AICIdentity");
124         requiredAAIKeys.add("is_closed_loop_disabled");
125         requiredAAIKeys.add(VM_NAME);
126     }
127
128     public ControlLoopEventManager(String closedLoopControlName, UUID requestId) {
129         this.closedLoopControlName = closedLoopControlName;
130         this.requestId = requestId;
131     }
132
133     public String getClosedLoopControlName() {
134         return closedLoopControlName;
135     }
136
137     public String getControlLoopResult() {
138         return controlLoopResult;
139     }
140
141     public void setControlLoopResult(String controlLoopResult) {
142         this.controlLoopResult = controlLoopResult;
143     }
144
145     public Integer getNumOnsets() {
146         return numOnsets;
147     }
148
149     public void setNumOnsets(Integer numOnsets) {
150         this.numOnsets = numOnsets;
151     }
152
153     public Integer getNumAbatements() {
154         return numAbatements;
155     }
156
157     public void setNumAbatements(Integer numAbatements) {
158         this.numAbatements = numAbatements;
159     }
160
161     public boolean isActivated() {
162         return isActivated;
163     }
164
165     public void setActivated(boolean isActivated) {
166         this.isActivated = isActivated;
167     }
168
169     public boolean useTargetLock() {
170         return useTargetLock();
171     }
172
173     public void setUseTargetLock(boolean useTargetLock) {
174         this.useTargetLock = useTargetLock;
175     }
176
177     public VirtualControlLoopEvent getOnsetEvent() {
178         return this.onset;
179     }
180
181     public VirtualControlLoopEvent getAbatementEvent() {
182         return this.abatement;
183     }
184
185     public ControlLoopProcessor getProcessor() {
186         return this.processor;
187     }
188
189     public UUID getRequestId() {
190         return requestId;
191     }
192
193     /**
194      * Activate a control loop event.
195      *
196      * @param event the event
197      * @return the VirtualControlLoopNotification
198      */
199     public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) {
200         VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
201         try {
202             //
203             // This method should ONLY be called ONCE
204             //
205             if (this.isActivated) {
206                 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
207             }
208             //
209             // Syntax check the event
210             //
211             checkEventSyntax(event);
212
213             //
214             // At this point we are good to go with this event
215             //
216             this.onset = event;
217             this.numOnsets = 1;
218             //
219             notification.setNotification(ControlLoopNotificationType.ACTIVE);
220             //
221             // Set ourselves as active
222             //
223             this.isActivated = true;
224         } catch (ControlLoopException e) {
225             logger.error("{}: activate by event threw: ", this, e);
226             notification.setNotification(ControlLoopNotificationType.REJECTED);
227             notification.setMessage(e.getMessage());
228         }
229         return notification;
230     }
231
232     /**
233      * Activate a control loop event.
234      *
235      * @param yamlSpecification the yaml specification
236      * @param event the event
237      * @return the VirtualControlLoopNotification
238      */
239     public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) {
240         VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
241         try {
242             //
243             // This method should ONLY be called ONCE
244             //
245             if (this.isActivated) {
246                 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
247             }
248             //
249             // Syntax check the event
250             //
251             checkEventSyntax(event);
252
253             //
254             // Check the YAML
255             //
256             if (yamlSpecification == null || yamlSpecification.length() < 1) {
257                 throw new ControlLoopException("yaml specification is null or 0 length");
258             }
259         } catch (ControlLoopException e) {
260             logger.error("{}: activate by YAML specification and event threw: ", this, e);
261             notification.setNotification(ControlLoopNotificationType.REJECTED);
262             notification.setMessage(e.getMessage());
263             return notification;
264         }
265
266         String decodedYaml = null;
267         try {
268             decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8");
269             if (decodedYaml != null && decodedYaml.length() > 0) {
270                 yamlSpecification = decodedYaml;
271             }
272         } catch (UnsupportedEncodingException e) {
273             logger.error("{}: YAML decode in activate by YAML specification and event threw: ", this, e);
274             notification.setNotification(ControlLoopNotificationType.REJECTED);
275             notification.setMessage(e.getMessage());
276             return notification;
277         }
278
279         try {
280             //
281             // Parse the YAML specification
282             //
283             this.processor = new ControlLoopProcessor(yamlSpecification);
284             //
285             // At this point we are good to go with this event
286             //
287             this.onset = event;
288             this.numOnsets = 1;
289             //
290             //
291             //
292             notification.setNotification(ControlLoopNotificationType.ACTIVE);
293             //
294             // Set ourselves as active
295             //
296             this.isActivated = true;
297         } catch (ControlLoopException e) {
298             logger.error("{}: activate by YAML specification and event threw: ", this, e);
299             notification.setNotification(ControlLoopNotificationType.REJECTED);
300             notification.setMessage(e.getMessage());
301         }
302         return notification;
303     }
304
305     /**
306      * Check if the control loop is final.
307      *
308      * @return a VirtualControlLoopNotification if the control loop is final, otherwise
309      *         <code>null</code> is returned
310      * @throws ControlLoopException if an error occurs
311      */
312     public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException {
313         //
314         // Check if they activated us
315         //
316         if (!this.isActivated) {
317             throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
318         }
319         //
320         // Make sure we are expecting this call.
321         //
322         if (this.onset == null) {
323             throw new ControlLoopException("No onset event for ControlLoopEventManager.");
324         }
325         //
326         // Ok, start creating the notification
327         //
328         VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
329         //
330         // Check if the overall control loop has timed out
331         //
332         if (this.isControlLoopTimedOut()) {
333             //
334             // Yes we have timed out
335             //
336             notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
337             notification.setMessage("Control Loop timed out");
338             notification.getHistory().addAll(this.controlLoopHistory);
339             return notification;
340         }
341         //
342         // Check if the current policy is Final
343         //
344         FinalResult result = this.processor.checkIsCurrentPolicyFinal();
345         if (result == null) {
346             //
347             // we are not at a final result
348             //
349             return null;
350         }
351
352         switch (result) {
353             case FINAL_FAILURE_EXCEPTION:
354                 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
355                 notification.setMessage("Exception in processing closed loop");
356                 break;
357             case FINAL_FAILURE:
358             case FINAL_FAILURE_RETRIES:
359             case FINAL_FAILURE_TIMEOUT:
360             case FINAL_FAILURE_GUARD:
361                 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
362                 break;
363             case FINAL_OPENLOOP:
364                 notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP);
365                 break;
366             case FINAL_SUCCESS:
367                 notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS);
368                 break;
369             default:
370                 return null;
371         }
372         //
373         // Be sure to add all the history
374         //
375         notification.getHistory().addAll(this.controlLoopHistory);
376         return notification;
377     }
378
379     /**
380      * Process the control loop.
381      *
382      * @return a ControlLoopOperationManager
383      * @throws ControlLoopException if an error occurs
384      * @throws AaiException if an error occurs retrieving information from A&AI
385      */
386     public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AaiException {
387         //
388         // Check if they activated us
389         //
390         if (!this.isActivated) {
391             throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
392         }
393         //
394         // Make sure we are expecting this call.
395         //
396         if (this.onset == null) {
397             throw new ControlLoopException("No onset event for ControlLoopEventManager.");
398         }
399         //
400         // Is there a current operation?
401         //
402         if (this.currentOperation != null) {
403             //
404             // Throw an exception, or simply return the current operation?
405             //
406             throw new ControlLoopException("Already working an Operation, do not call this method.");
407         }
408         //
409         // Ensure we are not FINAL
410         //
411         VirtualControlLoopNotification notification = this.isControlLoopFinal();
412         if (notification != null) {
413             //
414             // This is weird, we require them to call the isControlLoopFinal() method first
415             //
416             // We should really abstract this and avoid throwing an exception, because it really
417             // isn't an exception.
418             //
419             throw new ControlLoopException("Control Loop is in FINAL state, do not call this method.");
420         }
421         //
422         // Not final so get the policy that needs to be worked on.
423         //
424         Policy policy = this.processor.getCurrentPolicy();
425         if (policy == null) {
426             throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy.");
427         }
428         //
429         // And setup an operation
430         //
431         this.lastOperationManager = this.currentOperation;
432         this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this);
433         //
434         // Return it
435         //
436         return this.currentOperation;
437     }
438
439     /**
440      * Finish an operation.
441      *
442      * @param operation the operation
443      */
444     public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException {
445         //
446         // Verify we have a current operation
447         //
448         if (this.currentOperation != null) {
449             //
450             // Validate they are finishing the current operation
451             // PLD - this is simply comparing the policy. Do we want to equals the whole object?
452             //
453             if (this.currentOperation.policy.equals(operation.policy)) {
454                 logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(),
455                         this.currentOperation.getOperationResult());
456                 //
457                 // Save history
458                 //
459                 this.controlLoopHistory.addAll(this.currentOperation.getHistory());
460                 //
461                 // Move to the next Policy
462                 //
463                 this.processor.nextPolicyForResult(this.currentOperation.getOperationResult());
464                 //
465                 // Just null this out
466                 //
467                 this.lastOperationManager = this.currentOperation;
468                 this.currentOperation = null;
469                 //
470                 // TODO: Release our lock
471                 //
472                 return;
473             }
474             logger.debug("Cannot finish current operation {} does not match given operation {}",
475                     this.currentOperation.policy, operation.policy);
476             return;
477         }
478         throw new ControlLoopException("No operation to finish.");
479     }
480
481     /**
482      * Obtain a lock for the current operation.
483      *
484      * @return the lock result
485      * @throws ControlLoopException if an error occurs
486      */
487     public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException {
488         //
489         // Sanity check
490         //
491         if (this.currentOperation == null) {
492             throw new ControlLoopException("Do not have a current operation.");
493         }
494         //
495         // Not using target locks? Create and return a lock w/o actually locking.
496         //
497         if (!this.useTargetLock) {
498             TargetLock lock = PolicyGuard.createTargetLock(this.currentOperation.policy.getTarget().getType(),
499                                                            this.currentOperation.getTargetEntity(),
500                                                            this.onset.getRequestId(), this);
501             this.targetLock = lock;
502             return LockResult.createLockResult(GuardResult.LOCK_ACQUIRED, lock);
503         }
504         //
505         // Have we acquired it already?
506         //
507         if (this.targetLock != null) {
508             //
509             // TODO: Make sure the current lock is for the same target.
510             // Currently, it should be. But in the future it may not.
511             //
512             GuardResult result = PolicyGuard.lockTarget(targetLock,
513                             this.currentOperation.getOperationTimeout() + ADDITIONAL_LOCK_SEC);
514             return new LockResult<>(result, this.targetLock);
515         } else {
516             //
517             // Ask the Guard
518             //
519             LockResult<GuardResult, TargetLock> lockResult =
520                     PolicyGuard.lockTarget(this.currentOperation.policy.getTarget().getType(),
521                             this.currentOperation.getTargetEntity(), this.onset.getRequestId(), this,
522                             this.currentOperation.getOperationTimeout() + ADDITIONAL_LOCK_SEC);
523             //
524             // Was it acquired?
525             //
526             if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) {
527                 //
528                 // Yes, let's save it
529                 //
530                 this.targetLock = lockResult.getB();
531             }
532             return lockResult;
533         }
534     }
535
536     /**
537      * Release the lock for the current operation.
538      *
539      * @return the target lock
540      */
541     public synchronized TargetLock unlockCurrentOperation() {
542         if (this.targetLock == null) {
543             return null;
544         }
545
546         TargetLock returnLock = this.targetLock;
547         this.targetLock = null;
548         //
549         // if using target locking unlock before returning
550         //
551         if (this.useTargetLock) {
552             PolicyGuard.unlockTarget(returnLock);
553         }
554
555         // always return the old target lock so rules can retract it
556         return returnLock;
557     }
558
559     public enum NewEventStatus {
560         FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR;
561     }
562
563     /**
564      * An event onset/abatement.
565      *
566      * @param event the event
567      * @return the status
568      * @throws AaiException if an error occurs retrieving information from A&AI
569      */
570     public NewEventStatus onNewEvent(VirtualControlLoopEvent event) throws AaiException {
571         try {
572             this.checkEventSyntax(event);
573             if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) {
574                 //
575                 // Check if this is our original ONSET
576                 //
577                 if (event.equals(this.onset)) {
578                     //
579                     // Query A&AI if needed
580                     //
581                     queryAai(event);
582
583                     //
584                     // DO NOT retract it
585                     //
586                     return NewEventStatus.FIRST_ONSET;
587                 }
588                 //
589                 // Log that we got an onset
590                 //
591                 this.numOnsets++;
592                 return NewEventStatus.SUBSEQUENT_ONSET;
593             } else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
594                 //
595                 // Have we already got an abatement?
596                 //
597                 if (this.abatement == null) {
598                     //
599                     // Save this
600                     //
601                     this.abatement = event;
602                     //
603                     // Keep track that we received another
604                     //
605                     this.numAbatements++;
606                     //
607                     //
608                     //
609                     return NewEventStatus.FIRST_ABATEMENT;
610                 } else {
611                     //
612                     // Keep track that we received another
613                     //
614                     this.numAbatements++;
615                     //
616                     //
617                     //
618                     return NewEventStatus.SUBSEQUENT_ABATEMENT;
619                 }
620             }
621         } catch (ControlLoopException e) {
622             logger.error("{}: onNewEvent threw: ", this, e);
623         }
624         return NewEventStatus.SYNTAX_ERROR;
625     }
626
627
628     /**
629      * Commit the abatement to the history database.
630      *
631      * @param message the abatement message
632      * @param outcome the abatement outcome
633      */
634     public void commitAbatement(String message, String outcome) {
635         if (this.lastOperationManager == null) {
636             logger.error("{}: commitAbatement: no operation manager", this);
637             return;
638         }
639         try {
640             this.lastOperationManager.commitAbatement(message,outcome);          
641         } catch (NoSuchElementException e) {
642             logger.error("{}: commitAbatement threw an exception ", this, e);
643         }
644     }
645
646     
647     /**
648      * Set the control loop time out.
649      *
650      * @return a VirtualControlLoopNotification
651      */
652     public VirtualControlLoopNotification setControlLoopTimedOut() {
653         this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT;
654         VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
655         notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
656         notification.setMessage("Control Loop timed out");
657         notification.getHistory().addAll(this.controlLoopHistory);
658         return notification;
659     }
660
661     public boolean isControlLoopTimedOut() {
662         return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT);
663     }
664
665     /**
666      * Get the control loop timeout.
667      *
668      * @param defaultTimeout the default timeout
669      * @return the timeout
670      */
671     public int getControlLoopTimeout(Integer defaultTimeout) {
672         if (this.processor != null && this.processor.getControlLoop() != null) {
673             return this.processor.getControlLoop().getTimeout();
674         }
675         if (defaultTimeout != null) {
676             return defaultTimeout;
677         }
678         return 0;
679     }
680
681     public AaiGetVnfResponse getVnfResponse() {
682         return vnfResponse;
683     }
684
685     public AaiGetVserverResponse getVserverResponse() {
686         return vserverResponse;
687     }
688
689     /**
690      * Check an event syntax.
691      *
692      * @param event the event syntax
693      * @throws ControlLoopException if an error occurs
694      */
695     public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
696         if (event.getClosedLoopEventStatus() == null
697                 || (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET
698                         && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED)) {
699             throw new ControlLoopException("Invalid value in closedLoopEventStatus");
700         }
701         if (event.getClosedLoopControlName() == null || event.getClosedLoopControlName().length() < 1) {
702             throw new ControlLoopException("No control loop name");
703         }
704         if (event.getRequestId() == null) {
705             throw new ControlLoopException("No request ID");
706         }
707         if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
708             return;
709         }
710         if (event.getTarget() == null || event.getTarget().length() < 1) {
711             throw new ControlLoopException("No target field");
712         } else if (!VM_NAME.equalsIgnoreCase(event.getTarget()) && !VNF_NAME.equalsIgnoreCase(event.getTarget())
713                 && !VSERVER_VSERVER_NAME.equalsIgnoreCase(event.getTarget())
714                 && !GENERIC_VNF_VNF_ID.equalsIgnoreCase(event.getTarget())
715                 && !GENERIC_VNF_VNF_NAME.equalsIgnoreCase(event.getTarget())) {
716             throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME");
717         }
718         if (event.getAai() == null) {
719             throw new ControlLoopException("AAI is null");
720         }
721         if (event.getAai().get(GENERIC_VNF_VNF_ID) == null && event.getAai().get(VSERVER_VSERVER_NAME) == null
722                 && event.getAai().get(GENERIC_VNF_VNF_NAME) == null) {
723             throw new ControlLoopException(
724                     "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
725         }
726     }
727
728     /**
729      * Query A&AI for an event.
730      *
731      * @param event the event
732      * @throws AaiException if an error occurs retrieving information from A&AI
733      */
734     public void queryAai(VirtualControlLoopEvent event) throws AaiException {
735
736         Map<String, String> aai = event.getAai();
737
738         if (aai.containsKey(VSERVER_IS_CLOSED_LOOP_DISABLED) || aai.containsKey(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) {
739
740             if (isClosedLoopDisabled(event)) {
741                 throw new AaiException("is-closed-loop-disabled is set to true on VServer or VNF");
742             }
743
744             if (isProvStatusInactive(event)) {
745                 throw new AaiException("prov-status is not ACTIVE on VServer or VNF");
746             }
747
748             // no need to query, as we already have the data
749             return;
750         }
751
752         if (vnfResponse != null || vserverResponse != null) {
753             // query has already been performed
754             return;
755         }
756
757         try {
758             if (aai.containsKey(GENERIC_VNF_VNF_ID) || aai.containsKey(GENERIC_VNF_VNF_NAME)) {
759                 vnfResponse = getAaiVnfInfo(event);
760                 processVnfResponse(vnfResponse, aai.containsKey(GENERIC_VNF_VNF_ID));
761             } else if (aai.containsKey(VSERVER_VSERVER_NAME)) {
762                 vserverResponse = getAaiVserverInfo(event);
763                 processVServerResponse(vserverResponse);
764             }
765         } catch (AaiException e) {
766             logger.error(QUERY_AAI_ERROR_MSG, e);
767             throw e;
768         } catch (Exception e) {
769             logger.error(QUERY_AAI_ERROR_MSG, e);
770             throw new AaiException(QUERY_AAI_ERROR_MSG + e.toString());
771         }
772     }
773
774     /**
775      * Process a response from A&AI for a VNF.
776      *
777      * @param aaiResponse the response from A&AI
778      * @param queryByVnfId <code>true</code> if the query was based on vnf-id,
779      *        <code>false</code> if the query was based on vnf-name
780      * @throws AaiException if an error occurs processing the response
781      */
782     private static void processVnfResponse(AaiGetVnfResponse aaiResponse, boolean queryByVnfId) throws AaiException {
783         String queryTypeString = (queryByVnfId ? "vnf-id" : "vnf-name");
784
785         if (aaiResponse == null) {
786             throw new AaiException("AAI Response is null (query by " + queryTypeString + ")");
787         }
788         if (aaiResponse.getRequestError() != null) {
789             throw new AaiException("AAI Responded with a request error (query by " + queryTypeString + ")");
790         }
791
792         if (aaiResponse.getIsClosedLoopDisabled()) {
793             throw new AaiException("is-closed-loop-disabled is set to true (query by " + queryTypeString + ")");
794         }
795
796         if (!PROV_STATUS_ACTIVE.equals(aaiResponse.getProvStatus())) {
797             throw new AaiException("prov-status is not ACTIVE (query by " + queryTypeString + ")");
798         }
799     }
800
801     /**
802      * Process a response from A&AI for a VServer.
803      *
804      * @param aaiResponse the response from A&AI
805      * @throws AaiException if an error occurs processing the response
806      */
807     private static void processVServerResponse(AaiGetVserverResponse aaiResponse) throws AaiException {
808         if (aaiResponse == null) {
809             throw new AaiException("AAI Response is null (query by vserver-name)");
810         }
811         if (aaiResponse.getRequestError() != null) {
812             throw new AaiException("AAI Responded with a request error (query by vserver-name)");
813         }
814
815         List<AaiNqVServer> lst = aaiResponse.getVserver();
816         if (lst.isEmpty()) {
817             return;
818         }
819
820         AaiNqVServer svr = lst.get(0);
821         if (svr.getIsClosedLoopDisabled()) {
822             throw new AaiException("is-closed-loop-disabled is set to true (query by vserver-name)");
823         }
824
825         if (!PROV_STATUS_ACTIVE.equals(svr.getProvStatus())) {
826             throw new AaiException("prov-status is not ACTIVE (query by vserver-name)");
827         }
828     }
829
830     /**
831      * Is closed loop disabled for an event.
832      *
833      * @param event the event
834      * @return <code>true</code> if the control loop is disabled, <code>false</code>
835      *         otherwise
836      */
837     public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
838         Map<String, String> aai = event.getAai();
839         return (isAaiTrue(aai.get(VSERVER_IS_CLOSED_LOOP_DISABLED))
840                         || isAaiTrue(aai.get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)));
841     }
842
843     /**
844      * Does provisioning status, for an event, have a value other than ACTIVE.
845      *
846      * @param event the event
847      * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null},
848      *         {@code false} otherwise
849      */
850     protected static boolean isProvStatusInactive(VirtualControlLoopEvent event) {
851         Map<String, String> aai = event.getAai();
852         return (!PROV_STATUS_ACTIVE.equals(aai.getOrDefault(VSERVER_PROV_STATUS, PROV_STATUS_ACTIVE))
853                         || !PROV_STATUS_ACTIVE.equals(aai.getOrDefault(GENERIC_VNF_PROV_STATUS, PROV_STATUS_ACTIVE)));
854     }
855
856     /**
857      * Determines the boolean value represented by the given AAI field value.
858      *
859      * @param aaiValue value to be examined
860      * @return the boolean value represented by the field value, or {@code false} if the
861      *         value is {@code null}
862      */
863     protected static boolean isAaiTrue(String aaiValue) {
864         return ("true".equalsIgnoreCase(aaiValue) || "T".equalsIgnoreCase(aaiValue) || "yes".equalsIgnoreCase(aaiValue)
865                         || "Y".equalsIgnoreCase(aaiValue));
866     }
867
868     /**
869      * Get the A&AI VService information for an event.
870      *
871      * @param event the event
872      * @return a AaiGetVserverResponse
873      * @throws ControlLoopException if an error occurs
874      */
875     public static AaiGetVserverResponse getAaiVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException {
876         UUID requestId = event.getRequestId();
877         AaiGetVserverResponse response = null;
878         String vserverName = event.getAai().get(VSERVER_VSERVER_NAME);
879
880         try {
881             if (vserverName != null) {
882                 String aaiHostUrl = PolicyEngine.manager.getEnvironmentProperty(AAI_URL);
883                 String aaiUser = PolicyEngine.manager.getEnvironmentProperty(AAI_USERNAME_PROPERTY);
884                 String aaiPassword = PolicyEngine.manager.getEnvironmentProperty(AAI_PASS_PROPERTY);
885                 String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name=";
886                 String url = aaiHostUrl + aaiGetQueryByVserver;
887                 logger.info("AAI Host URL by VServer: {}", url);
888                 response = new AaiManager(new RestManager()).getQueryByVserverName(url, aaiUser, aaiPassword, requestId,
889                         vserverName);
890             }
891         } catch (Exception e) {
892             logger.error("getAaiVserverInfo exception: ", e);
893             throw new ControlLoopException("Exception in getAaiVserverInfo: ", e);
894         }
895
896         return response;
897     }
898
899     /**
900      * Get A&AI VNF information for an event.
901      *
902      * @param event the event
903      * @return a AaiGetVnfResponse
904      * @throws ControlLoopException if an error occurs
905      */
906     public static AaiGetVnfResponse getAaiVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException {
907         UUID requestId = event.getRequestId();
908         AaiGetVnfResponse response = null;
909         String vnfName = event.getAai().get(GENERIC_VNF_VNF_NAME);
910         String vnfId = event.getAai().get(GENERIC_VNF_VNF_ID);
911
912         String aaiHostUrl = PolicyEngine.manager.getEnvironmentProperty(AAI_URL);
913         String aaiUser = PolicyEngine.manager.getEnvironmentProperty(AAI_USERNAME_PROPERTY);
914         String aaiPassword = PolicyEngine.manager.getEnvironmentProperty(AAI_PASS_PROPERTY);
915
916         try {
917             if (vnfName != null) {
918                 String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=";
919                 String url = aaiHostUrl + aaiGetQueryByVnfName;
920                 logger.info("AAI Host URL by VNF name: {}", url);
921                 response = new AaiManager(new RestManager()).getQueryByVnfName(url, aaiUser, aaiPassword, requestId,
922                         vnfName);
923             } else if (vnfId != null) {
924                 String aaiGetQueryByVnfId = "/aai/v11/network/generic-vnfs/generic-vnf/";
925                 String url = aaiHostUrl + aaiGetQueryByVnfId;
926                 logger.info("AAI Host URL by VNF ID: {}", url);
927                 response =
928                         new AaiManager(new RestManager()).getQueryByVnfId(url, aaiUser, aaiPassword, requestId, vnfId);
929             }
930         } catch (Exception e) {
931             logger.error("getAaiVnfInfo exception: ", e);
932             throw new ControlLoopException("Exception in getAaiVnfInfo: ", e);
933         }
934
935         return response;
936     }
937
938     /**
939      * Gets the output from the AAI vserver named-query, using the cache, if appropriate.
940      * @return output from the AAI vserver named-query
941      */
942     public AaiNqResponseWrapper getNqVserverFromAai() {
943         if (nqVserverResponse != null) {
944             // already queried
945             return nqVserverResponse;
946         }
947
948         String vserverName = onset.getAai().get(VSERVER_VSERVER_NAME);
949         if (vserverName == null) {
950             logger.warn("Missing vserver-name for AAI request {}", onset.getRequestId());
951             return null;
952         }
953
954         // create AAI named-query request with UUID started with ""
955         AaiNqRequest aaiNqRequest = new AaiNqRequest();
956         AaiNqQueryParameters aaiNqQueryParam = new AaiNqQueryParameters();
957         AaiNqNamedQuery aaiNqNamedQuery = new AaiNqNamedQuery();
958         final AaiNqInstanceFilters aaiNqInstanceFilter = new AaiNqInstanceFilters();
959
960         // queryParameters
961         aaiNqNamedQuery.setNamedQueryUuid(UUID.fromString("4ff56a54-9e3f-46b7-a337-07a1d3c6b469"));
962         aaiNqQueryParam.setNamedQuery(aaiNqNamedQuery);
963         aaiNqRequest.setQueryParameters(aaiNqQueryParam);
964         //
965         // instanceFilters
966         //
967         Map<String, Map<String, String>> aaiNqInstanceFilterMap = new HashMap<>();
968         Map<String, String> aaiNqInstanceFilterMapItem = new HashMap<>();
969         aaiNqInstanceFilterMapItem.put("vserver-name", vserverName);
970         aaiNqInstanceFilterMap.put("vserver", aaiNqInstanceFilterMapItem);
971         aaiNqInstanceFilter.getInstanceFilter().add(aaiNqInstanceFilterMap);
972         aaiNqRequest.setInstanceFilters(aaiNqInstanceFilter);
973
974         if (logger.isDebugEnabled()) {
975             logger.debug("AAI Request sent: {}", Serialization.gsonPretty.toJson(aaiNqRequest));
976         }
977
978         AaiNqResponse aaiNqResponse = new AaiManager(new RestManager()).postQuery(getPeManagerEnvProperty(AAI_URL),
979                 getPeManagerEnvProperty(AAI_USERNAME_PROPERTY), getPeManagerEnvProperty(AAI_PASS_PROPERTY), 
980                 aaiNqRequest, onset.getRequestId());
981
982         // Check AAI response
983         if (aaiNqResponse == null) {
984             logger.warn("No response received from AAI for request {}", aaiNqRequest);
985             return null;
986         }
987
988         // Create AAINQResponseWrapper
989         nqVserverResponse = new AaiNqResponseWrapper(onset.getRequestId(), aaiNqResponse);
990
991         if (logger.isDebugEnabled()) {
992             logger.debug("AAI Named Query Response: ");
993             logger.debug(Serialization.gsonPretty.toJson(nqVserverResponse.getAaiNqResponse()));
994         }
995
996         return nqVserverResponse;
997     }
998
999     /**
1000      * This method reads and validates environmental properties coming from the policy engine. Null
1001      * properties cause an {@link IllegalArgumentException} runtime exception to be thrown
1002      *
1003      * @param enginePropertyName the name of the parameter to retrieve
1004      * @return the property value
1005      */
1006     private static String getPeManagerEnvProperty(String enginePropertyName) {
1007         String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName);
1008         if (enginePropertyValue == null) {
1009             throw new IllegalArgumentException("The value of policy engine manager environment property \""
1010                     + enginePropertyName + "\" may not be null");
1011         }
1012         return enginePropertyValue;
1013     }
1014
1015     @Override
1016     public boolean isActive() {
1017         // TODO
1018         return true;
1019     }
1020
1021     @Override
1022     public boolean releaseLock() {
1023         // TODO
1024         return false;
1025     }
1026
1027     @Override
1028     public String toString() {
1029         return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestId=" + requestId
1030                 + ", processor=" + processor + ", onset=" + (onset != null ? onset.getRequestId() : "null")
1031                 + ", numOnsets=" + numOnsets + ", numAbatements=" + numAbatements + ", isActivated=" + isActivated
1032                 + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]";
1033     }
1034
1035 }