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.controlloop.ControlLoopEventStatus;
35 import org.onap.policy.controlloop.ControlLoopException;
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.policy.FinalResult;
41 import org.onap.policy.controlloop.policy.Policy;
42 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
43 import org.onap.policy.guard.GuardResult;
44 import org.onap.policy.guard.LockCallback;
45 import org.onap.policy.guard.PolicyGuard;
46 import org.onap.policy.guard.PolicyGuard.LockResult;
47 import org.onap.policy.guard.TargetLock;
48 import org.onap.policy.drools.system.PolicyEngine;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class ControlLoopEventManager implements LockCallback, Serializable {
57 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class);
59 private static final long serialVersionUID = -1216568161322872641L;
60 public final String closedLoopControlName;
61 public final UUID requestID;
63 private String controlLoopResult;
64 private transient ControlLoopProcessor processor = null;
65 private VirtualControlLoopEvent onset;
66 private Integer numOnsets = 0;
67 private Integer numAbatements = 0;
68 private VirtualControlLoopEvent abatement;
69 private FinalResult controlLoopTimedOut = null;
71 private boolean isActivated = false;
72 private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
73 private ControlLoopOperationManager currentOperation = null;
74 private transient TargetLock targetLock = null;
75 private static AAIGETVnfResponse vnfResponse = null;
76 private static AAIGETVserverResponse vserverResponse = null;
77 private static String aaiHostURL;
78 private static String aaiUser;
79 private static String aaiPassword;
80 private static String aaiGetQueryByVserver;
81 private static String aaiGetQueryByVnfID;
82 private static String aaiGetQueryByVnfName;
84 private static Collection<String> requiredAAIKeys = new ArrayList<>();
86 requiredAAIKeys.add("AICVServerSelfLink");
87 requiredAAIKeys.add("AICIdentity");
88 requiredAAIKeys.add("is_closed_loop_disabled");
89 requiredAAIKeys.add("VM_NAME");
92 public ControlLoopEventManager(String closedLoopControlName, UUID requestID) {
93 this.closedLoopControlName = closedLoopControlName;
94 this.requestID = requestID;
97 public String getControlLoopResult() {
98 return controlLoopResult;
101 public void setControlLoopResult(String controlLoopResult) {
102 this.controlLoopResult = controlLoopResult;
105 public Integer getNumOnsets() {
109 public void setNumOnsets(Integer numOnsets) {
110 this.numOnsets = numOnsets;
113 public Integer getNumAbatements() {
114 return numAbatements;
117 public void setNumAbatements(Integer numAbatements) {
118 this.numAbatements = numAbatements;
121 public boolean isActivated() {
125 public void setActivated(boolean isActivated) {
126 this.isActivated = isActivated;
129 public VirtualControlLoopEvent getOnsetEvent() {
133 public VirtualControlLoopEvent getAbatementEvent() {
134 return this.abatement;
137 public ControlLoopProcessor getProcessor() {
138 return this.processor;
141 public VirtualControlLoopNotification activate(VirtualControlLoopEvent event) {
142 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
145 // This method should ONLY be called ONCE
147 if (this.isActivated) {
148 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
151 // Syntax check the event
153 checkEventSyntax(event);
155 // At this point we are good to go with this event
160 notification.notification = ControlLoopNotificationType.ACTIVE;
162 // Set ourselves as active
164 this.isActivated = true;
165 } catch (ControlLoopException e) {
166 logger.error("{}: activate threw: ",this, e);
167 notification.notification = ControlLoopNotificationType.REJECTED;
168 notification.message = e.getMessage();
175 public VirtualControlLoopNotification activate(String yamlSpecification, VirtualControlLoopEvent event) {
176 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(event);
179 // This method should ONLY be called ONCE
181 if (this.isActivated) {
182 throw new ControlLoopException("ControlLoopEventManager has already been activated.");
185 // Syntax check the event
187 checkEventSyntax(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
272 case FINAL_FAILURE_EXCEPTION:
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 {
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.getTargetInstance(this.currentOperation.policy),
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) {
441 ControlLoopEventManager.checkEventSyntax(event);
442 if (event.closedLoopEventStatus == ControlLoopEventStatus.ONSET) {
444 // Check if this is our original ONSET
446 if (event.equals(this.onset)) {
450 return NEW_EVENT_STATUS.FIRST_ONSET;
453 // Log that we got an onset
456 return NEW_EVENT_STATUS.SUBSEQUENT_ONSET;
457 } else if (event.closedLoopEventStatus == ControlLoopEventStatus.ABATED) {
459 // Have we already got an abatement?
461 if (this.abatement == null) {
465 this.abatement = event;
467 // Keep track that we received another
469 this.numAbatements++;
473 return NEW_EVENT_STATUS.FIRST_ABATEMENT;
476 // Keep track that we received another
478 this.numAbatements++;
482 return NEW_EVENT_STATUS.SUBSEQUENT_ABATEMENT;
485 return NEW_EVENT_STATUS.SYNTAX_ERROR;
487 } catch (ControlLoopException e) {
488 logger.error("{}: onNewEvent threw: ",this, e);
489 return NEW_EVENT_STATUS.SYNTAX_ERROR;
493 public VirtualControlLoopNotification setControlLoopTimedOut() {
494 this.controlLoopTimedOut = FinalResult.FINAL_FAILURE_TIMEOUT;
495 VirtualControlLoopNotification notification = new VirtualControlLoopNotification(this.onset);
496 notification.notification = ControlLoopNotificationType.FINAL_FAILURE;
497 notification.message = "Control Loop timed out";
498 notification.history.addAll(this.controlLoopHistory);
502 public boolean isControlLoopTimedOut() {
503 return (this.controlLoopTimedOut == FinalResult.FINAL_FAILURE_TIMEOUT);
506 public int getControlLoopTimeout(Integer defaultTimeout) {
507 if (this.processor != null && this.processor.getControlLoop() != null) {
508 return this.processor.getControlLoop().getTimeout();
510 if (defaultTimeout != null) {
511 return defaultTimeout;
516 public AAIGETVnfResponse getVnfResponse() {
520 public AAIGETVserverResponse getVserverResponse() {
521 return vserverResponse;
524 public static void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
525 if (event.closedLoopEventStatus == null ||
526 (event.closedLoopEventStatus != ControlLoopEventStatus.ONSET &&
527 event.closedLoopEventStatus != ControlLoopEventStatus.ABATED)) {
528 throw new ControlLoopException("Invalid value in closedLoopEventStatus");
530 if (event.closedLoopControlName == null || event.closedLoopControlName.length() < 1) {
531 throw new ControlLoopException("No control loop name");
533 if (event.requestID == null) {
534 throw new ControlLoopException("No request ID");
536 if (event.AAI == null) {
537 throw new ControlLoopException("AAI is null");
539 if (event.AAI.get("generic-vnf.vnf-id") == null && event.AAI.get("vserver.vserver-name") == null &&
540 event.AAI.get("generic-vnf.vnf-name") == null) {
541 throw new ControlLoopException("generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
543 if (event.AAI.get("vserver.is-closed-loop-disabled") == null) {
545 if (event.AAI.get("generic-vnf.vnf-id") != null) {
546 vnfResponse = getAAIVnfInfo(event);
547 if (vnfResponse == null) {
548 throw new ControlLoopException("AAI Response is null (query by vnf-id)");
550 if (isClosedLoopDisabled(vnfResponse) == true) {
551 throw new ControlLoopException("is-closed-loop-disabled is set to true");
553 } else if (event.AAI.get("generic-vnf.vnf-name") != null) {
554 vnfResponse = getAAIVnfInfo(event);
555 if (vnfResponse == null) {
556 throw new ControlLoopException("AAI Response is null (query by vnf-name)");
558 if (isClosedLoopDisabled(vnfResponse) == true) {
559 throw new ControlLoopException("is-closed-loop-disabled is set to true");
561 } else if (event.AAI.get("vserver.vserver-name") != null) {
562 vserverResponse = getAAIVserverInfo(event);
563 if (vserverResponse == null) {
564 throw new ControlLoopException("AAI Response is null (query by vserver-name)");
566 if (isClosedLoopDisabled(vserverResponse) == true) {
567 throw new ControlLoopException("is-closed-loop-disabled is set to true");
570 } catch (Exception e) {
571 logger.error("Exception from getAAIInfo: ", e);
572 throw new ControlLoopException("Exception from getAAIInfo: " + e.toString());
574 } else if (isClosedLoopDisabled(event)) {
575 throw new ControlLoopException("is-closed-loop-disabled is set to true");
577 if (event.target == null || event.target.length() < 1) {
578 throw new ControlLoopException("No target field");
580 if (! event.target.equalsIgnoreCase("VM_NAME") &&
581 ! event.target.equalsIgnoreCase("VNF_NAME") &&
582 ! event.target.equalsIgnoreCase("vserver.vserver-name") &&
583 ! event.target.equalsIgnoreCase("generic-vnf.vnf-id") &&
584 ! event.target.equalsIgnoreCase("generic-vnf.vnf-name") ) {
585 throw new ControlLoopException("target field invalid - expecting VM_NAME or VNF_NAME");
590 public static boolean isClosedLoopDisabled(AAIGETVnfResponse aaiResponse) {
591 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
592 String value = aaiResponse.isClosedLoopDisabled;
593 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
594 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
602 public static boolean isClosedLoopDisabled(AAIGETVserverResponse aaiResponse) {
603 if (aaiResponse != null && aaiResponse.isClosedLoopDisabled != null) {
604 String value = aaiResponse.isClosedLoopDisabled;
605 if ("true".equalsIgnoreCase(value) || "T".equalsIgnoreCase(value) ||
606 "yes".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value)) {
614 public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
615 if ("true".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
616 "T".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
617 "yes".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled")) ||
618 "Y".equalsIgnoreCase(event.AAI.get("vserver.is-closed-loop-disabled"))) {
624 public static AAIGETVserverResponse getAAIVserverInfo(VirtualControlLoopEvent event) throws ControlLoopException {
625 UUID requestID = event.requestID;
626 AAIGETVserverResponse response = null;
627 String vserverName = event.AAI.get("vserver.vserver-name");
630 if (vserverName != null) {
631 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
632 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.user");
633 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
634 String aaiGetQueryByVserver = "/aai/v11/nodes/vservers?vserver-name=";
635 String url = aaiHostURL + aaiGetQueryByVserver;
636 logger.info("url: " + url);
637 response = AAIManager.getQueryByVserverName(url, aaiUser, aaiPassword, requestID, vserverName);
639 } catch (Exception e) {
640 logger.error("getAAIVserverInfo exception: ", e);
641 throw new ControlLoopException("Exception in getAAIVserverInfo: ", e);
647 public static AAIGETVnfResponse getAAIVnfInfo(VirtualControlLoopEvent event) throws ControlLoopException {
648 UUID requestID = event.requestID;
649 AAIGETVnfResponse response = null;
650 String vnfName = event.AAI.get("generic-vnf.vnf-name");
651 String vnfID = event.AAI.get("generic-vnf.vnf-id");
654 if (vnfName != null) {
655 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
656 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.user");
657 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
658 String aaiGetQueryByVnfName = "/aai/v11/network/generic-vnfs/generic-vnf?vnf-name=";
659 String url = aaiHostURL + aaiGetQueryByVnfName;
660 logger.info("url: " + url);
661 response = AAIManager.getQueryByVnfName(url, aaiUser, aaiPassword, requestID, vnfName);
662 } else if (vnfID != null) {
663 aaiHostURL = PolicyEngine.manager.getEnvironmentProperty("aai.url");
664 aaiUser = PolicyEngine.manager.getEnvironmentProperty("aai.user");
665 aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
666 String aaiGetQueryByVnfID = "/aai/v11/network/generic-vnfs/generic-vnf/";
667 String url = aaiHostURL + aaiGetQueryByVnfID;
668 logger.info("url: " + url);
669 response = AAIManager.getQueryByVnfID(url, aaiUser, aaiPassword, requestID, vnfID);
671 } catch (Exception e) {
672 logger.error("getAAIVnfInfo exception: ", e);
673 throw new ControlLoopException("Exception in getAAIVnfInfo: ", e);
680 public boolean isActive() {
686 public boolean releaseLock() {
691 public String getTargetInstance(Policy policy) {
692 if (policy.getTarget() != null) {
693 if (policy.getTarget().getType() != null) {
694 switch(policy.getTarget().getType()) {
699 if (this.onset.target.equalsIgnoreCase("vserver.vserver-name")) {
700 return this.onset.AAI.get("vserver.vserver-name");
702 else if (this.onset.target.equalsIgnoreCase("generic-vnf.vnf-id")) {
703 return this.onset.AAI.get("generic-vnf.vnf-id");
705 else if (this.onset.target.equalsIgnoreCase("generic-vnf.vnf-name")) {
706 return this.onset.AAI.get("generic-vnf.vnf-name");
718 public String toString() {
719 return "ControlLoopEventManager [closedLoopControlName=" + closedLoopControlName + ", requestID=" + requestID
720 + ", processor=" + processor + ", onset=" + (onset != null ? onset.requestID : "null") + ", numOnsets=" + numOnsets + ", numAbatements="
721 + numAbatements + ", isActivated="
722 + isActivated + ", currentOperation=" + currentOperation + ", targetLock=" + targetLock + "]";