2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 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 static org.onap.policy.controlloop.ControlLoopTargetType.PNF;
24 import static org.onap.policy.controlloop.ControlLoopTargetType.VM;
25 import static org.onap.policy.controlloop.ControlLoopTargetType.VNF;
27 import java.io.Serializable;
28 import java.util.HashMap;
29 import java.util.LinkedList;
32 import java.util.UUID;
33 import java.util.concurrent.CompletableFuture;
34 import java.util.concurrent.Executor;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.ForkJoinPool;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.atomic.AtomicReference;
39 import java.util.function.Consumer;
40 import java.util.stream.Collectors;
41 import java.util.stream.Stream;
43 import lombok.ToString;
44 import org.apache.commons.lang3.StringUtils;
45 import org.drools.core.WorkingMemory;
46 import org.kie.api.runtime.rule.FactHandle;
47 import org.onap.policy.controlloop.ControlLoopEventStatus;
48 import org.onap.policy.controlloop.ControlLoopException;
49 import org.onap.policy.controlloop.ControlLoopNotificationType;
50 import org.onap.policy.controlloop.ControlLoopOperation;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.VirtualControlLoopNotification;
53 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
54 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
55 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
56 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
57 import org.onap.policy.controlloop.ophistory.OperationHistoryDataManager;
58 import org.onap.policy.controlloop.policy.FinalResult;
59 import org.onap.policy.controlloop.policy.Policy;
60 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
61 import org.onap.policy.drools.core.lock.LockCallback;
62 import org.onap.policy.drools.system.PolicyEngineConstants;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
67 * Manager for a single control loop event. Once this has been created, the event can be
68 * retracted from working memory. Once this has been created, {@link #start()} should be
69 * invoked, and then {@link #nextStep()} should be invoked continually until
70 * {@link #isActive()} returns {@code false}, indicating that all steps have completed.
72 @ToString(onlyExplicitlyIncluded = true)
73 public class ControlLoopEventManager2 implements ManagerContext, Serializable {
74 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager2.class);
75 private static final long serialVersionUID = -1216568161322872641L;
77 private static final String EVENT_MANAGER_SERVICE_CONFIG = "config/event-manager.properties";
78 public static final String PROV_STATUS_ACTIVE = "ACTIVE";
79 private static final String VM_NAME = "VM_NAME";
80 private static final String VNF_NAME = "VNF_NAME";
81 public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
82 public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
83 public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
84 public static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled";
85 public static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled";
86 public static final String PNF_IS_IN_MAINT = "pnf.in-maint";
87 public static final String GENERIC_VNF_PROV_STATUS = "generic-vnf.prov-status";
88 public static final String VSERVER_PROV_STATUS = "vserver.prov-status";
89 public static final String PNF_ID = "pnf.pnf-id";
90 public static final String PNF_NAME = "pnf.pnf-name";
92 private static final Set<String> VALID_TARGETS = Stream
93 .of(VM_NAME, VNF_NAME, VSERVER_VSERVER_NAME, GENERIC_VNF_VNF_ID, GENERIC_VNF_VNF_NAME, PNF_NAME)
94 .map(String::toLowerCase).collect(Collectors.toSet());
96 private static final Set<String> TRUE_VALUES = Set.of("true", "t", "yes", "y");
98 public enum NewEventStatus {
99 FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR
102 // TODO limit the number of policies that may be executed for a single event?
105 * {@code True} if this object was created by this JVM instance, {@code false}
106 * otherwise. This will be {@code false} if this object is reconstituted from a
107 * persistent store or by transfer from another server.
109 private transient boolean createdByThisJvmInstance;
113 public final String closedLoopControlName;
116 private final UUID requestId;
117 private final ControlLoopEventContext context;
119 private int numOnsets = 1;
121 private int numAbatements = 0;
122 private VirtualControlLoopEvent abatement = null;
125 * Time, in milliseconds, when the control loop will time out.
128 private final long endTimeMs;
130 // fields extracted from the ControlLoopParams
132 private final String policyName;
133 private final String policyScope;
134 private final String policyVersion;
136 private final LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
139 * Maps a target entity to its lock.
141 private final transient Map<String, LockData> target2lock = new HashMap<>();
143 private final ControlLoopProcessor processor;
144 private final AtomicReference<ControlLoopOperationManager2> currentOperation = new AtomicReference<>();
146 private FinalResult finalResult = null;
149 private VirtualControlLoopNotification notification;
152 private boolean updated = false;
154 private final transient WorkingMemory workMem;
155 private transient FactHandle factHandle;
159 * Constructs the object.
161 * @param params control loop parameters
162 * @param event event to be managed by this object
163 * @param workMem working memory to update if this changes
164 * @throws ControlLoopException if the event is invalid or if a YAML processor cannot
167 public ControlLoopEventManager2(ControlLoopParams params, VirtualControlLoopEvent event, WorkingMemory workMem)
168 throws ControlLoopException {
170 checkEventSyntax(event);
172 if (isClosedLoopDisabled(event)) {
173 throw new IllegalStateException("is-closed-loop-disabled is set to true on VServer or VNF");
176 if (isProvStatusInactive(event)) {
177 throw new IllegalStateException("prov-status is not ACTIVE on VServer or VNF");
180 this.createdByThisJvmInstance = true;
181 this.closedLoopControlName = params.getClosedLoopControlName();
182 this.requestId = event.getRequestId();
183 this.context = new ControlLoopEventContext(event);
184 this.policyName = params.getPolicyName();
185 this.policyScope = params.getPolicyScope();
186 this.policyVersion = params.getPolicyVersion();
187 this.processor = new ControlLoopProcessor(params.getToscaPolicy());
188 this.workMem = workMem;
189 this.endTimeMs = System.currentTimeMillis() + detmControlLoopTimeoutMs();
193 * Starts the manager.
195 * @throws ControlLoopException if the processor cannot get a policy
197 public void start() throws ControlLoopException {
199 throw new IllegalStateException("manager is no longer active");
202 if ((factHandle = workMem.getFactHandle(this)) == null) {
203 throw new IllegalStateException("manager is not in working memory");
206 if (currentOperation.get() != null) {
207 throw new IllegalStateException("manager already started");
214 * Starts an operation for the current processor policy.
216 * @throws ControlLoopException if the processor cannot get a policy
218 private synchronized void startOperation() throws ControlLoopException {
220 if ((finalResult = processor.checkIsCurrentPolicyFinal()) == null) {
221 // not final - start the next operation
222 currentOperation.set(makeOperationManager(context, processor.getCurrentPolicy()));
223 currentOperation.get().start(endTimeMs - System.currentTimeMillis());
227 logger.info("final={} oper state={} for {}", finalResult, currentOperation.get().getState(), requestId);
229 notification = makeNotification();
230 notification.setHistory(controlLoopHistory);
232 switch (finalResult) {
233 case FINAL_FAILURE_EXCEPTION:
234 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
235 notification.setMessage("Exception in processing closed loop");
238 notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS);
241 notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP);
245 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
251 * Starts the next step, whatever that may be.
253 public void nextStep() {
261 if (!currentOperation.get().nextStep()) {
262 // current operation is done - try the next
263 controlLoopHistory.addAll(currentOperation.get().getHistory());
264 processor.nextPolicyForResult(currentOperation.get().getOperationResult());
268 } catch (ControlLoopException | RuntimeException e) {
269 // processor problem - this is fatal
270 logger.warn("{}: cannot start next step for {}", closedLoopControlName, requestId, e);
271 notification = makeNotification();
272 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
273 notification.setMessage("Policy processing aborted due to policy error");
274 notification.setHistory(controlLoopHistory);
275 finalResult = FinalResult.FINAL_FAILURE_EXCEPTION;
280 * Determines if the manager is still active.
282 * @return {@code true} if the manager is still active, {@code false} otherwise
284 public boolean isActive() {
285 return (createdByThisJvmInstance && finalResult == null);
289 * Updates working memory if this changes.
291 * @param operation operation manager that was updated
294 public synchronized void updated(ControlLoopOperationManager2 operation) {
295 if (!isActive() || operation != currentOperation.get()) {
296 // no longer working on the given operation
300 notification = makeNotification();
302 VirtualControlLoopEvent event = context.getEvent();
304 notification.setHistory(operation.getHistory());
306 switch (operation.getState()) {
308 notification.setNotification(ControlLoopNotificationType.REJECTED);
309 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is already locked");
312 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
313 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is no longer locked");
316 notification.setNotification(ControlLoopNotificationType.OPERATION);
317 notification.setMessage(
318 "Sending guard query for " + operation.getActor() + " " + operation.getOperation());
320 case GUARD_PERMITTED:
321 notification.setNotification(ControlLoopNotificationType.OPERATION);
322 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
326 notification.setNotification(ControlLoopNotificationType.OPERATION);
327 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
330 case OPERATION_SUCCESS:
331 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
334 case CONTROL_LOOP_TIMEOUT:
335 logger.warn("{}: control loop timed out for {}", closedLoopControlName, requestId);
336 controlLoopHistory.addAll(currentOperation.get().getHistory());
337 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
338 notification.setMessage("Control Loop timed out");
339 notification.setHistory(controlLoopHistory);
340 finalResult = FinalResult.FINAL_FAILURE;
343 case OPERATION_FAILURE:
345 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
350 workMem.update(factHandle, this);
354 * Cancels the current operation and frees all locks.
356 public void destroy() {
357 ControlLoopOperationManager2 oper = currentOperation.get();
362 getBlockingExecutor().execute(this::freeAllLocks);
368 private void freeAllLocks() {
369 target2lock.values().forEach(LockData::free);
373 * Makes a notification message for the current operation.
375 * @return a new notification
377 public VirtualControlLoopNotification makeNotification() {
378 VirtualControlLoopNotification notif = new VirtualControlLoopNotification();
379 notif.setNotification(ControlLoopNotificationType.OPERATION);
380 notif.setFrom("policy");
381 notif.setPolicyScope(policyScope);
382 notif.setPolicyVersion(policyVersion);
384 if (finalResult == null) {
385 ControlLoopOperationManager2 oper = currentOperation.get();
387 notif.setMessage(oper.getOperationMessage());
388 notif.setHistory(oper.getHistory());
396 * An event onset/abatement.
398 * @param event the event
401 public NewEventStatus onNewEvent(VirtualControlLoopEvent event) {
403 checkEventSyntax(event);
405 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) {
406 if (event.equals(context.getEvent())) {
407 return NewEventStatus.FIRST_ONSET;
411 return NewEventStatus.SUBSEQUENT_ONSET;
414 if (abatement == null) {
417 return NewEventStatus.FIRST_ABATEMENT;
420 return NewEventStatus.SUBSEQUENT_ABATEMENT;
423 } catch (ControlLoopException e) {
424 logger.error("{}: onNewEvent threw an exception", this, e);
425 return NewEventStatus.SYNTAX_ERROR;
430 * Determines the overall control loop timeout.
432 * @return the policy timeout, in milliseconds, if specified, a default timeout
435 private long detmControlLoopTimeoutMs() {
436 // validation checks preclude null or 0 timeout values in the policy
437 Integer timeout = processor.getControlLoop().getTimeout();
438 return TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
442 * Check an event syntax.
444 * @param event the event syntax
445 * @throws ControlLoopException if an error occurs
447 public void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
448 validateStatus(event);
449 if (StringUtils.isBlank(event.getClosedLoopControlName())) {
450 throw new ControlLoopException("No control loop name");
452 if (event.getRequestId() == null) {
453 throw new ControlLoopException("No request ID");
455 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
458 if (StringUtils.isBlank(event.getTarget())) {
459 throw new ControlLoopException("No target field");
460 } else if (!VALID_TARGETS.contains(event.getTarget().toLowerCase())) {
461 throw new ControlLoopException("target field invalid");
463 validateAaiData(event);
466 private void validateStatus(VirtualControlLoopEvent event) throws ControlLoopException {
467 if (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET
468 && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED) {
469 throw new ControlLoopException("Invalid value in closedLoopEventStatus");
473 private void validateAaiData(VirtualControlLoopEvent event) throws ControlLoopException {
474 Map<String, String> eventAai = event.getAai();
475 if (eventAai == null) {
476 throw new ControlLoopException("AAI is null");
478 if (event.getTargetType() == null) {
479 throw new ControlLoopException("The Target type is null");
481 switch (event.getTargetType()) {
484 validateAaiVmVnfData(eventAai);
487 validateAaiPnfData(eventAai);
490 throw new ControlLoopException("The target type is not supported");
494 private void validateAaiVmVnfData(Map<String, String> eventAai) throws ControlLoopException {
495 if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null
496 && eventAai.get(GENERIC_VNF_VNF_NAME) == null) {
497 throw new ControlLoopException(
498 "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
502 private void validateAaiPnfData(Map<String, String> eventAai) throws ControlLoopException {
503 if (eventAai.get(PNF_NAME) == null) {
504 throw new ControlLoopException("AAI PNF object key pnf-name is missing");
509 * Is closed loop disabled for an event.
511 * @param event the event
512 * @return <code>true</code> if the control loop is disabled, <code>false</code>
515 public static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
516 Map<String, String> aai = event.getAai();
517 return (isAaiTrue(aai.get(VSERVER_IS_CLOSED_LOOP_DISABLED))
518 || isAaiTrue(aai.get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))
519 || isAaiTrue(aai.get(PNF_IS_IN_MAINT)));
523 * Does provisioning status, for an event, have a value other than ACTIVE.
525 * @param event the event
526 * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null},
527 * {@code false} otherwise
529 protected static boolean isProvStatusInactive(VirtualControlLoopEvent event) {
530 Map<String, String> aai = event.getAai();
531 return !(PROV_STATUS_ACTIVE.equals(aai.getOrDefault(VSERVER_PROV_STATUS, PROV_STATUS_ACTIVE))
532 && PROV_STATUS_ACTIVE.equals(aai.getOrDefault(GENERIC_VNF_PROV_STATUS, PROV_STATUS_ACTIVE)));
536 * Determines the boolean value represented by the given AAI field value.
538 * @param aaiValue value to be examined
539 * @return the boolean value represented by the field value, or {@code false} if the
540 * value is {@code null}
542 protected static boolean isAaiTrue(String aaiValue) {
543 return (aaiValue != null && TRUE_VALUES.contains(aaiValue.toLowerCase()));
547 * Requests a lock. This requests the lock for the time that remains before the
548 * timeout expires. This avoids having to extend the lock.
550 * @param targetEntity entity to be locked
551 * @param lockUnavailableCallback function to be invoked if the lock is
553 * @return a future that can be used to await the lock
556 public synchronized CompletableFuture<OperationOutcome> requestLock(String targetEntity,
557 Consumer<OperationOutcome> lockUnavailableCallback) {
559 long remainingMs = endTimeMs - System.currentTimeMillis();
560 int remainingSec = 15 + Math.max(0, (int) TimeUnit.SECONDS.convert(remainingMs, TimeUnit.MILLISECONDS));
562 LockData data = target2lock.computeIfAbsent(targetEntity, key -> {
563 LockData data2 = new LockData(key, requestId);
564 makeLock(targetEntity, requestId.toString(), remainingSec, data2);
568 data.addUnavailableCallback(lockUnavailableCallback);
570 return data.getFuture();
574 * Initializes various components, on demand.
576 private static class LazyInitData {
577 private static final OperationHistoryDataManager DATA_MANAGER;
578 private static final ActorService ACTOR_SERVICE;
581 EventManagerServices services = new EventManagerServices(EVENT_MANAGER_SERVICE_CONFIG);
582 ACTOR_SERVICE = services.getActorService();
583 DATA_MANAGER = services.getDataManager();
587 // the following methods may be overridden by junit tests
589 protected ControlLoopOperationManager2 makeOperationManager(ControlLoopEventContext ctx, Policy policy) {
590 return new ControlLoopOperationManager2(this, ctx, policy, getExecutor());
593 protected Executor getExecutor() {
594 return ForkJoinPool.commonPool();
597 protected ExecutorService getBlockingExecutor() {
598 return PolicyEngineConstants.getManager().getExecutorService();
601 protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
602 PolicyEngineConstants.getManager().createLock(targetEntity, requestId, holdSec, callback, false);
606 public ActorService getActorService() {
607 return LazyInitData.ACTOR_SERVICE;
611 public OperationHistoryDataManager getDataManager() {
612 return LazyInitData.DATA_MANAGER;