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.List;
30 import java.util.UUID;
31 import java.util.HashMap;
33 import java.util.Iterator;
35 import org.onap.policy.controlloop.ControlLoopEventStatus;
36 import org.onap.policy.controlloop.ControlLoopNotificationType;
37 import org.onap.policy.controlloop.ControlLoopOperation;
38 import org.onap.policy.controlloop.VirtualControlLoopEvent;
39 import org.onap.policy.controlloop.VirtualControlLoopNotification;
40 import org.onap.policy.controlloop.ControlLoopException;
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.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 import org.onap.policy.aai.AAIManager;
53 import org.onap.policy.aai.AAIGETVserverResponse;
54 import org.onap.policy.aai.AAIGETVnfResponse;
55 import org.onap.policy.aai.RelatedToPropertyItem;
56 import org.onap.policy.aai.RelationshipList;
57 import org.onap.policy.aai.Relationship;
59 public class ControlLoopEventManager implements LockCallback, Serializable {
64 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class);
66 private static final long serialVersionUID = -1216568161322872641L;
67 public final String closedLoopControlName;
68 public final UUID requestID;
70 private String controlLoopResult;
71 private ControlLoopProcessor processor = null;
72 private VirtualControlLoopEvent onset;
73 private Integer numOnsets = 0;
74 private Integer numAbatements = 0;
75 private VirtualControlLoopEvent abatement;
76 private FinalResult controlLoopTimedOut = null;
78 private boolean isActivated = false;
79 private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
80 private ControlLoopOperationManager currentOperation = null;
81 private TargetLock targetLock = null;
82 private static AAIGETVnfResponse vnfResponse = null;
83 private static AAIGETVserverResponse vserverResponse = null;
85 private static Collection<String> requiredAAIKeys = new ArrayList<>();
87 requiredAAIKeys.add("AICVServerSelfLink");
88 requiredAAIKeys.add("AICIdentity");
89 requiredAAIKeys.add("is_closed_loop_disabled");
90 requiredAAIKeys.add("VM_NAME");
93 public ControlLoopEventManager(String closedLoopControlName, UUID requestID) {
94 this.closedLoopControlName = closedLoopControlName;
95 this.requestID = requestID;
98 public String getControlLoopResult() {
99 return controlLoopResult;
102 public void setControlLoopResult(String controlLoopResult) {
103 this.controlLoopResult = controlLoopResult;
106 public Integer getNumOnsets() {
110 public void setNumOnsets(Integer numOnsets) {
111 this.numOnsets = numOnsets;
114 public Integer getNumAbatements() {
115 return numAbatements;
118 public void setNumAbatements(Integer numAbatements) {
119 this.numAbatements = numAbatements;
122 public boolean isActivated() {
126 public void setActivated(boolean isActivated) {
127 this.isActivated = isActivated;
130 public VirtualControlLoopEvent getOnsetEvent() {
134 public VirtualControlLoopEvent getAbatementEvent() {
135 return this.abatement;
138 public ControlLoopProcessor getProcessor() {
139 return this.processor;
142 public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) {
143 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
146 // This method should ONLY be called ONCE
148 if (this.isActivated) {
149 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
152 // Syntax check the event
154 checkEventSyntax(event);
156 // At this point we are good to go with this event
161 notification.notification = ControlLoopNotificationType.ACTIVE;
163 // Set ourselves as active
165 this.isActivated = true;
166 } catch (ControlLoopException e) {
167 logger.error("{}: activate threw: ",this, e);
168 notification.notification = ControlLoopNotificationType.REJECTED;
169 notification.message = e.getMessage();
176 public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) {
177 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
180 // This method should ONLY be called ONCE
182 if (this.isActivated) {
183 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
186 // Syntax check the event
188 checkEventSyntax(event);
193 if (yamlSpecification == null || yamlSpecification.length() < 1) {
194 throw new ControlLoopException("yaml specification is null or 0 length");
196 String decodedYaml = null;
198 decodedYaml = URLDecoder.decode(yamlSpecification, "UTF-8");
199 if (decodedYaml != null && decodedYaml.length() > 0) {
200 yamlSpecification = decodedYaml;
202 } catch (UnsupportedEncodingException e) {
203 logger.error("{}: activate threw: ",this, e);
206 // Parse the YAML specification
208 this.processor = new ControlLoopProcessor(yamlSpecification);
211 // At this point we are good to go with this event
218 notification.notification = ControlLoopNotificationType.ACTIVE;
220 // Set ourselves as active
222 this.isActivated = true;
223 } catch (ControlLoopException e) {
224 logger.error("{}: activate threw: ",this, e);
225 notification.notification = ControlLoopNotificationType.REJECTED;
226 notification.message = e.getMessage();
231 public VirtualControlLoopNotification isControlLoopFinal() throws ControlLoopException {
233 // Check if they activated us
235 if (this.isActivated == false) {
236 throw new ControlLoopException("ControlLoopEventManager MUST be activated first.");
239 // Make sure we are expecting this call.
241 if (this.onset == null) {
242 throw new ControlLoopException("No onset event for ControlLoopEventManager.");
245 // Ok, start creating the notification
247 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
249 // Check if the overall control loop has timed out
251 if (this.isControlLoopTimedOut()) {
253 // Yes we have timed out
255 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
256 notification.message = "Control Loop timed out";
257 notification.history.addAll(this.controlLoopHistory);
261 // Check if the current policy is Final
263 FinalResult result = this.processor.checkIsCurrentPolicyFinal();
264 if (result == null) {
266 // we are not at a final result
273 case FINAL_FAILURE_EXCEPTION:
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 {
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.getTargetInstance(this.currentOperation.policy),
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 ControlLoopEventManager.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 static 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.AAI == null) {
538 throw new ControlLoopException("AAI is null");
540 if (event.AAI.get("generic-vnf.vnf-id") == null && event.AAI.get("vserver.vserver-name") == null &&
541 event.AAI.get("generic-vnf.vnf-name") == null) {
542 throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
544 if (event.AAI.get("vserver.is-closed-loop-disabled") == null) {
546 if (event.AAI.get("generic-vnf.vnf-id") != null) {
547 vnfResponse = getAAIVnfInfo(event);
548 if (vnfResponse != null && isClosedLoopDisabled(vnfResponse) == true) {
549 throw new ControlLoopException("is-closed-loop-disabled is set to true");
551 } else if (event.AAI.get("generic-vnf.vnf-name") != null) {
552 vnfResponse = getAAIVnfInfo(event);
553 if (vnfResponse != null && isClosedLoopDisabled(vnfResponse) == true) {
554 throw new ControlLoopException("is-closed-loop-disabled is set to true");
556 } else if (event.AAI.get("vserver.vserver-name") != null) {
557 vserverResponse = getAAIVserverInfo(event);
558 if (vserverResponse != null && isClosedLoopDisabled(vserverResponse) == true) {
559 throw new ControlLoopException("is-closed-loop-disabled is set to true");
562 } catch (Exception e) {
563 logger.error("Exception from getAAIInfo: ", e);
564 throw new ControlLoopException("Exception from getAAIInfo: " + e.toString());
566 } else if (isClosedLoopDisabled(event)) {
567 throw new ControlLoopException("is-closed-loop-disabled is set to true");
569 if (event.target == null || event.target.length() < 1) {
570 throw new ControlLoopException("No target field");
572 if (! event.target.equalsIgnoreCase("VM_NAME") &&
573 ! event.target.equalsIgnoreCase("VNF_NAME") &&
574 ! event.target.equalsIgnoreCase("vserver.vserver-name") &&
575 ! event.target.equalsIgnoreCase("generic-vnf.vnf-id") &&
576 ! event.target.equalsIgnoreCase("generic-vnf.vnf-name") ) {
577 throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME");
582 public static boolean isClosedLoopDisabled(AAIGETVnfResponse aaiResponse) {
583 RelationshipList relationshipList = new RelationshipList();
584 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
585 String value = aaiResponse.isClosedLoopDisabled;
586 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
587 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
595 public static boolean isClosedLoopDisabled(AAIGETVserverResponse aaiResponse) {
596 RelationshipList relationshipList = new RelationshipList();
597 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
598 String value = aaiResponse.isClosedLoopDisabled;
599 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
600 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
608 public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
609 if ("true".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
610 "T".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
611 "yes".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
612 "Y".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled"))) {
618 public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException {
619 String user = "POLICY";
620 String password = "POLICY";
621 UUID requestID = event.requestID;
622 AAIGETVserverResponse response = null;
623 String vserverName = event.AAI.get("vserver.vserver-name");
626 if (vserverName != null) {
627 AAIManager manager = new AAIManager();
628 String url = "https://aai-ext1.test.att.com:8443/aai/v11/nodes/vservers?vserver-name=";
629 response = manager.getQueryByVserverName(url, user, password, requestID, vserverName);
631 } catch (Exception e) {
632 logger.error("getAAIVserverInfo exception: ", e);
633 throw new ControlLoopException("Exception in getAAIVserverInfo: ", e);
639 public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException {
640 String user = "POLICY";
641 String password = "POLICY";
642 UUID requestID = event.requestID;
643 AAIGETVnfResponse response = null;
644 String vnfName = event.AAI.get("generic-vnf.vnf-name");
645 String vnfID = event.AAI.get("generic-vnf.vnf-id");
648 if (vnfName != null) {
649 AAIManager manager = new AAIManager();
650 String url = "https://aai-ext1.test.att.com:8443/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=";
651 response = manager.getQueryByVnfName(url, user, password, requestID, vnfName);
652 } else if (vnfID != null) {
653 AAIManager manager = new AAIManager();
654 String url = "https://aai-ext1.test.att.com:8443/aai/v11/network/generic-vnfs/generic-vnf/";
655 response = manager.getQueryByVnfID(url, user, password, requestID, vnfID);
657 } catch (Exception e) {
658 logger.error("getAAIVnfInfo exception: ", e);
659 throw new ControlLoopException("Exception in getAAIVnfInfo: ", e);
666 public boolean isActive() {
672 public boolean releaseLock() {
677 public String getTargetInstance(Policy policy) {
678 if (policy.getTarget() != null) {
679 if (policy.getTarget().getType() != null) {
680 switch(policy.getTarget().getType()) {
685 if (this.onset.target.equalsIgnoreCase("vserver.vserver-name")) {
686 return this.onset.AAI.get("vserver.vserver-name");
688 else if (this.onset.target.equalsIgnoreCase("generic-vnf.vnf-id")) {
689 return this.onset.AAI.get("generic-vnf.vnf-id");
691 else if (this.onset.target.equalsIgnoreCase("generic-vnf.vnf-name")) {
692 return this.onset.AAI.get("generic-vnf.vnf-name");
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 + "]";