2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved.
7 * Modifications Copyright (C) 2019 Tech Mahindra
8 * Modifications Copyright (C) 2019 Bell Canada.
9 * ================================================================================
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
14 * http://www.apache.org/licenses/LICENSE-2.0
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.controlloop.eventmanager;
26 import java.io.Serializable;
27 import java.time.Instant;
28 import java.util.Deque;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.concurrent.CancellationException;
32 import java.util.concurrent.CompletableFuture;
33 import java.util.concurrent.ConcurrentLinkedDeque;
34 import java.util.concurrent.Executor;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicReference;
37 import java.util.stream.Collectors;
38 import lombok.AccessLevel;
40 import lombok.ToString;
41 import org.onap.policy.aai.AaiConstants;
42 import org.onap.policy.aai.AaiCqResponse;
43 import org.onap.policy.controlloop.ControlLoopOperation;
44 import org.onap.policy.controlloop.ControlLoopResponse;
45 import org.onap.policy.controlloop.VirtualControlLoopEvent;
46 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
47 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
48 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
49 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineUtil;
50 import org.onap.policy.controlloop.policy.Policy;
51 import org.onap.policy.controlloop.policy.PolicyResult;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Manages a single Operation for a single event. Once this has been created,
57 * {@link #start()} should be invoked, and then {@link #nextStep()} should be invoked
58 * continually until it returns {@code false}, indicating that all steps have completed.
60 @ToString(onlyExplicitlyIncluded = true)
61 public class ControlLoopOperationManager2 implements Serializable {
62 private static final long serialVersionUID = -3773199283624595410L;
63 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager2.class);
64 private static final String CL_TIMEOUT_ACTOR = "-CL-TIMEOUT-";
65 public static final String LOCK_ACTOR = "LOCK";
66 public static final String LOCK_OPERATION = "Lock";
67 private static final String GUARD_ACTOR = "GUARD";
68 public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
69 public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
70 public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
71 public static final String PNF_NAME = "pnf.pnf-name";
88 private final transient ManagerContext operContext;
89 private final transient ControlLoopEventContext eventContext;
90 private final Policy policy;
94 private State state = State.ACTIVE;
97 private final String requestId;
100 private final String policyId;
103 * Bumped each time the "complete" callback is invoked by the Actor, provided it's for
107 private int attempts = 0;
109 private final Deque<Operation> operationHistory = new ConcurrentLinkedDeque<>();
112 * Set to {@code true} to prevent the last item in {@link #operationHistory} from
113 * being included in the outcome of {@link #getHistory()}. Used when the operation
114 * aborts prematurely due to lock-denied, guard-denied, etc.
116 private boolean holdLast = false;
119 * Queue of outcomes yet to be processed. Outcomes are added to this each time the
120 * "start" or "complete" callback is invoked.
122 @Getter(AccessLevel.PROTECTED)
123 private final transient Deque<OperationOutcome> outcomes = new ConcurrentLinkedDeque<>();
126 * Used to cancel the running operation.
128 @Getter(AccessLevel.PROTECTED)
129 private transient CompletableFuture<OperationOutcome> future = null;
132 * Target entity. Determined after the lock is granted, though it may require the
133 * custom query to be performed first.
136 private String targetEntity;
138 @Getter(AccessLevel.PROTECTED)
139 private final transient ControlLoopOperationParams params;
140 private final transient PipelineUtil taskUtil;
143 private ControlLoopResponse controlLoopResponse;
146 * Time when the lock was first requested.
148 private transient AtomicReference<Instant> lockStart = new AtomicReference<>();
150 // values extracted from the policy
152 private final String actor;
154 private final String operation;
158 * Construct an instance.
160 * @param operContext this operation's context
161 * @param context event context
162 * @param policy operation's policy
163 * @param executor executor for the Operation
165 public ControlLoopOperationManager2(ManagerContext operContext, ControlLoopEventContext context, Policy policy,
168 this.operContext = operContext;
169 this.eventContext = context;
170 this.policy = policy;
171 this.requestId = context.getEvent().getRequestId().toString();
172 this.policyId = "" + policy.getId();
173 this.actor = policy.getActor();
174 this.operation = policy.getRecipe();
177 params = ControlLoopOperationParams.builder()
178 .actorService(operContext.getActorService())
180 .operation(operation)
183 .target(policy.getTarget())
184 .startCallback(this::onStart)
185 .completeCallback(this::onComplete)
189 taskUtil = new PipelineUtil(params);
193 // Internal class used for tracking
197 private class Operation implements Serializable {
198 private static final long serialVersionUID = 1L;
201 private PolicyResult policyResult;
202 private ControlLoopOperation clOperation;
203 private ControlLoopResponse clResponse;
206 * Constructs the object.
208 * @param outcome outcome of the operation
210 public Operation(OperationOutcome outcome) {
211 attempt = ControlLoopOperationManager2.this.attempts;
212 policyResult = outcome.getResult();
213 clOperation = outcome.toControlLoopOperation();
214 clOperation.setTarget(policy.getTarget().toString());
215 clResponse = outcome.getControlLoopResponse();
217 if (outcome.getEnd() == null) {
218 clOperation.setOutcome("Started");
219 } else if (clOperation.getOutcome() == null) {
220 clOperation.setOutcome("");
226 * Start the operation, first acquiring any locks that are needed. This should not
227 * throw any exceptions, but will, instead, invoke the callbacks with exceptions.
229 * @param remainingMs time remaining, in milliseconds, for the control loop
231 @SuppressWarnings("unchecked")
232 public synchronized void start(long remainingMs) {
233 // this is synchronized while we update "future"
236 // provide a default, in case something fails before requestLock() is called
237 lockStart.set(Instant.now());
240 future = taskUtil.sequence(
243 this::startOperation);
246 // handle any exceptions that may be thrown, set timeout, and handle timeout
249 future.exceptionally(this::handleException)
250 .orTimeout(remainingMs, TimeUnit.MILLISECONDS)
251 .exceptionally(this::handleTimeout);
254 } catch (RuntimeException e) {
260 * Start the operation, after the lock has been acquired.
264 private CompletableFuture<OperationOutcome> startOperation() {
266 ControlLoopOperationParams params2 = params.toBuilder()
267 .payload(new LinkedHashMap<>())
268 .retry(policy.getRetry())
269 .timeoutSec(policy.getTimeout())
270 .targetEntity(targetEntity)
274 if (policy.getPayload() != null) {
275 params2.getPayload().putAll(policy.getPayload());
278 return params2.start();
282 * Handles exceptions that may be generated.
284 * @param thrown exception that was generated
285 * @return {@code null}
287 private OperationOutcome handleException(Throwable thrown) {
288 if (thrown instanceof CancellationException || thrown.getCause() instanceof CancellationException) {
292 logger.warn("{}.{}: exception starting operation for {}", actor, operation, requestId, thrown);
293 OperationOutcome outcome = taskUtil.setOutcome(params.makeOutcome(), thrown);
294 outcome.setStart(lockStart.get());
295 outcome.setEnd(Instant.now());
296 outcome.setFinalOutcome(true);
299 // this outcome is not used so just return "null"
304 * Handles control loop timeout exception.
306 * @param thrown exception that was generated
307 * @return {@code null}
309 private OperationOutcome handleTimeout(Throwable thrown) {
310 logger.warn("{}.{}: control loop timeout for {}", actor, operation, requestId, thrown);
312 OperationOutcome outcome = taskUtil.setOutcome(params.makeOutcome(), thrown);
313 outcome.setActor(CL_TIMEOUT_ACTOR);
314 outcome.setOperation(null);
315 outcome.setStart(lockStart.get());
316 outcome.setEnd(Instant.now());
317 outcome.setFinalOutcome(true);
320 // cancel the operation, if it's still running
321 future.cancel(false);
323 // this outcome is not used so just return "null"
328 * Cancels the operation.
330 public void cancel() {
331 synchronized (this) {
332 if (future == null) {
337 future.cancel(false);
341 * Requests a lock on the {@link #targetEntity}.
343 * @return a future to await the lock
345 private CompletableFuture<OperationOutcome> requestLock() {
347 * Failures are handled via the callback, and successes are discarded by
348 * sequence(), without passing them to onComplete().
350 * Return a COPY of the future so that if we try to cancel it, we'll only cancel
351 * the copy, not the original. This is done by tacking thenApply() onto the end.
353 lockStart.set(Instant.now());
354 return operContext.requestLock(targetEntity, this::lockUnavailable).thenApply(outcome -> outcome);
358 * Indicates that the lock on the target entity is unavailable.
360 * @param outcome lock outcome
362 private void lockUnavailable(OperationOutcome outcome) {
364 // Note: NEVER invoke onStart() for locks; only invoke onComplete()
368 * Now that we've added the lock outcome to the queue, ensure the future is
369 * canceled, which may, itself, generate an operation outcome.
375 * Handles responses provided via the "start" callback. Note: this is never be invoked
376 * for locks; only {@link #onComplete(OperationOutcome)} is invoked for locks.
378 * @param outcome outcome provided to the callback
380 private void onStart(OperationOutcome outcome) {
381 if (outcome.isFor(actor, operation) || GUARD_ACTOR.equals(outcome.getActor())) {
387 * Handles responses provided via the "complete" callback. Note: this is never invoked
388 * for "successful" locks.
390 * @param outcome outcome provided to the callback
392 private void onComplete(OperationOutcome outcome) {
394 switch (outcome.getActor()) {
397 case CL_TIMEOUT_ACTOR:
402 if (outcome.isFor(actor, operation)) {
410 * Adds an outcome to {@link #outcomes}.
412 * @param outcome outcome to be added
414 private synchronized void addOutcome(OperationOutcome outcome) {
416 * This is synchronized to prevent nextStep() from invoking processOutcome() at
420 logger.debug("added outcome={} for {}", outcome, requestId);
421 outcomes.add(outcome);
423 if (outcomes.peekFirst() == outcomes.peekLast()) {
424 // this is the first outcome in the queue - process it
430 * Looks for the next step in the queue.
432 * @return {@code true} if more responses are expected, {@code false} otherwise
434 public synchronized boolean nextStep() {
439 case CONTROL_LOOP_TIMEOUT:
446 OperationOutcome outcome = outcomes.peek();
447 if (outcome == null) {
452 if (outcome.isFinalOutcome() && outcome.isFor(actor, operation)) {
453 controlLoopResponse = null;
457 // first item has been processed, remove it
459 if (!outcomes.isEmpty()) {
460 // have a new "first" item - process it
468 * Processes the first item in {@link #outcomes}. Sets the state, increments
469 * {@link #attempts}, if appropriate, and stores the operation history in the DB.
471 private synchronized void processOutcome() {
472 OperationOutcome outcome = outcomes.peek();
473 logger.debug("process outcome={} for {}", outcome, requestId);
475 controlLoopResponse = null;
477 switch (outcome.getActor()) {
479 case CL_TIMEOUT_ACTOR:
480 state = State.CONTROL_LOOP_TIMEOUT;
481 processAbort(outcome, PolicyResult.FAILURE, "Control loop timed out");
485 // lock is no longer available
486 if (state == State.ACTIVE) {
487 state = State.LOCK_DENIED;
488 storeFailureInDataBase(outcome, PolicyResult.FAILURE_GUARD, "Operation denied by Lock");
490 state = State.LOCK_LOST;
491 processAbort(outcome, PolicyResult.FAILURE, "Operation aborted by Lock");
496 if (outcome.getEnd() == null) {
497 state = State.GUARD_STARTED;
498 } else if (outcome.getResult() == PolicyResult.SUCCESS) {
499 state = State.GUARD_PERMITTED;
501 state = State.GUARD_DENIED;
502 storeFailureInDataBase(outcome, PolicyResult.FAILURE_GUARD, "Operation denied by Guard");
507 if (outcome.getEnd() == null) {
510 state = State.OPERATION_STARTED;
514 * Operation completed. If the last entry was a "start" (i.e., "end" field
515 * is null), then replace it. Otherwise, just add the completion.
517 state = (outcome.getResult() == PolicyResult.SUCCESS ? State.OPERATION_SUCCESS
518 : State.OPERATION_FAILURE);
519 controlLoopResponse = makeControlLoopResponse(outcome.getControlLoopResponse());
520 if (!operationHistory.isEmpty() && operationHistory.peekLast().getClOperation().getEnd() == null) {
521 operationHistory.removeLast();
525 operationHistory.add(new Operation(outcome));
526 storeOperationInDataBase();
530 // indicate that this has changed
531 operContext.updated(this);
535 * Processes an operation abort, updating the DB record, if an operation has been
538 * @param outcome operation outcome
539 * @param result result to put into the DB
540 * @param message message to put into the DB
542 private void processAbort(OperationOutcome outcome, PolicyResult result, String message) {
543 if (operationHistory.isEmpty() || operationHistory.peekLast().getClOperation().getEnd() != null) {
544 // last item was not a "start" operation
546 // NOTE: do NOT generate control loop response since operation was not started
548 storeFailureInDataBase(outcome, result, message);
552 // last item was a "start" operation - replace it with a failure
553 final Operation operOrig = operationHistory.removeLast();
555 // use start time from the operation, itself
556 if (operOrig != null && operOrig.getClOperation() != null) {
557 outcome.setStart(operOrig.getClOperation().getStart());
560 controlLoopResponse = makeControlLoopResponse(outcome.getControlLoopResponse());
562 storeFailureInDataBase(outcome, result, message);
566 * Makes a control loop response.
568 * @param source original control loop response or {@code null}
569 * @return a new control loop response, or {@code null} if none is required
571 protected ControlLoopResponse makeControlLoopResponse(ControlLoopResponse source) {
572 if (source != null) {
576 // only generate response for certain actors.
577 if (!actor.equals("SDNR")) {
581 VirtualControlLoopEvent event = eventContext.getEvent();
583 ControlLoopResponse clRsp = new ControlLoopResponse();
584 clRsp.setFrom(actor);
585 clRsp.setTarget("DCAE");
586 clRsp.setClosedLoopControlName(event.getClosedLoopControlName());
587 clRsp.setPolicyName(event.getPolicyName());
588 clRsp.setPolicyVersion(event.getPolicyVersion());
589 clRsp.setRequestId(event.getRequestId());
590 clRsp.setVersion(event.getVersion());
596 * Get the operation, as a message.
598 * @return the operation, as a message
600 public String getOperationMessage() {
601 Operation last = operationHistory.peekLast();
602 return (last == null ? null : last.getClOperation().toMessage());
606 * Gets the operation result.
608 * @return the operation result
610 public PolicyResult getOperationResult() {
611 Operation last = operationHistory.peekLast();
612 return (last == null ? PolicyResult.FAILURE_EXCEPTION : last.getPolicyResult());
616 * Get the latest operation history.
618 * @return the latest operation history
620 public String getOperationHistory() {
621 Operation last = operationHistory.peekLast();
622 return (last == null ? null : last.clOperation.toHistory());
628 * @return the list of control loop operations
630 public List<ControlLoopOperation> getHistory() {
631 Operation last = (holdLast ? operationHistory.removeLast() : null);
633 List<ControlLoopOperation> result = operationHistory.stream().map(Operation::getClOperation)
634 .map(ControlLoopOperation::new).collect(Collectors.toList());
637 operationHistory.add(last);
644 * Stores a failure in the DB.
646 * @param outcome operation outcome
647 * @param result result to put into the DB
648 * @param message message to put into the DB
650 private void storeFailureInDataBase(OperationOutcome outcome, PolicyResult result, String message) {
651 // don't include this in history yet
654 outcome.setActor(actor);
655 outcome.setOperation(operation);
656 outcome.setMessage(message);
657 outcome.setResult(result);
659 operationHistory.add(new Operation(outcome));
660 storeOperationInDataBase();
664 * Stores the latest operation in the DB.
666 private void storeOperationInDataBase() {
667 operContext.getDataManager().store(requestId, eventContext.getEvent(), targetEntity,
668 operationHistory.peekLast().getClOperation());
672 * Determines the target entity.
674 * @return a future to determine the target entity, or {@code null} if the entity has
675 * already been determined
677 protected CompletableFuture<OperationOutcome> detmTarget() {
678 if (policy.getTarget() == null) {
679 throw new IllegalArgumentException("The target is null");
682 if (policy.getTarget().getType() == null) {
683 throw new IllegalArgumentException("The target type is null");
686 switch (policy.getTarget().getType()) {
688 return detmPnfTarget();
692 return detmVfModuleTarget();
694 throw new IllegalArgumentException("The target type is not supported");
699 * Determines the PNF target entity.
701 * @return a future to determine the target entity, or {@code null} if the entity has
702 * already been determined
704 private CompletableFuture<OperationOutcome> detmPnfTarget() {
705 if (!PNF_NAME.equalsIgnoreCase(eventContext.getEvent().getTarget())) {
706 throw new IllegalArgumentException("Target does not match target type");
709 targetEntity = eventContext.getEnrichment().get(PNF_NAME);
710 if (targetEntity == null) {
711 throw new IllegalArgumentException("AAI section is missing " + PNF_NAME);
718 * Determines the VF Module target entity.
720 * @return a future to determine the target entity, or {@code null} if the entity has
721 * already been determined
723 private CompletableFuture<OperationOutcome> detmVfModuleTarget() {
724 String targetFieldName = eventContext.getEvent().getTarget();
725 if (targetFieldName == null) {
726 throw new IllegalArgumentException("Target is null");
729 switch (targetFieldName.toLowerCase()) {
730 case VSERVER_VSERVER_NAME:
731 targetEntity = eventContext.getEnrichment().get(VSERVER_VSERVER_NAME);
733 case GENERIC_VNF_VNF_ID:
734 targetEntity = eventContext.getEnrichment().get(GENERIC_VNF_VNF_ID);
736 case GENERIC_VNF_VNF_NAME:
737 return detmVnfName();
739 throw new IllegalArgumentException("Target does not match target type");
742 if (targetEntity == null) {
743 throw new IllegalArgumentException("Enrichment data is missing " + targetFieldName);
750 * Determines the VNF Name target entity.
752 * @return a future to determine the target entity, or {@code null} if the entity has
753 * already been determined
755 @SuppressWarnings("unchecked")
756 private CompletableFuture<OperationOutcome> detmVnfName() {
757 // if the onset is enriched with the vnf-id, we don't need an A&AI response
758 targetEntity = eventContext.getEnrichment().get(GENERIC_VNF_VNF_ID);
759 if (targetEntity != null) {
763 // vnf-id was not in the onset - obtain it via the custom query
766 ControlLoopOperationParams cqparams = params.toBuilder()
767 .actor(AaiConstants.ACTOR_NAME)
768 .operation(AaiCqResponse.OPERATION)
773 // perform custom query and then extract the VNF ID from it
774 return taskUtil.sequence(() -> eventContext.obtain(AaiCqResponse.CONTEXT_KEY, cqparams),
775 this::extractVnfFromCq);
779 * Extracts the VNF Name target entity from the custom query data.
781 * @return {@code null}
783 private CompletableFuture<OperationOutcome> extractVnfFromCq() {
784 // already have the CQ data
785 AaiCqResponse cq = eventContext.getProperty(AaiCqResponse.CONTEXT_KEY);
786 if (cq.getDefaultGenericVnf() == null) {
787 throw new IllegalArgumentException("No vnf-id found");
790 targetEntity = cq.getDefaultGenericVnf().getVnfId();
791 if (targetEntity == null) {
792 throw new IllegalArgumentException("No vnf-id found");