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;
32 import java.util.concurrent.CancellationException;
33 import java.util.concurrent.CompletableFuture;
34 import java.util.concurrent.ConcurrentLinkedDeque;
35 import java.util.concurrent.Executor;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.atomic.AtomicReference;
38 import java.util.stream.Collectors;
39 import lombok.AccessLevel;
41 import lombok.ToString;
42 import org.onap.policy.aai.AaiConstants;
43 import org.onap.policy.aai.AaiCqResponse;
44 import org.onap.policy.controlloop.ControlLoopOperation;
45 import org.onap.policy.controlloop.ControlLoopResponse;
46 import org.onap.policy.controlloop.VirtualControlLoopEvent;
47 import org.onap.policy.controlloop.actor.guard.GuardActor;
48 import org.onap.policy.controlloop.actor.sdnr.SdnrActor;
49 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
50 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
51 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
52 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
53 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
54 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineUtil;
55 import org.onap.policy.drools.domain.models.operational.OperationalTarget;
56 import org.onap.policy.sdnr.PciMessage;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
61 * Manages a single Operation for a single event. Once this has been created,
62 * {@link #start()} should be invoked, and then {@link #nextStep()} should be invoked
63 * continually until it returns {@code false}, indicating that all steps have completed.
65 @ToString(onlyExplicitlyIncluded = true)
66 public class ControlLoopOperationManager2 implements Serializable {
67 private static final long serialVersionUID = -3773199283624595410L;
68 private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager2.class);
69 private static final String CL_TIMEOUT_ACTOR = "-CL-TIMEOUT-";
70 public static final String LOCK_ACTOR = "LOCK";
71 public static final String LOCK_OPERATION = "Lock";
72 private static final String GUARD_ACTOR = GuardActor.NAME;
73 public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
74 public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
75 public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
76 public static final String PNF_NAME = "pnf.pnf-name";
93 private final transient ManagerContext operContext;
94 private final transient ControlLoopEventContext eventContext;
95 private final org.onap.policy.drools.domain.models.operational.Operation policy;
99 private State state = State.ACTIVE;
102 private final String requestId;
105 private final String policyId;
108 * Bumped each time the "complete" callback is invoked by the Actor, provided it's for
112 private int attempts = 0;
114 private final Deque<Operation> operationHistory = new ConcurrentLinkedDeque<>();
117 * Set to {@code true} to prevent the last item in {@link #operationHistory} from
118 * being included in the outcome of {@link #getHistory()}. Used when the operation
119 * aborts prematurely due to lock-denied, guard-denied, etc.
121 private boolean holdLast = false;
124 * Queue of outcomes yet to be processed. Outcomes are added to this each time the
125 * "start" or "complete" callback is invoked.
127 @Getter(AccessLevel.PROTECTED)
128 private final transient Deque<OperationOutcome> outcomes = new ConcurrentLinkedDeque<>();
131 * Used to cancel the running operation.
133 @Getter(AccessLevel.PROTECTED)
134 private transient CompletableFuture<OperationOutcome> future = null;
137 * Target entity. Determined after the lock is granted, though it may require the
138 * custom query to be performed first.
141 private String targetEntity;
143 @Getter(AccessLevel.PROTECTED)
144 private final transient ControlLoopOperationParams params;
145 private final transient PipelineUtil taskUtil;
148 private ControlLoopResponse controlLoopResponse;
151 * Time when the lock was first requested.
153 private transient AtomicReference<Instant> lockStart = new AtomicReference<>();
155 // values extracted from the policy
157 private final String actor;
159 private final String operation;
161 private final String targetStr;
162 private final OperationalTarget target;
166 * Construct an instance.
168 * @param operContext this operation's context
169 * @param context event context
170 * @param operation2 operation's policy
171 * @param executor executor for the Operation
173 public ControlLoopOperationManager2(ManagerContext operContext, ControlLoopEventContext context,
174 org.onap.policy.drools.domain.models.operational.Operation operation2, Executor executor) {
176 this.operContext = operContext;
177 this.eventContext = context;
178 this.policy = operation2;
179 this.requestId = context.getEvent().getRequestId().toString();
180 this.policyId = "" + operation2.getId();
181 this.actor = operation2.getActorOperation().getActor();
182 this.operation = operation2.getActorOperation().getOperation();
183 this.target = operation2.getActorOperation().getTarget();
185 String targetType = (target != null ? target.getTargetType() : null);
186 Map<String, String> entityIds = (target != null ? target.getEntityIds() : null);
189 this.targetStr = (target != null ? target.toString() : null);
192 params = ControlLoopOperationParams.builder()
193 .actorService(operContext.getActorService())
195 .operation(operation)
198 .targetType(TargetType.toTargetType(targetType))
199 .targetEntityIds(entityIds)
200 .startCallback(this::onStart)
201 .completeCallback(this::onComplete)
205 taskUtil = new PipelineUtil(params);
209 // Internal class used for tracking
213 private class Operation implements Serializable {
214 private static final long serialVersionUID = 1L;
217 private OperationResult policyResult;
218 private ControlLoopOperation clOperation;
219 private ControlLoopResponse clResponse;
222 * Constructs the object.
224 * @param outcome outcome of the operation
226 public Operation(OperationOutcome outcome) {
227 attempt = ControlLoopOperationManager2.this.attempts;
228 policyResult = outcome.getResult();
229 clOperation = outcome.toControlLoopOperation();
230 clOperation.setTarget(targetStr);
231 clResponse = makeControlLoopResponse(outcome);
233 if (outcome.getEnd() == null) {
234 clOperation.setOutcome("Started");
235 } else if (clOperation.getOutcome() == null) {
236 clOperation.setOutcome("");
242 * Start the operation, first acquiring any locks that are needed. This should not
243 * throw any exceptions, but will, instead, invoke the callbacks with exceptions.
245 * @param remainingMs time remaining, in milliseconds, for the control loop
247 @SuppressWarnings("unchecked")
248 public synchronized void start(long remainingMs) {
249 // this is synchronized while we update "future"
252 // provide a default, in case something fails before requestLock() is called
253 lockStart.set(Instant.now());
256 future = taskUtil.sequence(
259 this::startOperation);
262 // handle any exceptions that may be thrown, set timeout, and handle timeout
265 future.exceptionally(this::handleException)
266 .orTimeout(remainingMs, TimeUnit.MILLISECONDS)
267 .exceptionally(this::handleTimeout);
270 } catch (RuntimeException e) {
276 * Start the operation, after the lock has been acquired.
280 private CompletableFuture<OperationOutcome> startOperation() {
282 ControlLoopOperationParams params2 = params.toBuilder()
283 .payload(new LinkedHashMap<>())
284 .retry(policy.getRetries())
285 .timeoutSec(policy.getTimeout())
286 .targetEntity(targetEntity)
290 if (policy.getActorOperation().getPayload() != null) {
291 params2.getPayload().putAll(policy.getActorOperation().getPayload());
294 return params2.start();
298 * Handles exceptions that may be generated.
300 * @param thrown exception that was generated
301 * @return {@code null}
303 private OperationOutcome handleException(Throwable thrown) {
304 if (thrown instanceof CancellationException || thrown.getCause() instanceof CancellationException) {
308 logger.warn("{}.{}: exception starting operation for {}", actor, operation, requestId, thrown);
309 OperationOutcome outcome = taskUtil.setOutcome(params.makeOutcome(), thrown);
310 outcome.setStart(lockStart.get());
311 outcome.setEnd(Instant.now());
312 outcome.setFinalOutcome(true);
315 // this outcome is not used so just return "null"
320 * Handles control loop timeout exception.
322 * @param thrown exception that was generated
323 * @return {@code null}
325 private OperationOutcome handleTimeout(Throwable thrown) {
326 logger.warn("{}.{}: control loop timeout for {}", actor, operation, requestId, thrown);
328 OperationOutcome outcome = taskUtil.setOutcome(params.makeOutcome(), thrown);
329 outcome.setActor(CL_TIMEOUT_ACTOR);
330 outcome.setOperation(null);
331 outcome.setStart(lockStart.get());
332 outcome.setEnd(Instant.now());
333 outcome.setFinalOutcome(true);
336 // cancel the operation, if it's still running
337 future.cancel(false);
339 // this outcome is not used so just return "null"
344 * Cancels the operation.
346 public void cancel() {
347 synchronized (this) {
348 if (future == null) {
353 future.cancel(false);
357 * Requests a lock on the {@link #targetEntity}.
359 * @return a future to await the lock
361 private CompletableFuture<OperationOutcome> requestLock() {
363 * Failures are handled via the callback, and successes are discarded by
364 * sequence(), without passing them to onComplete().
366 * Return a COPY of the future so that if we try to cancel it, we'll only cancel
367 * the copy, not the original. This is done by tacking thenApply() onto the end.
369 lockStart.set(Instant.now());
370 return operContext.requestLock(targetEntity, this::lockUnavailable).thenApply(outcome -> outcome);
374 * Indicates that the lock on the target entity is unavailable.
376 * @param outcome lock outcome
378 private void lockUnavailable(OperationOutcome outcome) {
380 // Note: NEVER invoke onStart() for locks; only invoke onComplete()
384 * Now that we've added the lock outcome to the queue, ensure the future is
385 * canceled, which may, itself, generate an operation outcome.
391 * Handles responses provided via the "start" callback. Note: this is never be invoked
392 * for locks; only {@link #onComplete(OperationOutcome)} is invoked for locks.
394 * @param outcome outcome provided to the callback
396 private void onStart(OperationOutcome outcome) {
397 if (outcome.isFor(actor, operation) || GUARD_ACTOR.equals(outcome.getActor())) {
403 * Handles responses provided via the "complete" callback. Note: this is never invoked
404 * for "successful" locks.
406 * @param outcome outcome provided to the callback
408 private void onComplete(OperationOutcome outcome) {
410 switch (outcome.getActor()) {
413 case CL_TIMEOUT_ACTOR:
418 if (outcome.isFor(actor, operation)) {
426 * Adds an outcome to {@link #outcomes}.
428 * @param outcome outcome to be added
430 private synchronized void addOutcome(OperationOutcome outcome) {
432 * This is synchronized to prevent nextStep() from invoking processOutcome() at
436 logger.debug("added outcome={} for {}", outcome, requestId);
437 outcomes.add(outcome);
439 if (outcomes.peekFirst() == outcomes.peekLast()) {
440 // this is the first outcome in the queue - process it
446 * Looks for the next step in the queue.
448 * @return {@code true} if more responses are expected, {@code false} otherwise
450 public synchronized boolean nextStep() {
455 case CONTROL_LOOP_TIMEOUT:
462 OperationOutcome outcome = outcomes.peek();
463 if (outcome == null) {
468 if (outcome.isFinalOutcome() && outcome.isFor(actor, operation)) {
469 controlLoopResponse = null;
473 // first item has been processed, remove it
475 if (!outcomes.isEmpty()) {
476 // have a new "first" item - process it
484 * Processes the first item in {@link #outcomes}. Sets the state, increments
485 * {@link #attempts}, if appropriate, and stores the operation history in the DB.
487 private synchronized void processOutcome() {
488 OperationOutcome outcome = outcomes.peek();
489 logger.debug("process outcome={} for {}", outcome, requestId);
491 controlLoopResponse = null;
493 switch (outcome.getActor()) {
495 case CL_TIMEOUT_ACTOR:
496 state = State.CONTROL_LOOP_TIMEOUT;
497 processAbort(outcome, OperationResult.FAILURE, "Control loop timed out");
501 // lock is no longer available
502 if (state == State.ACTIVE) {
503 state = State.LOCK_DENIED;
504 storeFailureInDataBase(outcome, OperationResult.FAILURE_GUARD, "Operation denied by Lock");
506 state = State.LOCK_LOST;
507 processAbort(outcome, OperationResult.FAILURE, "Operation aborted by Lock");
512 if (outcome.getEnd() == null) {
513 state = State.GUARD_STARTED;
514 } else if (outcome.getResult() == OperationResult.SUCCESS) {
515 state = State.GUARD_PERMITTED;
517 state = State.GUARD_DENIED;
518 storeFailureInDataBase(outcome, OperationResult.FAILURE_GUARD, "Operation denied by Guard");
523 if (outcome.getEnd() == null) {
526 state = State.OPERATION_STARTED;
530 * Operation completed. If the last entry was a "start" (i.e., "end" field
531 * is null), then replace it. Otherwise, just add the completion.
533 state = (outcome.getResult() == OperationResult.SUCCESS ? State.OPERATION_SUCCESS
534 : State.OPERATION_FAILURE);
535 controlLoopResponse = makeControlLoopResponse(outcome);
536 if (!operationHistory.isEmpty() && operationHistory.peekLast().getClOperation().getEnd() == null) {
537 operationHistory.removeLast();
541 operationHistory.add(new Operation(outcome));
542 storeOperationInDataBase();
546 // indicate that this has changed
547 operContext.updated(this);
551 * Processes an operation abort, updating the DB record, if an operation has been
554 * @param outcome operation outcome
555 * @param result result to put into the DB
556 * @param message message to put into the DB
558 private void processAbort(OperationOutcome outcome, OperationResult result, String message) {
559 if (operationHistory.isEmpty() || operationHistory.peekLast().getClOperation().getEnd() != null) {
560 // last item was not a "start" operation
562 // NOTE: do NOT generate control loop response since operation was not started
564 storeFailureInDataBase(outcome, result, message);
568 // last item was a "start" operation - replace it with a failure
569 final Operation operOrig = operationHistory.removeLast();
571 // use start time from the operation, itself
572 if (operOrig != null && operOrig.getClOperation() != null) {
573 outcome.setStart(operOrig.getClOperation().getStart());
576 controlLoopResponse = makeControlLoopResponse(outcome);
578 storeFailureInDataBase(outcome, result, message);
582 * Makes a control loop response.
584 * @param outcome operation outcome
585 * @return a new control loop response, or {@code null} if none is required
587 protected ControlLoopResponse makeControlLoopResponse(OperationOutcome outcome) {
589 // only generate response for certain actors.
590 if (outcome == null || !actor.equals(SdnrActor.NAME)) {
594 VirtualControlLoopEvent event = eventContext.getEvent();
596 ControlLoopResponse clRsp = new ControlLoopResponse();
597 clRsp.setFrom(actor);
598 clRsp.setTarget("DCAE");
599 clRsp.setClosedLoopControlName(event.getClosedLoopControlName());
600 clRsp.setPolicyName(event.getPolicyName());
601 clRsp.setPolicyVersion(event.getPolicyVersion());
602 clRsp.setRequestId(event.getRequestId());
603 clRsp.setVersion(event.getVersion());
605 PciMessage msg = outcome.getResponse();
606 if (msg != null && msg.getBody() != null && msg.getBody().getOutput() != null) {
607 clRsp.setPayload(msg.getBody().getOutput().getPayload());
614 * Get the operation, as a message.
616 * @return the operation, as a message
618 public String getOperationMessage() {
619 Operation last = operationHistory.peekLast();
620 return (last == null ? null : last.getClOperation().toMessage());
624 * Gets the operation result.
626 * @return the operation result
628 public OperationResult getOperationResult() {
629 Operation last = operationHistory.peekLast();
630 return (last == null ? OperationResult.FAILURE_EXCEPTION : last.getPolicyResult());
634 * Get the latest operation history.
636 * @return the latest operation history
638 public String getOperationHistory() {
639 Operation last = operationHistory.peekLast();
640 return (last == null ? null : last.clOperation.toHistory());
646 * @return the list of control loop operations
648 public List<ControlLoopOperation> getHistory() {
649 Operation last = (holdLast ? operationHistory.removeLast() : null);
651 List<ControlLoopOperation> result = operationHistory.stream().map(Operation::getClOperation)
652 .map(ControlLoopOperation::new).collect(Collectors.toList());
655 operationHistory.add(last);
662 * Stores a failure in the DB.
664 * @param outcome operation outcome
665 * @param result result to put into the DB
666 * @param message message to put into the DB
668 private void storeFailureInDataBase(OperationOutcome outcome, OperationResult result, String message) {
669 // don't include this in history yet
672 outcome.setActor(actor);
673 outcome.setOperation(operation);
674 outcome.setMessage(message);
675 outcome.setResult(result);
677 operationHistory.add(new Operation(outcome));
678 storeOperationInDataBase();
682 * Stores the latest operation in the DB.
684 private void storeOperationInDataBase() {
685 operContext.getDataManager().store(requestId, eventContext.getEvent(), targetEntity,
686 operationHistory.peekLast().getClOperation());
690 * Determines the target entity.
692 * @return a future to determine the target entity, or {@code null} if the entity has
693 * already been determined
695 protected CompletableFuture<OperationOutcome> detmTarget() {
696 if (target == null) {
697 throw new IllegalArgumentException("The target is null");
700 if (target.getTargetType() == null) {
701 throw new IllegalArgumentException("The target type is null");
704 switch (TargetType.toTargetType(target.getTargetType())) {
706 return detmPnfTarget();
710 return detmVfModuleTarget();
712 throw new IllegalArgumentException("The target type is not supported");
717 * Determines the PNF target entity.
719 * @return a future to determine the target entity, or {@code null} if the entity has
720 * already been determined
722 private CompletableFuture<OperationOutcome> detmPnfTarget() {
723 if (!PNF_NAME.equalsIgnoreCase(eventContext.getEvent().getTarget())) {
724 throw new IllegalArgumentException("Target does not match target type");
727 targetEntity = eventContext.getEnrichment().get(PNF_NAME);
728 if (targetEntity == null) {
729 throw new IllegalArgumentException("AAI section is missing " + PNF_NAME);
736 * Determines the VF Module target entity.
738 * @return a future to determine the target entity, or {@code null} if the entity has
739 * already been determined
741 private CompletableFuture<OperationOutcome> detmVfModuleTarget() {
742 String targetFieldName = eventContext.getEvent().getTarget();
743 if (targetFieldName == null) {
744 throw new IllegalArgumentException("Target is null");
747 switch (targetFieldName.toLowerCase()) {
748 case VSERVER_VSERVER_NAME:
749 targetEntity = eventContext.getEnrichment().get(VSERVER_VSERVER_NAME);
751 case GENERIC_VNF_VNF_ID:
752 targetEntity = eventContext.getEnrichment().get(GENERIC_VNF_VNF_ID);
754 case GENERIC_VNF_VNF_NAME:
755 return detmVnfName();
757 throw new IllegalArgumentException("Target does not match target type");
760 if (targetEntity == null) {
761 throw new IllegalArgumentException("Enrichment data is missing " + targetFieldName);
768 * Determines the VNF Name target entity.
770 * @return a future to determine the target entity, or {@code null} if the entity has
771 * already been determined
773 @SuppressWarnings("unchecked")
774 private CompletableFuture<OperationOutcome> detmVnfName() {
775 // if the onset is enriched with the vnf-id, we don't need an A&AI response
776 targetEntity = eventContext.getEnrichment().get(GENERIC_VNF_VNF_ID);
777 if (targetEntity != null) {
781 // vnf-id was not in the onset - obtain it via the custom query
784 ControlLoopOperationParams cqparams = params.toBuilder()
785 .actor(AaiConstants.ACTOR_NAME)
786 .operation(AaiCqResponse.OPERATION)
791 // perform custom query and then extract the VNF ID from it
792 return taskUtil.sequence(() -> eventContext.obtain(AaiCqResponse.CONTEXT_KEY, cqparams),
793 this::extractVnfFromCq);
797 * Extracts the VNF Name target entity from the custom query data.
799 * @return {@code null}
801 private CompletableFuture<OperationOutcome> extractVnfFromCq() {
802 // already have the CQ data
803 AaiCqResponse cq = eventContext.getProperty(AaiCqResponse.CONTEXT_KEY);
804 if (cq.getDefaultGenericVnf() == null) {
805 throw new IllegalArgumentException("No vnf-id found");
808 targetEntity = cq.getDefaultGenericVnf().getVnfId();
809 if (targetEntity == null) {
810 throw new IllegalArgumentException("No vnf-id found");