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.Collections;
29 import java.util.HashMap;
30 import java.util.LinkedList;
33 import java.util.UUID;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.concurrent.Executor;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.ForkJoinPool;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicLong;
40 import java.util.concurrent.atomic.AtomicReference;
41 import java.util.function.Consumer;
42 import java.util.stream.Collectors;
43 import java.util.stream.Stream;
45 import lombok.ToString;
46 import org.apache.commons.lang3.StringUtils;
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.ControlLoopResponse;
52 import org.onap.policy.controlloop.VirtualControlLoopEvent;
53 import org.onap.policy.controlloop.VirtualControlLoopNotification;
54 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
55 import org.onap.policy.controlloop.actorserviceprovider.OperationFinalResult;
56 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
57 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
58 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
59 import org.onap.policy.controlloop.ophistory.OperationHistoryDataManager;
60 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
61 import org.onap.policy.drools.core.lock.LockCallback;
62 import org.onap.policy.drools.domain.models.operational.Operation;
63 import org.onap.policy.drools.system.PolicyEngineConstants;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
68 * Manager for a single control loop event. Once this has been created, the event can be
69 * retracted from working memory. Once this has been created, {@link #start()} should be
70 * invoked, and then {@link #nextStep()} should be invoked continually until
71 * {@link #isActive()} returns {@code false}, indicating that all steps have completed.
73 @ToString(onlyExplicitlyIncluded = true)
74 public abstract class ControlLoopEventManager2 implements ManagerContext, Serializable {
75 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager2.class);
76 private static final long serialVersionUID = -1216568161322872641L;
78 private static final String EVENT_MANAGER_SERVICE_CONFIG = "event-manager";
79 public static final String PROV_STATUS_ACTIVE = "ACTIVE";
80 private static final String VM_NAME = "VM_NAME";
81 private static final String VNF_NAME = "VNF_NAME";
82 public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
83 public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
84 public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
85 public static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled";
86 public static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled";
87 public static final String PNF_IS_IN_MAINT = "pnf.in-maint";
88 public static final String GENERIC_VNF_PROV_STATUS = "generic-vnf.prov-status";
89 public static final String VSERVER_PROV_STATUS = "vserver.prov-status";
90 public static final String PNF_ID = "pnf.pnf-id";
91 public static final String PNF_NAME = "pnf.pnf-name";
93 private static final Set<String> VALID_TARGETS = Stream
94 .of(VM_NAME, VNF_NAME, VSERVER_VSERVER_NAME, GENERIC_VNF_VNF_ID, GENERIC_VNF_VNF_NAME, PNF_NAME)
95 .map(String::toLowerCase).collect(Collectors.toSet());
97 private static final Set<String> TRUE_VALUES = Set.of("true", "t", "yes", "y");
100 * Counts the number of these objects that have been created. This is used by junit
103 private static final AtomicLong createCount = new AtomicLong(0);
105 public enum NewEventStatus {
106 FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR
110 * {@code True} if this object was created by this JVM instance, {@code false}
111 * otherwise. This will be {@code false} if this object is reconstituted from a
112 * persistent store or by transfer from another server.
114 private transient boolean createdByThisJvmInstance;
118 public final String closedLoopControlName;
121 private final UUID requestId;
123 private final ControlLoopEventContext context;
125 private int numOnsets = 1;
127 private int numAbatements = 0;
128 private VirtualControlLoopEvent abatement = null;
131 * Time, in milliseconds, when the control loop will time out.
134 private final long endTimeMs;
136 // fields extracted from the ControlLoopParams
138 private final String policyName;
139 private final String policyScope;
140 private final String policyVersion;
142 private final LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
145 * Maps a target entity to its lock.
147 private final transient Map<String, LockData> target2lock = new HashMap<>();
149 private final ControlLoopProcessor processor;
150 private final AtomicReference<ControlLoopOperationManager2> currentOperation = new AtomicReference<>();
152 private OperationFinalResult finalResult = null;
155 private VirtualControlLoopNotification notification;
157 private ControlLoopResponse controlLoopResponse;
160 private boolean updated = false;
164 * Constructs the object.
166 * @param params control loop parameters
167 * @param event event to be managed by this object
168 * @throws ControlLoopException if the event is invalid or if a YAML processor cannot
171 public ControlLoopEventManager2(ControlLoopParams params, VirtualControlLoopEvent event)
172 throws ControlLoopException {
174 createCount.incrementAndGet();
176 checkEventSyntax(event);
178 if (isClosedLoopDisabled(event)) {
179 throw new IllegalStateException("is-closed-loop-disabled is set to true on VServer or VNF");
182 if (isProvStatusInactive(event)) {
183 throw new IllegalStateException("prov-status is not ACTIVE on VServer or VNF");
186 this.createdByThisJvmInstance = true;
187 this.closedLoopControlName = params.getClosedLoopControlName();
188 this.requestId = event.getRequestId();
189 this.context = new ControlLoopEventContext(event);
190 this.policyName = params.getPolicyName();
191 this.policyScope = params.getPolicyScope();
192 this.policyVersion = params.getPolicyVersion();
193 this.processor = new ControlLoopProcessor(params.getToscaPolicy());
194 this.endTimeMs = System.currentTimeMillis() + detmControlLoopTimeoutMs();
198 * Gets the number of managers objects that have been created.
199 * @return the number of managers objects that have been created
201 public static long getCreateCount() {
202 return createCount.get();
206 * Starts the manager.
208 * @throws ControlLoopException if the processor cannot get a policy
210 public void start() throws ControlLoopException {
212 throw new IllegalStateException("manager is no longer active");
217 if (currentOperation.get() != null) {
218 throw new IllegalStateException("manager already started");
225 * Starts an operation for the current processor policy.
227 * @throws ControlLoopException if the processor cannot get a policy
229 private synchronized void startOperation() throws ControlLoopException {
231 if ((finalResult = processor.checkIsCurrentPolicyFinal()) == null) {
232 // not final - start the next operation
233 currentOperation.set(makeOperationManager(context, processor.getCurrentPolicy()));
234 currentOperation.get().start(endTimeMs - System.currentTimeMillis());
238 logger.info("final={} oper state={} for {}", finalResult, currentOperation.get().getState(), requestId);
240 controlLoopResponse = null;
241 notification = makeNotification();
242 notification.setHistory(controlLoopHistory);
244 switch (finalResult) {
245 case FINAL_FAILURE_EXCEPTION:
246 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
247 notification.setMessage("Exception in processing closed loop");
250 notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS);
253 notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP);
257 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
263 * Starts the next step, whatever that may be.
265 public synchronized void nextStep() {
273 if (!currentOperation.get().nextStep()) {
274 // current operation is done - try the next
275 controlLoopHistory.addAll(currentOperation.get().getHistory());
276 processor.nextPolicyForResult(currentOperation.get().getOperationResult());
280 } catch (ControlLoopException | RuntimeException e) {
281 // processor problem - this is fatal
282 logger.warn("{}: cannot start next step for {}", closedLoopControlName, requestId, e);
283 finalResult = OperationFinalResult.FINAL_FAILURE_EXCEPTION;
284 controlLoopResponse = null;
285 notification = makeNotification();
286 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
287 notification.setMessage("Policy processing aborted due to policy error");
288 notification.setHistory(controlLoopHistory);
293 * Determines if the manager is still active.
295 * @return {@code true} if the manager is still active, {@code false} otherwise
297 public synchronized boolean isActive() {
298 return (createdByThisJvmInstance && finalResult == null);
302 * Updates working memory if this changes.
304 * @param operation operation manager that was updated
307 public synchronized void updated(ControlLoopOperationManager2 operation) {
308 if (!isActive() || operation != currentOperation.get()) {
309 // no longer working on the given operation
313 controlLoopResponse = operation.getControlLoopResponse();
314 notification = makeNotification();
316 VirtualControlLoopEvent event = context.getEvent();
318 switch (operation.getState()) {
320 notification.setNotification(ControlLoopNotificationType.REJECTED);
321 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is already locked");
324 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
325 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is no longer locked");
328 notification.setNotification(ControlLoopNotificationType.OPERATION);
329 notification.setMessage(
330 "Sending guard query for " + operation.getActor() + " " + operation.getOperation());
332 case GUARD_PERMITTED:
333 notification.setNotification(ControlLoopNotificationType.OPERATION);
334 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
338 notification.setNotification(ControlLoopNotificationType.OPERATION);
339 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
342 case OPERATION_STARTED:
343 notification.setNotification(ControlLoopNotificationType.OPERATION);
344 notification.setMessage(operation.getOperationMessage());
345 notification.setHistory(Collections.emptyList());
347 case OPERATION_SUCCESS:
348 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
351 case CONTROL_LOOP_TIMEOUT:
352 logger.warn("{}: control loop timed out for {}", closedLoopControlName, requestId);
353 controlLoopHistory.addAll(currentOperation.get().getHistory());
354 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
355 notification.setMessage("Control Loop timed out");
356 notification.setHistory(controlLoopHistory);
357 finalResult = OperationFinalResult.FINAL_FAILURE;
360 case OPERATION_FAILURE:
362 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
371 * Cancels the current operation and frees all locks.
373 public synchronized void destroy() {
374 ControlLoopOperationManager2 oper = currentOperation.get();
379 getBlockingExecutor().execute(this::freeAllLocks);
385 private void freeAllLocks() {
386 target2lock.values().forEach(LockData::free);
390 * Makes a notification message for the current operation.
392 * @return a new notification
394 public synchronized VirtualControlLoopNotification makeNotification() {
395 VirtualControlLoopNotification notif = new VirtualControlLoopNotification(context.getEvent());
396 notif.setNotification(ControlLoopNotificationType.OPERATION);
397 notif.setFrom("policy");
398 notif.setPolicyScope(policyScope);
399 notif.setPolicyVersion(policyVersion);
401 if (finalResult == null) {
402 ControlLoopOperationManager2 oper = currentOperation.get();
404 notif.setMessage(oper.getOperationHistory());
405 notif.setHistory(oper.getHistory());
413 * An event onset/abatement.
415 * @param event the event
418 public synchronized NewEventStatus onNewEvent(VirtualControlLoopEvent event) {
420 checkEventSyntax(event);
422 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) {
423 if (event.equals(context.getEvent())) {
424 return NewEventStatus.FIRST_ONSET;
428 return NewEventStatus.SUBSEQUENT_ONSET;
431 if (abatement == null) {
434 return NewEventStatus.FIRST_ABATEMENT;
437 return NewEventStatus.SUBSEQUENT_ABATEMENT;
440 } catch (ControlLoopException e) {
441 logger.error("{}: onNewEvent threw an exception", this, e);
442 return NewEventStatus.SYNTAX_ERROR;
447 * Determines the overall control loop timeout.
449 * @return the policy timeout, in milliseconds, if specified, a default timeout
452 private long detmControlLoopTimeoutMs() {
453 // validation checks preclude null or 0 timeout values in the policy
454 Integer timeout = processor.getPolicy().getProperties().getTimeout();
455 return TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
459 * Check an event syntax.
461 * @param event the event syntax
462 * @throws ControlLoopException if an error occurs
464 protected void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
465 validateStatus(event);
466 if (StringUtils.isBlank(event.getClosedLoopControlName())) {
467 throw new ControlLoopException("No control loop name");
469 if (event.getRequestId() == null) {
470 throw new ControlLoopException("No request ID");
472 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
475 if (StringUtils.isBlank(event.getTarget())) {
476 throw new ControlLoopException("No target field");
477 } else if (!VALID_TARGETS.contains(event.getTarget().toLowerCase())) {
478 throw new ControlLoopException("target field invalid");
480 validateAaiData(event);
483 private void validateStatus(VirtualControlLoopEvent event) throws ControlLoopException {
484 if (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET
485 && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED) {
486 throw new ControlLoopException("Invalid value in closedLoopEventStatus");
490 private void validateAaiData(VirtualControlLoopEvent event) throws ControlLoopException {
491 Map<String, String> eventAai = event.getAai();
492 if (eventAai == null) {
493 throw new ControlLoopException("AAI is null");
495 if (event.getTargetType() == null) {
496 throw new ControlLoopException("The Target type is null");
498 switch (event.getTargetType()) {
501 validateAaiVmVnfData(eventAai);
504 validateAaiPnfData(eventAai);
507 throw new ControlLoopException("The target type is not supported");
511 private void validateAaiVmVnfData(Map<String, String> eventAai) throws ControlLoopException {
512 if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null
513 && eventAai.get(GENERIC_VNF_VNF_NAME) == null) {
514 throw new ControlLoopException(
515 "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
519 private void validateAaiPnfData(Map<String, String> eventAai) throws ControlLoopException {
520 if (eventAai.get(PNF_NAME) == null) {
521 throw new ControlLoopException("AAI PNF object key pnf-name is missing");
526 * Is closed loop disabled for an event.
528 * @param event the event
529 * @return <code>true</code> if the control loop is disabled, <code>false</code>
532 private static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
533 Map<String, String> aai = event.getAai();
534 return (isAaiTrue(aai.get(VSERVER_IS_CLOSED_LOOP_DISABLED))
535 || isAaiTrue(aai.get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))
536 || isAaiTrue(aai.get(PNF_IS_IN_MAINT)));
540 * Does provisioning status, for an event, have a value other than ACTIVE.
542 * @param event the event
543 * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null},
544 * {@code false} otherwise
546 private static boolean isProvStatusInactive(VirtualControlLoopEvent event) {
547 Map<String, String> aai = event.getAai();
548 return !(PROV_STATUS_ACTIVE.equalsIgnoreCase(aai.getOrDefault(VSERVER_PROV_STATUS, PROV_STATUS_ACTIVE))
549 && PROV_STATUS_ACTIVE.equalsIgnoreCase(
550 aai.getOrDefault(GENERIC_VNF_PROV_STATUS, PROV_STATUS_ACTIVE)));
554 * Determines the boolean value represented by the given AAI field value.
556 * @param aaiValue value to be examined
557 * @return the boolean value represented by the field value, or {@code false} if the
558 * value is {@code null}
560 private static boolean isAaiTrue(String aaiValue) {
561 return (aaiValue != null && TRUE_VALUES.contains(aaiValue.toLowerCase()));
565 * Requests a lock. This requests the lock for the time that remains before the
566 * timeout expires. This avoids having to extend the lock.
568 * @param targetEntity entity to be locked
569 * @param lockUnavailableCallback function to be invoked if the lock is
571 * @return a future that can be used to await the lock
574 public synchronized CompletableFuture<OperationOutcome> requestLock(String targetEntity,
575 Consumer<OperationOutcome> lockUnavailableCallback) {
577 long remainingMs = endTimeMs - System.currentTimeMillis();
578 int remainingSec = 15 + Math.max(0, (int) TimeUnit.SECONDS.convert(remainingMs, TimeUnit.MILLISECONDS));
580 LockData data = target2lock.computeIfAbsent(targetEntity, key -> {
581 LockData data2 = new LockData(key, requestId);
582 makeLock(targetEntity, requestId.toString(), remainingSec, data2);
586 data.addUnavailableCallback(lockUnavailableCallback);
588 return data.getFuture();
592 * Initializes various components, on demand.
594 private static class LazyInitData {
595 private static final OperationHistoryDataManager DATA_MANAGER;
596 private static final ActorService ACTOR_SERVICE;
599 EventManagerServices services = new EventManagerServices(EVENT_MANAGER_SERVICE_CONFIG);
600 ACTOR_SERVICE = services.getActorService();
601 DATA_MANAGER = services.getDataManager();
605 // the following methods may be overridden by junit tests
607 protected ControlLoopOperationManager2 makeOperationManager(ControlLoopEventContext ctx, Operation operation) {
608 return new ControlLoopOperationManager2(this, ctx, operation, getExecutor());
611 protected Executor getExecutor() {
612 return ForkJoinPool.commonPool();
615 protected ExecutorService getBlockingExecutor() {
616 return PolicyEngineConstants.getManager().getExecutorService();
619 protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
620 PolicyEngineConstants.getManager().createLock(targetEntity, requestId, holdSec, callback, false);
624 public ActorService getActorService() {
625 return LazyInitData.ACTOR_SERVICE;
629 public OperationHistoryDataManager getDataManager() {
630 return LazyInitData.DATA_MANAGER;
633 /* ============================================================ */
636 * This is a method, invoked from the 'start' method -- it gives subclasses
637 * the ability to add operations. The default implementation does nothing.
639 protected void startHook() {
643 * This is an abstract method that is called after a notable update has
644 * occurred to the 'ControlLoopEventManager2' object. It gives subclasses
645 * the ability to add a callback method to process state changes.
647 protected abstract void notifyUpdate();