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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controlloop.eventmanager;
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;
32 import java.util.NoSuchElementException;
33 import java.util.UUID;
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;
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";
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";
82 private static final String QUERY_AAI_ERROR_MSG = "Exception from queryAai: ";
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.
88 private static final int ADDITIONAL_LOCK_SEC = 60;
90 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class);
92 private static final long serialVersionUID = -1216568161322872641L;
93 public final String closedLoopControlName;
94 private final UUID requestId;
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;
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;
114 * Wrapper for AAI vserver named-query response. This is initialized in a lazy
117 private AaiNqResponseWrapper nqVserverResponse = null;
119 private static Collection<String> requiredAAIKeys = new ArrayList<>();
122 requiredAAIKeys.add("AICVServerSelfLink");
123 requiredAAIKeys.add("AICIdentity");
124 requiredAAIKeys.add("is_closed_loop_disabled");
125 requiredAAIKeys.add(VM_NAME);
128 public ControlLoopEventManager(String closedLoopControlName, UUID requestId) {
129 this.closedLoopControlName = closedLoopControlName;
130 this.requestId = requestId;
133 public String getClosedLoopControlName() {
134 return closedLoopControlName;
137 public String getControlLoopResult() {
138 return controlLoopResult;
141 public void setControlLoopResult(String controlLoopResult) {
142 this.controlLoopResult = controlLoopResult;
145 public Integer getNumOnsets() {
149 public void setNumOnsets(Integer numOnsets) {
150 this.numOnsets = numOnsets;
153 public Integer getNumAbatements() {
154 return numAbatements;
157 public void setNumAbatements(Integer numAbatements) {
158 this.numAbatements = numAbatements;
161 public boolean isActivated() {
165 public void setActivated(boolean isActivated) {
166 this.isActivated = isActivated;
169 public boolean useTargetLock() {
170 return useTargetLock();
173 public void setUseTargetLock(boolean useTargetLock) {
174 this.useTargetLock = useTargetLock;
177 public VirtualControlLoopEvent getOnsetEvent() {
181 public VirtualControlLoopEvent getAbatementEvent() {
182 return this.abatement;
185 public ControlLoopProcessor getProcessor() {
186 return this.processor;
189 public UUID getRequestID() {
194 * Activate a control loop event.
196 * @param event the event
197 * @return the VirtualControlLoopNotification
199 public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) {
200 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
203 // This method should ONLY be called ONCE
205 if (this.isActivated) {
206 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
209 // Syntax check the event
211 checkEventSyntax(event);
214 // At this point we are good to go with this event
219 notification.setNotification(ControlLoopNotificationType.ACTIVE);
221 // Set ourselves as active
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());
233 * Activate a control loop event.
235 * @param yamlSpecification the yaml specification
236 * @param event the event
237 * @return the VirtualControlLoopNotification
239 public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) {
240 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
243 // This method should ONLY be called ONCE
245 if (this.isActivated) {
246 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
249 // Syntax check the event
251 checkEventSyntax(event);
256 if (yamlSpecification == null || yamlSpecification.length() < 1) {
257 throw new ControlLoopException("yaml specification is null or 0 length");
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());
266 String decodedYaml = null;
268 decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8");
269 if (decodedYaml != null && decodedYaml.length() > 0) {
270 yamlSpecification = decodedYaml;
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());
281 // Parse the YAML specification
283 this.processor = new ControlLoopProcessor(yamlSpecification);
285 // At this point we are good to go with this event
292 notification.setNotification(ControlLoopNotificationType.ACTIVE);
294 // Set ourselves as active
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());
306 * Check if the control loop is final.
308 * @return a VirtualControlLoopNotification if the control loop is final, otherwise
309 * <code>null</code> is returned
310 * @throws ControlLoopException if an error occurs
312 public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException {
314 // Check if they activated us
316 if (!this.isActivated) {
317 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
320 // Make sure we are expecting this call.
322 if (this.onset == null) {
323 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
326 // Ok, start creating the notification
328 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
330 // Check if the overall control loop has timed out
332 if (this.isControlLoopTimedOut()) {
334 // Yes we have timed out
336 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
337 notification.setMessage("Control Loop timed out");
338 notification.getHistory().addAll(this.controlLoopHistory);
342 // Check if the current policy is Final
344 FinalResult result = this.processor.checkIsCurrentPolicyFinal();
345 if (result == null) {
347 // we are not at a final result
353 case FINAL_FAILURE_EXCEPTION:
354 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
355 notification.setMessage("Exception in processing closed loop");
358 case FINAL_FAILURE_RETRIES:
359 case FINAL_FAILURE_TIMEOUT:
360 case FINAL_FAILURE_GUARD:
361 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
364 notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP);
367 notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS);
373 // Be sure to add all the history
375 notification.getHistory().addAll(this.controlLoopHistory);
380 * Process the control loop.
382 * @return a ControlLoopOperationManager
383 * @throws ControlLoopException if an error occurs
384 * @throws AaiException if an error occurs retrieving information from A&AI
386 public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AaiException {
388 // Check if they activated us
390 if (!this.isActivated) {
391 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
394 // Make sure we are expecting this call.
396 if (this.onset == null) {
397 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
400 // Is there a current operation?
402 if (this.currentOperation != null) {
404 // Throw an exception, or simply return the current operation?
406 throw new ControlLoopException("Already working an Operation, do not call this method.");
409 // Ensure we are not FINAL
411 VirtualControlLoopNotification notification = this.isControlLoopFinal();
412 if (notification != null) {
414 // This is weird, we require them to call the isControlLoopFinal() method first
416 // We should really abstract this and avoid throwing an exception, because it really
417 // isn't an exception.
419 throw new ControlLoopException("Control Loop is in FINAL state, do not call this method.");
422 // Not final so get the policy that needs to be worked on.
424 Policy policy = this.processor.getCurrentPolicy();
425 if (policy == null) {
426 throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy.");
429 // And setup an operation
431 this.lastOperationManager = this.currentOperation;
432 this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this);
436 return this.currentOperation;
440 * Finish an operation.
442 * @param operation the operation
444 public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException {
446 // Verify we have a current operation
448 if (this.currentOperation != null) {
450 // Validate they are finishing the current operation
451 // PLD - this is simply comparing the policy. Do we want to equals the whole object?
453 if (this.currentOperation.policy.equals(operation.policy)) {
454 logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(),
455 this.currentOperation.getOperationResult());
459 this.controlLoopHistory.addAll(this.currentOperation.getHistory());
461 // Move to the next Policy
463 this.processor.nextPolicyForResult(this.currentOperation.getOperationResult());
465 // Just null this out
467 this.lastOperationManager = this.currentOperation;
468 this.currentOperation = null;
470 // TODO: Release our lock
474 logger.debug("Cannot finish current operation {} does not match given operation {}",
475 this.currentOperation.policy, operation.policy);
478 throw new ControlLoopException("No operation to finish.");
482 * Obtain a lock for the current operation.
484 * @return the lock result
485 * @throws ControlLoopException if an error occurs
487 public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException {
491 if (this.currentOperation == null) {
492 throw new ControlLoopException("Do not have a current operation.");
495 // Not using target locks? Create and return a lock w/o actually locking.
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);
505 // Have we acquired it already?
507 if (this.targetLock != null) {
509 // TODO: Make sure the current lock is for the same target.
510 // Currently, it should be. But in the future it may not.
512 GuardResult result = PolicyGuard.lockTarget(targetLock,
513 this.currentOperation.getOperationTimeout() + ADDITIONAL_LOCK_SEC);
514 return new LockResult<>(result, this.targetLock);
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);
526 if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) {
528 // Yes, let's save it
530 this.targetLock = lockResult.getB();
537 * Release the lock for the current operation.
539 * @return the target lock
541 public synchronized TargetLock unlockCurrentOperation() {
542 if (this.targetLock == null) {
546 TargetLock returnLock = this.targetLock;
547 this.targetLock = null;
549 // if using target locking unlock before returning
551 if (this.useTargetLock) {
552 PolicyGuard.unlockTarget(returnLock);
555 // always return the old target lock so rules can retract it
559 public enum NEW_EVENT_STATUS {
560 FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR;
564 * An event onset/abatement.
566 * @param event the event
568 * @throws AaiException if an error occurs retrieving information from A&AI
570 public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) throws AaiException {
572 this.checkEventSyntax(event);
573 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) {
575 // Check if this is our original ONSET
577 if (event.equals(this.onset)) {
579 // Query A&AI if needed
586 return NEW_EVENT_STATUS.FIRST_ONSET;
589 // Log that we got an onset
592 return NEW_EVENT_STATUS.SUBSEQUENT_ONSET;
593 } else if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
595 // Have we already got an abatement?
597 if (this.abatement == null) {
601 this.abatement = event;
603 // Keep track that we received another
605 this.numAbatements++;
609 return NEW_EVENT_STATUS.FIRST_ABATEMENT;
612 // Keep track that we received another
614 this.numAbatements++;
618 return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT;
621 } catch (ControlLoopException e) {
622 logger.error("{}: onNewEvent threw: ", this, e);
624 return NEW_EVENT_STATUS.SYNTAX_ERROR;
629 * Commit the abatement to the history database.
631 * @param message the abatement message
632 * @param outcome the abatement outcome
634 public void commitAbatement(String message, String outcome) {
635 if (this.lastOperationManager == null) {
636 logger.error("{}: commitAbatement: no operation manager", this);
640 this.lastOperationManager.commitAbatement(message,outcome);
641 } catch (NoSuchElementException e) {
642 logger.error("{}: commitAbatement threw an exception ", this, e);
648 * Set the control loop time out.
650 * @return a VirtualControlLoopNotification
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);
661 public boolean isControlLoopTimedOut() {
662 return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT);
666 * Get the control loop timeout.
668 * @param defaultTimeout the default timeout
669 * @return the timeout
671 public int getControlLoopTimeout(Integer defaultTimeout) {
672 if (this.processor != null && this.processor.getControlLoop() != null) {
673 return this.processor.getControlLoop().getTimeout();
675 if (defaultTimeout != null) {
676 return defaultTimeout;
681 public AaiGetVnfResponse getVnfResponse() {
685 public AaiGetVserverResponse getVserverResponse() {
686 return vserverResponse;
690 * Check an event syntax.
692 * @param event the event syntax
693 * @throws ControlLoopException if an error occurs
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");
701 if (event.getClosedLoopControlName() == null || event.getClosedLoopControlName().length() < 1) {
702 throw new ControlLoopException("No control loop name");
704 if (event.getRequestId() == null) {
705 throw new ControlLoopException("No request ID");
707 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
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");
718 if (event.getAai() == null) {
719 throw new ControlLoopException("AAI is null");
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");
729 * Query A&AI for an event.
731 * @param event the event
732 * @throws AaiException if an error occurs retrieving information from A&AI
734 public void queryAai(VirtualControlLoopEvent event) throws AaiException {
736 Map<String, String> aai = event.getAai();
738 if (aai.containsKey(VSERVER_IS_CLOSED_LOOP_DISABLED) || aai.containsKey(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED)) {
740 if (isClosedLoopDisabled(event)) {
741 throw new AaiException("is-closed-loop-disabled is set to true on VServer or VNF");
744 if (isProvStatusInactive(event)) {
745 throw new AaiException("prov-status is not ACTIVE on VServer or VNF");
748 // no need to query, as we already have the data
752 if (vnfResponse != null || vserverResponse != null) {
753 // query has already been performed
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);
765 } catch (AaiException e) {
766 logger.error(QUERY_AAI_ERROR_MSG, e);
768 } catch (Exception e) {
769 logger.error(QUERY_AAI_ERROR_MSG, e);
770 throw new AaiException(QUERY_AAI_ERROR_MSG + e.toString());
775 * Process a response from A&AI for a VNF.
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
782 private static void processVNFResponse(AaiGetVnfResponse aaiResponse, boolean queryByVNFID) throws AaiException {
783 String queryTypeString = (queryByVNFID ? "vnf-id" : "vnf-name");
785 if (aaiResponse == null) {
786 throw new AaiException("AAI Response is null (query by " + queryTypeString + ")");
788 if (aaiResponse.getRequestError() != null) {
789 throw new AaiException("AAI Responded with a request error (query by " + queryTypeString + ")");
792 if (aaiResponse.getIsClosedLoopDisabled()) {
793 throw new AaiException("is-closed-loop-disabled is set to true (query by " + queryTypeString + ")");
796 if (!PROV_STATUS_ACTIVE.equals(aaiResponse.getProvStatus())) {
797 throw new AaiException("prov-status is not ACTIVE (query by " + queryTypeString + ")");
802 * Process a response from A&AI for a VServer.
804 * @param aaiResponse the response from A&AI
805 * @throws AaiException if an error occurs processing the response
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)");
811 if (aaiResponse.getRequestError() != null) {
812 throw new AaiException("AAI Responded with a request error (query by vserver-name)");
815 List<AaiNqVServer> lst = aaiResponse.getVserver();
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)");
825 if (!PROV_STATUS_ACTIVE.equals(svr.getProvStatus())) {
826 throw new AaiException("prov-status is not ACTIVE (query by vserver-name)");
831 * Is closed loop disabled for an event.
833 * @param event the event
834 * @return <code>true</code> if the control loop is disabled, <code>false</code>
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)));
844 * Does provisioning status, for an event, have a value other than ACTIVE.
846 * @param event the event
847 * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null},
848 * {@code false} otherwise
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)));
857 * Determines the boolean value represented by the given AAI field value.
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}
863 protected static boolean isAaiTrue(String aaiValue) {
864 return ("true".equalsIgnoreCase(aaiValue) || "T".equalsIgnoreCase(aaiValue) || "yes".equalsIgnoreCase(aaiValue)
865 || "Y".equalsIgnoreCase(aaiValue));
869 * Get the A&AI VService information for an event.
871 * @param event the event
872 * @return a AaiGetVserverResponse
873 * @throws ControlLoopException if an error occurs
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);
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,
891 } catch (Exception e) {
892 logger.error("getAAIVserverInfo exception: ", e);
893 throw new ControlLoopException("Exception in getAAIVserverInfo: ", e);
900 * Get A&AI VNF information for an event.
902 * @param event the event
903 * @return a AaiGetVnfResponse
904 * @throws ControlLoopException if an error occurs
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);
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);
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,
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);
928 new AaiManager(new RestManager()).getQueryByVnfId(url, aaiUser, aaiPassword, requestId, vnfId);
930 } catch (Exception e) {
931 logger.error("getAAIVnfInfo exception: ", e);
932 throw new ControlLoopException("Exception in getAAIVnfInfo: ", e);
939 * Gets the output from the AAI vserver named-query, using the cache, if appropriate.
940 * @return output from the AAI vserver named-query
942 public AaiNqResponseWrapper getNqVserverFromAai() {
943 if (nqVserverResponse != null) {
945 return nqVserverResponse;
948 String vserverName = onset.getAai().get(VSERVER_VSERVER_NAME);
949 if (vserverName == null) {
950 logger.warn("Missing vserver-name for AAI request {}", onset.getRequestId());
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();
961 aaiNqNamedQuery.setNamedQueryUuid(UUID.fromString("4ff56a54-9e3f-46b7-a337-07a1d3c6b469"));
962 aaiNqQueryParam.setNamedQuery(aaiNqNamedQuery);
963 aaiNqRequest.setQueryParameters(aaiNqQueryParam);
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);
974 if (logger.isDebugEnabled()) {
975 logger.debug("AAI Request sent: {}", Serialization.gsonPretty.toJson(aaiNqRequest));
978 AaiNqResponse aaiNqResponse = new AaiManager(new RestManager()).postQuery(getPeManagerEnvProperty(AAI_URL),
979 getPeManagerEnvProperty(AAI_USERNAME_PROPERTY), getPeManagerEnvProperty(AAI_PASS_PROPERTY),
980 aaiNqRequest, onset.getRequestId());
982 // Check AAI response
983 if (aaiNqResponse == null) {
984 logger.warn("No response received from AAI for request {}", aaiNqRequest);
988 // Create AAINQResponseWrapper
989 nqVserverResponse = new AaiNqResponseWrapper(onset.getRequestId(), aaiNqResponse);
991 if (logger.isDebugEnabled()) {
992 logger.debug("AAI Named Query Response: ");
993 logger.debug(Serialization.gsonPretty.toJson(nqVserverResponse.getAaiNqResponse()));
996 return nqVserverResponse;
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
1003 * @param enginePropertyName the name of the parameter to retrieve
1004 * @return the property value
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");
1012 return enginePropertyValue;
1016 public boolean isActive() {
1022 public boolean releaseLock() {
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 + "]";