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);
152 checkEventAAISyntax(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);
187 checkEventAAISyntax(event);
192 if (yamlSpecification == null || yamlSpecification.length() < 1) {
193 throw new ControlLoopException("yaml specification is null or 0 length");
195 String decodedYaml = null;
197 decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8");
198 if (decodedYaml != null && decodedYaml.length() > 0) {
199 yamlSpecification = decodedYaml;
201 } catch (UnsupportedEncodingException e) {
202 logger.error("{}: activate threw: ",this, e);
205 // Parse the YAML specification
207 this.processor = new ControlLoopProcessor(yamlSpecification);
210 // At this point we are good to go with this event
217 notification.notification = ControlLoopNotificationType.ACTIVE;
219 // Set ourselves as active
221 this.isActivated = true;
222 } catch (ControlLoopException e) {
223 logger.error("{}: activate threw: ",this, e);
224 notification.notification = ControlLoopNotificationType.REJECTED;
225 notification.message = e.getMessage();
230 public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException {
232 // Check if they activated us
234 if (this.isActivated == false) {
235 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
238 // Make sure we are expecting this call.
240 if (this.onset == null) {
241 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
244 // Ok, start creating the notification
246 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
248 // Check if the overall control loop has timed out
250 if (this.isControlLoopTimedOut()) {
252 // Yes we have timed out
254 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
255 notification.message = "Control Loop timed out";
256 notification.history.addAll(this.controlLoopHistory);
260 // Check if the current policy is Final
262 FinalResult result = this.processor.checkIsCurrentPolicyFinal();
263 if (result == null) {
265 // we are not at a final result
271 case FINAL_FAILURE_EXCEPTION:
272 notification.message = "Exception in processing closed loop";
274 case FINAL_FAILURE_RETRIES:
275 case FINAL_FAILURE_TIMEOUT:
276 case FINAL_FAILURE_GUARD:
277 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
280 notification.notification = ControlLoopNotificationType.FINAL_OPENLOOP;
283 notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;
289 // Be sure to add all the history
291 notification.history.addAll(this.controlLoopHistory);
295 public ControlLoopOperationManager processControlLoop() throws ControlLoopException, AAIException {
297 // Check if they activated us
299 if (this.isActivated == false) {
300 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
303 // Make sure we are expecting this call.
305 if (this.onset == null) {
306 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
309 // Is there a current operation?
311 if (this.currentOperation != null) {
313 // Throw an exception, or simply return the current operation?
315 throw new ControlLoopException("Already working an Operation, do not call this method.");
318 // Ensure we are not FINAL
320 VirtualControlLoopNotification notification = this.isControlLoopFinal();
321 if (notification != null) {
323 // This is weird, we require them to call the isControlLoopFinal() method first
325 // We should really abstract this and avoid throwing an exception, because it really
326 // isn't an exception.
328 throw new ControlLoopException("Control Loop is in FINAL state, do not call this method.");
331 // Not final so get the policy that needs to be worked on.
333 Policy policy = this.processor.getCurrentPolicy();
334 if (policy == null) {
335 throw new ControlLoopException("ControlLoopEventManager: processor came upon null Policy.");
338 // And setup an operation
340 this.currentOperation = new ControlLoopOperationManager(this.onset, policy, this);
344 return this.currentOperation;
347 public void finishOperation(ControlLoopOperationManager operation) throws ControlLoopException {
349 // Verify we have a current operation
351 if (this.currentOperation != null) {
353 // Validate they are finishing the current operation
354 // PLD - this is simply comparing the policy. Do we want to equals the whole object?
356 if (this.currentOperation.policy.equals(operation.policy)) {
357 logger.debug("Finishing {} result is {}", this.currentOperation.policy.getRecipe(), this.currentOperation.getOperationResult());
361 this.controlLoopHistory.addAll(this.currentOperation.getHistory());
363 // Move to the next Policy
365 this.processor.nextPolicyForResult(this.currentOperation.getOperationResult());
367 // Just null this out
369 this.currentOperation = null;
371 // TODO: Release our lock
375 logger.debug("Cannot finish current operation {} does not match given operation {}", this.currentOperation.policy, operation.policy);
378 throw new ControlLoopException("No operation to finish.");
381 public synchronized LockResult<GuardResult, TargetLock> lockCurrentOperation() throws ControlLoopException {
385 if (this.currentOperation == null) {
386 throw new ControlLoopException("Do not have a current operation.");
389 // Have we acquired it already?
391 if (this.targetLock != null) {
393 // TODO: Make sure the current lock is for the same target.
394 // Currently, it should be. But in the future it may not.
396 return new LockResult<GuardResult, TargetLock>(GuardResult.LOCK_ACQUIRED, this.targetLock);
401 LockResult<GuardResult, TargetLock> lockResult = PolicyGuard.lockTarget(
402 this.currentOperation.policy.getTarget().getType(),
403 this.currentOperation.getTargetEntity(),
404 this.onset.requestID,
409 if (lockResult.getA().equals(GuardResult.LOCK_ACQUIRED)) {
411 // Yes, let's save it
413 this.targetLock = lockResult.getB();
419 public synchronized TargetLock unlockCurrentOperation() {
420 if (this.targetLock == null) {
423 if (PolicyGuard.unlockTarget(this.targetLock) == true) {
424 TargetLock returnLock = this.targetLock;
425 this.targetLock = null;
431 public enum NEW_EVENT_STATUS {
435 SUBSEQUENT_ABATEMENT,
440 public NEW_EVENT_STATUS onNewEvent(VirtualControlLoopEvent event) {
442 this.checkEventSyntax(event);
443 if (event.closedLoopEventStatus == ControlLoopEventStatus.ONSET) {
445 // Check if this is our original ONSET
447 if (event.equals(this.onset)) {
451 return NEW_EVENT_STATUS.FIRST_ONSET;
454 // Log that we got an onset
457 return NEW_EVENT_STATUS.SUBSEQUENT_ONSET;
458 } else if (event.closedLoopEventStatus == ControlLoopEventStatus.ABATED) {
460 // Have we already got an abatement?
462 if (this.abatement == null) {
466 this.abatement = event;
468 // Keep track that we received another
470 this.numAbatements++;
474 return NEW_EVENT_STATUS.FIRST_ABATEMENT;
477 // Keep track that we received another
479 this.numAbatements++;
483 return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT;
486 return NEW_EVENT_STATUS.SYNTAX_ERROR;
488 } catch (ControlLoopException e) {
489 logger.error("{}: onNewEvent threw: ",this, e);
490 return NEW_EVENT_STATUS.SYNTAX_ERROR;
494 public VirtualControlLoopNotification setControlLoopTimedOut() {
495 this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT;
496 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
497 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
498 notification.message = "Control Loop timed out";
499 notification.history.addAll(this.controlLoopHistory);
503 public boolean isControlLoopTimedOut() {
504 return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT);
507 public int getControlLoopTimeout(Integer defaultTimeout) {
508 if (this.processor != null && this.processor.getControlLoop() != null) {
509 return this.processor.getControlLoop().getTimeout();
511 if (defaultTimeout != null) {
512 return defaultTimeout;
517 public AAIGETVnfResponse getVnfResponse() {
521 public AAIGETVserverResponse getVserverResponse() {
522 return vserverResponse;
525 public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
526 if (event.closedLoopEventStatus == null ||
527 (event.closedLoopEventStatus != ControlLoopEventStatus.ONSET &&
528 event.closedLoopEventStatus != ControlLoopEventStatus.ABATED)) {
529 throw new ControlLoopException("Invalid value in closedLoopEventStatus");
531 if (event.closedLoopControlName == null || event.closedLoopControlName.length() < 1) {
532 throw new ControlLoopException("No control loop name");
534 if (event.requestID == null) {
535 throw new ControlLoopException("No request ID");
537 if (event.closedLoopEventStatus == ControlLoopEventStatus.ABATED) {
540 if (event.target == null || event.target.length() < 1) {
541 throw new ControlLoopException("No target field");
542 } else if (! "VM_NAME".equalsIgnoreCase(event.target) &&
543 ! "VNF_NAME".equalsIgnoreCase(event.target) &&
544 ! "vserver.vserver-name".equalsIgnoreCase(event.target) &&
545 ! "generic-vnf.vnf-id".equalsIgnoreCase(event.target) &&
546 ! "generic-vnf.vnf-name".equalsIgnoreCase(event.target) ) {
547 throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME");
551 public void checkEventAAISyntax(VirtualControlLoopEvent event) throws ControlLoopException {
552 if (event.AAI == null) {
553 throw new ControlLoopException("AAI is null");
555 if (event.AAI.get("generic-vnf.vnf-id") == null && event.AAI.get("vserver.vserver-name") == null &&
556 event.AAI.get("generic-vnf.vnf-name") == null) {
557 throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
559 if (event.AAI.get("vserver.is-closed-loop-disabled") == null) {
561 if (event.AAI.get("generic-vnf.vnf-id") != null) {
562 vnfResponse = getAAIVnfInfo(event);
563 if (vnfResponse == null) {
564 throw new ControlLoopException("AAI Response is null (query by vnf-id)");
566 if (vnfResponse.requestError != null) {
567 throw new ControlLoopException("AAI Responded with a request error (query by vnf-id)");
569 if (isClosedLoopDisabled(vnfResponse) == true) {
570 throw new ControlLoopException("is-closed-loop-disabled is set to true");
572 } else if (event.AAI.get("generic-vnf.vnf-name") != null) {
573 vnfResponse = getAAIVnfInfo(event);
574 if (vnfResponse == null) {
575 throw new ControlLoopException("AAI Response is null (query by vnf-name)");
577 if (vnfResponse.requestError != null) {
578 throw new ControlLoopException("AAI Responded with a request error (query by vnf-name)");
580 if (isClosedLoopDisabled(vnfResponse) == true) {
581 throw new ControlLoopException("is-closed-loop-disabled is set to true");
583 } else if (event.AAI.get("vserver.vserver-name") != null) {
584 vserverResponse = getAAIVserverInfo(event);
585 if (vserverResponse == null) {
586 throw new ControlLoopException("AAI Response is null (query by vserver-name)");
588 if (vserverResponse.requestError != null) {
589 throw new ControlLoopException("AAI responded with a request error (query by vserver-name)");
591 if (isClosedLoopDisabled(vserverResponse) == true) {
592 throw new ControlLoopException("is-closed-loop-disabled is set to true");
595 } catch (Exception e) {
596 logger.error("Exception from getAAIInfo: ", e);
597 throw new ControlLoopException("Exception from getAAIInfo: " + e.toString());
599 } else if (isClosedLoopDisabled(event)) {
600 throw new ControlLoopException("is-closed-loop-disabled is set to true");
604 public static boolean isClosedLoopDisabled(AAIGETVnfResponse aaiResponse) {
605 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
606 String value = aaiResponse.isClosedLoopDisabled;
607 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
608 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
616 public static boolean isClosedLoopDisabled(AAIGETVserverResponse aaiResponse) {
617 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
618 String value = aaiResponse.isClosedLoopDisabled;
619 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
620 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
628 public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
629 if ("true".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
630 "T".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
631 "yes".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
632 "Y".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled"))) {
638 public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException {
639 UUID requestID = event.requestID;
640 AAIGETVserverResponse response = null;
641 String vserverName = event.AAI.get("vserver.vserver-name");
644 if (vserverName != null) {
645 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
646 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username");
647 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
648 String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name=";
649 String url = aaiHostURL + aaiGetQueryByVserver;
650 logger.info("url: " + url);
651 response = AAIManager.getQueryByVserverName(url, aaiUser, aaiPassword, requestID, vserverName);
653 } catch (Exception e) {
654 logger.error("getAAIVserverInfo exception: ", e);
655 throw new ControlLoopException("Exception in getAAIVserverInfo: ", e);
661 public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException {
662 UUID requestID = event.requestID;
663 AAIGETVnfResponse response = null;
664 String vnfName = event.AAI.get("generic-vnf.vnf-name");
665 String vnfID = event.AAI.get("generic-vnf.vnf-id");
667 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
668 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.username");
669 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
672 if (vnfName != null) {
673 String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=";
674 String url = aaiHostURL + aaiGetQueryByVnfName;
675 logger.info("url: " + url);
676 response = AAIManager.getQueryByVnfName(url, aaiUser, aaiPassword, requestID, vnfName);
677 } else if (vnfID != null) {
678 String aaiGetQueryByVnfID = "/aai/v11/network/generic-vnfs/generic-vnf/";
679 String url = aaiHostURL + aaiGetQueryByVnfID;
680 logger.info("url: " + url);
681 response = AAIManager.getQueryByVnfID(url, aaiUser, aaiPassword, requestID, vnfID);
683 } catch (Exception e) {
684 logger.error("getAAIVnfInfo exception: ", e);
685 throw new ControlLoopException("Exception in getAAIVnfInfo: ", e);
692 public boolean isActive() {
698 public boolean releaseLock() {
704 public String toString() {
705 return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestID=" + requestID
706 + ", processor=" + processor + ", onset=" + (onset != null ? onset.requestID : "null") + ", numOnsets=" + numOnsets + ", numAbatements="
707 + numAbatements + ", isActivated="
708 + isActivated + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]";