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.AtomicReference;
40 import java.util.function.Consumer;
41 import java.util.stream.Collectors;
42 import java.util.stream.Stream;
44 import lombok.ToString;
45 import org.apache.commons.lang3.StringUtils;
46 import org.drools.core.WorkingMemory;
47 import org.kie.api.runtime.rule.FactHandle;
48 import org.onap.policy.controlloop.ControlLoopEventStatus;
49 import org.onap.policy.controlloop.ControlLoopException;
50 import org.onap.policy.controlloop.ControlLoopNotificationType;
51 import org.onap.policy.controlloop.ControlLoopOperation;
52 import org.onap.policy.controlloop.ControlLoopResponse;
53 import org.onap.policy.controlloop.VirtualControlLoopEvent;
54 import org.onap.policy.controlloop.VirtualControlLoopNotification;
55 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
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.policy.FinalResult;
61 import org.onap.policy.controlloop.policy.Policy;
62 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
63 import org.onap.policy.drools.core.lock.LockCallback;
64 import org.onap.policy.drools.system.PolicyEngineConstants;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
69 * Manager for a single control loop event. Once this has been created, the event can be
70 * retracted from working memory. Once this has been created, {@link #start()} should be
71 * invoked, and then {@link #nextStep()} should be invoked continually until
72 * {@link #isActive()} returns {@code false}, indicating that all steps have completed.
74 @ToString(onlyExplicitlyIncluded = true)
75 public class ControlLoopEventManager2 implements ManagerContext, Serializable {
76 private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager2.class);
77 private static final long serialVersionUID = -1216568161322872641L;
79 private static final String EVENT_MANAGER_SERVICE_CONFIG = "event-manager";
80 public static final String PROV_STATUS_ACTIVE = "ACTIVE";
81 private static final String VM_NAME = "VM_NAME";
82 private static final String VNF_NAME = "VNF_NAME";
83 public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
84 public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
85 public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
86 public static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled";
87 public static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled";
88 public static final String PNF_IS_IN_MAINT = "pnf.in-maint";
89 public static final String GENERIC_VNF_PROV_STATUS = "generic-vnf.prov-status";
90 public static final String VSERVER_PROV_STATUS = "vserver.prov-status";
91 public static final String PNF_ID = "pnf.pnf-id";
92 public static final String PNF_NAME = "pnf.pnf-name";
94 private static final Set<String> VALID_TARGETS = Stream
95 .of(VM_NAME, VNF_NAME, VSERVER_VSERVER_NAME, GENERIC_VNF_VNF_ID, GENERIC_VNF_VNF_NAME, PNF_NAME)
96 .map(String::toLowerCase).collect(Collectors.toSet());
98 private static final Set<String> TRUE_VALUES = Set.of("true", "t", "yes", "y");
100 public enum NewEventStatus {
101 FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR
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;
151 private ControlLoopResponse controlLoopResponse;
154 private boolean updated = false;
156 private final transient WorkingMemory workMem;
157 private transient FactHandle factHandle;
161 * Constructs the object.
163 * @param params control loop parameters
164 * @param event event to be managed by this object
165 * @param workMem working memory to update if this changes
166 * @throws ControlLoopException if the event is invalid or if a YAML processor cannot
169 public ControlLoopEventManager2(ControlLoopParams params, VirtualControlLoopEvent event, WorkingMemory workMem)
170 throws ControlLoopException {
172 checkEventSyntax(event);
174 if (isClosedLoopDisabled(event)) {
175 throw new IllegalStateException("is-closed-loop-disabled is set to true on VServer or VNF");
178 if (isProvStatusInactive(event)) {
179 throw new IllegalStateException("prov-status is not ACTIVE on VServer or VNF");
182 this.createdByThisJvmInstance = true;
183 this.closedLoopControlName = params.getClosedLoopControlName();
184 this.requestId = event.getRequestId();
185 this.context = new ControlLoopEventContext(event);
186 this.policyName = params.getPolicyName();
187 this.policyScope = params.getPolicyScope();
188 this.policyVersion = params.getPolicyVersion();
189 this.processor = new ControlLoopProcessor(params.getToscaPolicy());
190 this.workMem = workMem;
191 this.endTimeMs = System.currentTimeMillis() + detmControlLoopTimeoutMs();
195 * Starts the manager.
197 * @throws ControlLoopException if the processor cannot get a policy
199 public void start() throws ControlLoopException {
201 throw new IllegalStateException("manager is no longer active");
204 if ((factHandle = workMem.getFactHandle(this)) == null) {
205 throw new IllegalStateException("manager is not in working memory");
208 if (currentOperation.get() != null) {
209 throw new IllegalStateException("manager already started");
216 * Starts an operation for the current processor policy.
218 * @throws ControlLoopException if the processor cannot get a policy
220 private synchronized void startOperation() throws ControlLoopException {
222 if ((finalResult = processor.checkIsCurrentPolicyFinal()) == null) {
223 // not final - start the next operation
224 currentOperation.set(makeOperationManager(context, processor.getCurrentPolicy()));
225 currentOperation.get().start(endTimeMs - System.currentTimeMillis());
229 logger.info("final={} oper state={} for {}", finalResult, currentOperation.get().getState(), requestId);
231 controlLoopResponse = null;
232 notification = makeNotification();
233 notification.setHistory(controlLoopHistory);
235 switch (finalResult) {
236 case FINAL_FAILURE_EXCEPTION:
237 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
238 notification.setMessage("Exception in processing closed loop");
241 notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS);
244 notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP);
248 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
254 * Starts the next step, whatever that may be.
256 public synchronized void nextStep() {
264 if (!currentOperation.get().nextStep()) {
265 // current operation is done - try the next
266 controlLoopHistory.addAll(currentOperation.get().getHistory());
267 processor.nextPolicyForResult(currentOperation.get().getOperationResult());
271 } catch (ControlLoopException | RuntimeException e) {
272 // processor problem - this is fatal
273 logger.warn("{}: cannot start next step for {}", closedLoopControlName, requestId, e);
274 finalResult = FinalResult.FINAL_FAILURE_EXCEPTION;
275 controlLoopResponse = null;
276 notification = makeNotification();
277 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
278 notification.setMessage("Policy processing aborted due to policy error");
279 notification.setHistory(controlLoopHistory);
284 * Determines if the manager is still active.
286 * @return {@code true} if the manager is still active, {@code false} otherwise
288 public synchronized boolean isActive() {
289 return (createdByThisJvmInstance && finalResult == null);
293 * Updates working memory if this changes.
295 * @param operation operation manager that was updated
298 public synchronized void updated(ControlLoopOperationManager2 operation) {
299 if (!isActive() || operation != currentOperation.get()) {
300 // no longer working on the given operation
304 controlLoopResponse = operation.getControlLoopResponse();
305 notification = makeNotification();
307 VirtualControlLoopEvent event = context.getEvent();
309 switch (operation.getState()) {
311 notification.setNotification(ControlLoopNotificationType.REJECTED);
312 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is already locked");
315 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
316 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is no longer locked");
319 notification.setNotification(ControlLoopNotificationType.OPERATION);
320 notification.setMessage(
321 "Sending guard query for " + operation.getActor() + " " + operation.getOperation());
323 case GUARD_PERMITTED:
324 notification.setNotification(ControlLoopNotificationType.OPERATION);
325 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
329 notification.setNotification(ControlLoopNotificationType.OPERATION);
330 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
333 case OPERATION_STARTED:
334 notification.setNotification(ControlLoopNotificationType.OPERATION);
335 notification.setMessage(operation.getOperationMessage());
336 notification.setHistory(Collections.emptyList());
338 case OPERATION_SUCCESS:
339 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
342 case CONTROL_LOOP_TIMEOUT:
343 logger.warn("{}: control loop timed out for {}", closedLoopControlName, requestId);
344 controlLoopHistory.addAll(currentOperation.get().getHistory());
345 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
346 notification.setMessage("Control Loop timed out");
347 notification.setHistory(controlLoopHistory);
348 finalResult = FinalResult.FINAL_FAILURE;
351 case OPERATION_FAILURE:
353 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
358 workMem.update(factHandle, this);
362 * Cancels the current operation and frees all locks.
364 public synchronized void destroy() {
365 ControlLoopOperationManager2 oper = currentOperation.get();
370 getBlockingExecutor().execute(this::freeAllLocks);
376 private void freeAllLocks() {
377 target2lock.values().forEach(LockData::free);
381 * Makes a notification message for the current operation.
383 * @return a new notification
385 public synchronized VirtualControlLoopNotification makeNotification() {
386 VirtualControlLoopNotification notif = new VirtualControlLoopNotification(context.getEvent());
387 notif.setNotification(ControlLoopNotificationType.OPERATION);
388 notif.setFrom("policy");
389 notif.setPolicyScope(policyScope);
390 notif.setPolicyVersion(policyVersion);
392 if (finalResult == null) {
393 ControlLoopOperationManager2 oper = currentOperation.get();
395 notif.setMessage(oper.getOperationHistory());
396 notif.setHistory(oper.getHistory());
404 * An event onset/abatement.
406 * @param event the event
409 public synchronized NewEventStatus onNewEvent(VirtualControlLoopEvent event) {
411 checkEventSyntax(event);
413 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) {
414 if (event.equals(context.getEvent())) {
415 return NewEventStatus.FIRST_ONSET;
419 return NewEventStatus.SUBSEQUENT_ONSET;
422 if (abatement == null) {
425 return NewEventStatus.FIRST_ABATEMENT;
428 return NewEventStatus.SUBSEQUENT_ABATEMENT;
431 } catch (ControlLoopException e) {
432 logger.error("{}: onNewEvent threw an exception", this, e);
433 return NewEventStatus.SYNTAX_ERROR;
438 * Determines the overall control loop timeout.
440 * @return the policy timeout, in milliseconds, if specified, a default timeout
443 private long detmControlLoopTimeoutMs() {
444 // validation checks preclude null or 0 timeout values in the policy
445 Integer timeout = processor.getControlLoop().getTimeout();
446 return TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
450 * Check an event syntax.
452 * @param event the event syntax
453 * @throws ControlLoopException if an error occurs
455 protected void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
456 validateStatus(event);
457 if (StringUtils.isBlank(event.getClosedLoopControlName())) {
458 throw new ControlLoopException("No control loop name");
460 if (event.getRequestId() == null) {
461 throw new ControlLoopException("No request ID");
463 if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
466 if (StringUtils.isBlank(event.getTarget())) {
467 throw new ControlLoopException("No target field");
468 } else if (!VALID_TARGETS.contains(event.getTarget().toLowerCase())) {
469 throw new ControlLoopException("target field invalid");
471 validateAaiData(event);
474 private void validateStatus(VirtualControlLoopEvent event) throws ControlLoopException {
475 if (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET
476 && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED) {
477 throw new ControlLoopException("Invalid value in closedLoopEventStatus");
481 private void validateAaiData(VirtualControlLoopEvent event) throws ControlLoopException {
482 Map<String, String> eventAai = event.getAai();
483 if (eventAai == null) {
484 throw new ControlLoopException("AAI is null");
486 if (event.getTargetType() == null) {
487 throw new ControlLoopException("The Target type is null");
489 switch (event.getTargetType()) {
492 validateAaiVmVnfData(eventAai);
495 validateAaiPnfData(eventAai);
498 throw new ControlLoopException("The target type is not supported");
502 private void validateAaiVmVnfData(Map<String, String> eventAai) throws ControlLoopException {
503 if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null
504 && eventAai.get(GENERIC_VNF_VNF_NAME) == null) {
505 throw new ControlLoopException(
506 "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
510 private void validateAaiPnfData(Map<String, String> eventAai) throws ControlLoopException {
511 if (eventAai.get(PNF_NAME) == null) {
512 throw new ControlLoopException("AAI PNF object key pnf-name is missing");
517 * Is closed loop disabled for an event.
519 * @param event the event
520 * @return <code>true</code> if the control loop is disabled, <code>false</code>
523 private static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
524 Map<String, String> aai = event.getAai();
525 return (isAaiTrue(aai.get(VSERVER_IS_CLOSED_LOOP_DISABLED))
526 || isAaiTrue(aai.get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))
527 || isAaiTrue(aai.get(PNF_IS_IN_MAINT)));
531 * Does provisioning status, for an event, have a value other than ACTIVE.
533 * @param event the event
534 * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null},
535 * {@code false} otherwise
537 private static boolean isProvStatusInactive(VirtualControlLoopEvent event) {
538 Map<String, String> aai = event.getAai();
539 return !(PROV_STATUS_ACTIVE.equals(aai.getOrDefault(VSERVER_PROV_STATUS, PROV_STATUS_ACTIVE))
540 && PROV_STATUS_ACTIVE.equals(aai.getOrDefault(GENERIC_VNF_PROV_STATUS, PROV_STATUS_ACTIVE)));
544 * Determines the boolean value represented by the given AAI field value.
546 * @param aaiValue value to be examined
547 * @return the boolean value represented by the field value, or {@code false} if the
548 * value is {@code null}
550 private static boolean isAaiTrue(String aaiValue) {
551 return (aaiValue != null && TRUE_VALUES.contains(aaiValue.toLowerCase()));
555 * Requests a lock. This requests the lock for the time that remains before the
556 * timeout expires. This avoids having to extend the lock.
558 * @param targetEntity entity to be locked
559 * @param lockUnavailableCallback function to be invoked if the lock is
561 * @return a future that can be used to await the lock
564 public synchronized CompletableFuture<OperationOutcome> requestLock(String targetEntity,
565 Consumer<OperationOutcome> lockUnavailableCallback) {
567 long remainingMs = endTimeMs - System.currentTimeMillis();
568 int remainingSec = 15 + Math.max(0, (int) TimeUnit.SECONDS.convert(remainingMs, TimeUnit.MILLISECONDS));
570 LockData data = target2lock.computeIfAbsent(targetEntity, key -> {
571 LockData data2 = new LockData(key, requestId);
572 makeLock(targetEntity, requestId.toString(), remainingSec, data2);
576 data.addUnavailableCallback(lockUnavailableCallback);
578 return data.getFuture();
582 * Initializes various components, on demand.
584 private static class LazyInitData {
585 private static final OperationHistoryDataManager DATA_MANAGER;
586 private static final ActorService ACTOR_SERVICE;
589 EventManagerServices services = new EventManagerServices(EVENT_MANAGER_SERVICE_CONFIG);
590 ACTOR_SERVICE = services.getActorService();
591 DATA_MANAGER = services.getDataManager();
595 // the following methods may be overridden by junit tests
597 protected ControlLoopOperationManager2 makeOperationManager(ControlLoopEventContext ctx, Policy policy) {
598 return new ControlLoopOperationManager2(this, ctx, policy, getExecutor());
601 protected Executor getExecutor() {
602 return ForkJoinPool.commonPool();
605 protected ExecutorService getBlockingExecutor() {
606 return PolicyEngineConstants.getManager().getExecutorService();
609 protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
610 PolicyEngineConstants.getManager().createLock(targetEntity, requestId, holdSec, callback, false);
614 public ActorService getActorService() {
615 return LazyInitData.ACTOR_SERVICE;
619 public OperationHistoryDataManager getDataManager() {
620 return LazyInitData.DATA_MANAGER;