2 * ============LICENSE_START=======================================================
3 * controlloop event manager
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
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.LinkedList;
29 import java.util.UUID;
31 import org.onap.policy.aai.AAIGETVnfResponse;
32 import org.onap.policy.aai.AAIGETVserverResponse;
33 import org.onap.policy.aai.AAIManager;
34 import org.onap.policy.aai.util.AAIException;
35 import org.onap.policy.controlloop.ControlLoopEventStatus;
36 import org.onap.policy.controlloop.ControlLoopException;
37 import org.onap.policy.controlloop.ControlLoopNotificationType;
38 import org.onap.policy.controlloop.ControlLoopOperation;
39 import org.onap.policy.controlloop.VirtualControlLoopEvent;
40 import org.onap.policy.controlloop.VirtualControlLoopNotification;
41 import org.onap.policy.controlloop.policy.FinalResult;
42 import org.onap.policy.controlloop.policy.Policy;
43 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
44 import org.onap.policy.guard.GuardResult;
45 import org.onap.policy.guard.LockCallback;
46 import org.onap.policy.guard.PolicyGuard;
47 import org.onap.policy.guard.PolicyGuard.LockResult;
48 import org.onap.policy.guard.TargetLock;
49 import org.onap.policy.drools.system.PolicyEngine;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public class ControlLoopEventManager implements LockCallback, Serializable {
58 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class);
60 private static final long serialVersionUID = -1216568161322872641L;
61 public final String closedLoopControlName;
62 public final UUID requestID;
64 private String controlLoopResult;
65 private transient ControlLoopProcessor processor = null;
66 private VirtualControlLoopEvent onset;
67 private Integer numOnsets = 0;
68 private Integer numAbatements = 0;
69 private VirtualControlLoopEvent abatement;
70 private FinalResult controlLoopTimedOut = null;
72 private boolean isActivated = false;
73 private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
74 private ControlLoopOperationManager currentOperation = null;
75 private transient TargetLock targetLock = null;
76 private AAIGETVnfResponse vnfResponse = null;
77 private AAIGETVserverResponse vserverResponse = null;
78 private static String aaiHostURL;
79 private static String aaiUser;
80 private static String aaiPassword;
82 private static Collection<String> requiredAAIKeys = new ArrayList<>();
84 requiredAAIKeys.add("AICVServerSelfLink");
85 requiredAAIKeys.add("AICIdentity");
86 requiredAAIKeys.add("is_closed_loop_disabled");
87 requiredAAIKeys.add("VM_NAME");
90 public ControlLoopEventManager(String closedLoopControlName, UUID requestID) {
91 this.closedLoopControlName = closedLoopControlName;
92 this.requestID = requestID;
95 public String getControlLoopResult() {
96 return controlLoopResult;
99 public void setControlLoopResult(String controlLoopResult) {
100 this.controlLoopResult = controlLoopResult;
103 public Integer getNumOnsets() {
107 public void setNumOnsets(Integer numOnsets) {
108 this.numOnsets = numOnsets;
111 public Integer getNumAbatements() {
112 return numAbatements;
115 public void setNumAbatements(Integer numAbatements) {
116 this.numAbatements = numAbatements;
119 public boolean isActivated() {
123 public void setActivated(boolean isActivated) {
124 this.isActivated = isActivated;
127 public VirtualControlLoopEvent getOnsetEvent() {
131 public VirtualControlLoopEvent getAbatementEvent() {
132 return this.abatement;
135 public ControlLoopProcessor getProcessor() {
136 return this.processor;
139 public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) {
140 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
143 // This method should ONLY be called ONCE
145 if (this.isActivated) {
146 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
149 // Syntax check the event
151 checkEventSyntax(event);
154 // At this point we are good to go with this event
159 notification.notification = ControlLoopNotificationType.ACTIVE;
161 // Set ourselves as active
163 this.isActivated = true;
164 } catch (ControlLoopException e) {
165 logger.error("{}: activate threw: ",this, e);
166 notification.notification = ControlLoopNotificationType.REJECTED;
167 notification.message = e.getMessage();
174 public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) {
175 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
178 // This method should ONLY be called ONCE
180 if (this.isActivated) {
181 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
184 // Syntax check the event
186 checkEventSyntax(event);
191 if (yamlSpecification == null || yamlSpecification.length() < 1) {
192 throw new ControlLoopException("yaml specification is null or 0 length");
194 String decodedYaml = null;
196 decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8");
197 if (decodedYaml != null && decodedYaml.length() > 0) {
198 yamlSpecification = decodedYaml;
200 } catch (UnsupportedEncodingException e) {
201 logger.error("{}: activate threw: ",this, e);
204 // Parse the YAML specification
206 this.processor = new ControlLoopProcessor(yamlSpecification);
209 // At this point we are good to go with this event
216 notification.notification = ControlLoopNotificationType.ACTIVE;
218 // Set ourselves as active
220 this.isActivated = true;
221 } catch (ControlLoopException e) {
222 logger.error("{}: activate threw: ",this, e);
223 notification.notification = ControlLoopNotificationType.REJECTED;
224 notification.message = e.getMessage();
229 public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException {
231 // Check if they activated us
233 if (this.isActivated == false) {
234 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
237 // Make sure we are expecting this call.
239 if (this.onset == null) {
240 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
243 // Ok, start creating the notification
245 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
247 // Check if the overall control loop has timed out
249 if (this.isControlLoopTimedOut()) {
251 // Yes we have timed out
253 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
254 notification.message = "Control Loop timed out";
255 notification.history.addAll(this.controlLoopHistory);
259 // Check if the current policy is Final
261 FinalResult result = this.processor.checkIsCurrentPolicyFinal();
262 if (result == null) {
264 // we are not at a final result
270 case FINAL_FAILURE_EXCEPTION:
271 notification.message = "Exception in processing closed loop";
273 case FINAL_FAILURE_RETRIES:
274 case FINAL_FAILURE_TIMEOUT:
275 case FINAL_FAILURE_GUARD:
276 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
279 notification.notification = ControlLoopNotificationType.FINAL_OPENLOOP;
282 notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;
288 // Be sure to add all the history
290 notification.history.addAll(this.controlLoopHistory);
294 public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AAIException {
296 // Check if they activated us
298 if (this.isActivated == false) {
299 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
302 // Make sure we are expecting this call.
304 if (this.onset == null) {
305 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
308 // Is there a current operation?
310 if (this.currentOperation != null) {
312 // Throw an exception, or simply return the current operation?
314 throw new ControlLoopException("Already working an Operation, do not call this method.");
317 // Ensure we are not FINAL
319 VirtualControlLoopNotification notification = this.isControlLoopFinal();
320 if (notification != null) {
322 // This is weird, we require them to call the isControlLoopFinal() method first
324 // We should really abstract this and avoid throwing an exception, because it really
325 // isn't an exception.
327 throw new ControlLoopException("Control Loop is in FINAL state, do not call this method.");
330 // Not final so get the policy that needs to be worked on.
332 Policy policy = this.processor.getCurrentPolicy();
333 if (policy == null) {
334 throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy.");
337 // And setup an operation
339 this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this);
343 return this.currentOperation;
346 public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException {
348 // Verify we have a current operation
350 if (this.currentOperation != null) {
352 // Validate they are finishing the current operation
353 // PLD - this is simply comparing the policy. Do we want to equals the whole object?
355 if (this.currentOperation.policy.equals(operation.policy)) {
356 logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(), this.currentOperation.getOperationResult());
360 this.controlLoopHistory.addAll(this.currentOperation.getHistory());
362 // Move to the next Policy
364 this.processor.nextPolicyForResult(this.currentOperation.getOperationResult());
366 // Just null this out
368 this.currentOperation = null;
370 // TODO: Release our lock
374 logger.debug("Cannot finish current operation {} does not match given operation {}", this.currentOperation.policy, operation.policy);
377 throw new ControlLoopException("No operation to finish.");
380 public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException {
384 if (this.currentOperation == null) {
385 throw new ControlLoopException("Do not have a current operation.");
388 // Have we acquired it already?
390 if (this.targetLock != null) {
392 // TODO: Make sure the current lock is for the same target.
393 // Currently, it should be. But in the future it may not.
395 return new LockResult<GuardResult, TargetLock>(GuardResult.LOCK_ACQUIRED, this.targetLock);
400 LockResult<GuardResult, TargetLock> lockResult = PolicyGuard.lockTarget(
401 this.currentOperation.policy.getTarget().getType(),
402 this.currentOperation.getTargetEntity(),
403 this.onset.requestID,
408 if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) {
410 // Yes, let's save it
412 this.targetLock = lockResult.getB();
418 public synchronized TargetLock unlockCurrentOperation() {
419 if (this.targetLock == null) {
422 if (PolicyGuard.unlockTarget(this.targetLock) == true) {
423 TargetLock returnLock = this.targetLock;
424 this.targetLock = null;
430 public enum NEW_EVENT_STATUS {
434 SUBSEQUENT_ABATEMENT,
439 public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) throws AAIException {
441 this.checkEventSyntax(event);
442 if (event.closedLoopEventStatus == ControlLoopEventStatus.ONSET) {
444 // Check if this is our original ONSET
446 if (event.equals(this.onset)) {
448 // Query A&AI if needed
455 return NEW_EVENT_STATUS.FIRST_ONSET;
458 // Log that we got an onset
461 return NEW_EVENT_STATUS.SUBSEQUENT_ONSET;
462 } else if (event.closedLoopEventStatus == ControlLoopEventStatus.ABATED) {
464 // Have we already got an abatement?
466 if (this.abatement == null) {
470 this.abatement = event;
472 // Keep track that we received another
474 this.numAbatements++;
478 return NEW_EVENT_STATUS.FIRST_ABATEMENT;
481 // Keep track that we received another
483 this.numAbatements++;
487 return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT;
490 return NEW_EVENT_STATUS.SYNTAX_ERROR;
492 } catch (ControlLoopException e) {
493 logger.error("{}: onNewEvent threw: ",this, e);
494 return NEW_EVENT_STATUS.SYNTAX_ERROR;
498 public VirtualControlLoopNotification setControlLoopTimedOut() {
499 this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT;
500 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
501 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
502 notification.message = "Control Loop timed out";
503 notification.history.addAll(this.controlLoopHistory);
507 public boolean isControlLoopTimedOut() {
508 return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT);
511 public int getControlLoopTimeout(Integer defaultTimeout) {
512 if (this.processor != null && this.processor.getControlLoop() != null) {
513 return this.processor.getControlLoop().getTimeout();
515 if (defaultTimeout != null) {
516 return defaultTimeout;
521 public AAIGETVnfResponse getVnfResponse() {
525 public AAIGETVserverResponse getVserverResponse() {
526 return vserverResponse;
529 public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
530 if (event.closedLoopEventStatus == null ||
531 (event.closedLoopEventStatus != ControlLoopEventStatus.ONSET &&
532 event.closedLoopEventStatus != ControlLoopEventStatus.ABATED)) {
533 throw new ControlLoopException("Invalid value in closedLoopEventStatus");
535 if (event.closedLoopControlName == null || event.closedLoopControlName.length() < 1) {
536 throw new ControlLoopException("No control loop name");
538 if (event.requestID == null) {
539 throw new ControlLoopException("No request ID");
541 if (event.closedLoopEventStatus == ControlLoopEventStatus.ABATED) {
544 if (event.target == null || event.target.length() < 1) {
545 throw new ControlLoopException("No target field");
546 } else if (! "VM_NAME".equalsIgnoreCase(event.target) &&
547 ! "VNF_NAME".equalsIgnoreCase(event.target) &&
548 ! "vserver.vserver-name".equalsIgnoreCase(event.target) &&
549 ! "generic-vnf.vnf-id".equalsIgnoreCase(event.target) &&
550 ! "generic-vnf.vnf-name".equalsIgnoreCase(event.target) ) {
551 throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME");
553 if (event.AAI == null) {
554 throw new ControlLoopException("AAI is null");
556 if (event.AAI.get("generic-vnf.vnf-id") == null && event.AAI.get("vserver.vserver-name") == null &&
557 event.AAI.get("generic-vnf.vnf-name") == null) {
558 throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
562 public void queryAai(VirtualControlLoopEvent event) throws AAIException {
563 if (event.AAI.get("vserver.is-closed-loop-disabled") == null &&
564 event.AAI.get("generic-vnf.is-closed-loop-disabled") == null) {
566 if (event.AAI.get("generic-vnf.vnf-id") != null) {
567 vnfResponse = getAAIVnfInfo(event);
568 if (vnfResponse == null) {
569 throw new AAIException("AAI Response is null (query by vnf-id)");
571 if (vnfResponse.requestError != null) {
572 throw new AAIException("AAI Responded with a request error (query by vnf-id)");
574 if (isClosedLoopDisabled(vnfResponse) == true) {
575 throw new AAIException("is-closed-loop-disabled is set to true");
577 } else if (event.AAI.get("generic-vnf.vnf-name") != null) {
578 vnfResponse = getAAIVnfInfo(event);
579 if (vnfResponse == null) {
580 throw new AAIException("AAI Response is null (query by vnf-name)");
582 if (vnfResponse.requestError != null) {
583 throw new AAIException("AAI Responded with a request error (query by vnf-name)");
585 if (isClosedLoopDisabled(vnfResponse) == true) {
586 throw new AAIException("is-closed-loop-disabled is set to true");
588 } else if (event.AAI.get("vserver.vserver-name") != null) {
589 vserverResponse = getAAIVserverInfo(event);
590 if (vserverResponse == null) {
591 throw new AAIException("AAI Response is null (query by vserver-name)");
593 if (vserverResponse.requestError != null) {
594 throw new AAIException("AAI responded with a request error (query by vserver-name)");
596 if (isClosedLoopDisabled(vserverResponse) == true) {
597 throw new AAIException("is-closed-loop-disabled is set to true");
600 } catch (Exception e) {
601 logger.error("Exception from getAAIInfo: ", e);
602 throw new AAIException("Exception from getAAIInfo: " + e.toString());
604 } else if (isClosedLoopDisabled(event)) {
605 throw new AAIException("is-closed-loop-disabled is set to true");
609 public static boolean isClosedLoopDisabled(AAIGETVnfResponse aaiResponse) {
610 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
611 String value = aaiResponse.isClosedLoopDisabled;
612 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
613 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
621 public static boolean isClosedLoopDisabled(AAIGETVserverResponse aaiResponse) {
622 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
623 String value = aaiResponse.isClosedLoopDisabled;
624 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
625 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
633 public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
634 if ("true".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
635 "T".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
636 "yes".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
637 "Y".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled"))) {
640 else if ("true".equalsIgnoreCase(event.AAI.get("generic-vnf.is-closed-loop-disabled")) ||
641 "T".equalsIgnoreCase(event.AAI.get("generic-vnf.is-closed-loop-disabled")) ||
642 "yes".equalsIgnoreCase(event.AAI.get("generic-vnf.is-closed-loop-disabled")) ||
643 "Y".equalsIgnoreCase(event.AAI.get("generic-vnf.is-closed-loop-disabled"))) {
649 public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException {
650 UUID requestID = event.requestID;
651 AAIGETVserverResponse response = null;
652 String vserverName = event.AAI.get("vserver.vserver-name");
655 if (vserverName != null) {
656 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
657 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username");
658 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
659 String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name=";
660 String url = aaiHostURL + aaiGetQueryByVserver;
661 logger.info("url: " + url);
662 response = AAIManager.getQueryByVserverName(url, aaiUser, aaiPassword, requestID, vserverName);
664 } catch (Exception e) {
665 logger.error("getAAIVserverInfo exception: ", e);
666 throw new ControlLoopException("Exception in getAAIVserverInfo: ", e);
672 public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException {
673 UUID requestID = event.requestID;
674 AAIGETVnfResponse response = null;
675 String vnfName = event.AAI.get("generic-vnf.vnf-name");
676 String vnfID = event.AAI.get("generic-vnf.vnf-id");
678 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
679 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username");
680 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
683 if (vnfName != null) {
684 String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=";
685 String url = aaiHostURL + aaiGetQueryByVnfName;
686 logger.info("url: " + url);
687 response = AAIManager.getQueryByVnfName(url, aaiUser, aaiPassword, requestID, vnfName);
688 } else if (vnfID != null) {
689 String aaiGetQueryByVnfID = "/aai/v11/network/generic-vnfs/generic-vnf/";
690 String url = aaiHostURL + aaiGetQueryByVnfID;
691 logger.info("url: " + url);
692 response = AAIManager.getQueryByVnfID(url, aaiUser, aaiPassword, requestID, vnfID);
694 } catch (Exception e) {
695 logger.error("getAAIVnfInfo exception: ", e);
696 throw new ControlLoopException("Exception in getAAIVnfInfo: ", e);
703 public boolean isActive() {
709 public boolean releaseLock() {
715 public String toString() {
716 return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestID=" + requestID
717 + ", processor=" + processor + ", onset=" + (onset != null ? onset.requestID : "null") + ", numOnsets=" + numOnsets + ", numAbatements="
718 + numAbatements + ", isActivated="
719 + isActivated + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]";