31402f4cfc2631cd04a3c793ce9977a6ffb83a06
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
13  *
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  *
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=========================================================
22  */
23
24 package org.onap.policy.controlloop.eventmanager;
25
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.Map;
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;
40 import lombok.Getter;
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;
59
60 /**
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.
64  */
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";
77
78     // @formatter:off
79     public enum State {
80         ACTIVE,
81         LOCK_DENIED,
82         LOCK_LOST,
83         GUARD_STARTED,
84         GUARD_PERMITTED,
85         GUARD_DENIED,
86         OPERATION_STARTED,
87         OPERATION_SUCCESS,
88         OPERATION_FAILURE,
89         CONTROL_LOOP_TIMEOUT
90     }
91     // @formatter:on
92
93     private final transient ManagerContext operContext;
94     private final transient ControlLoopEventContext eventContext;
95     private final org.onap.policy.drools.domain.models.operational.Operation policy;
96
97     @Getter
98     @ToString.Include
99     private State state = State.ACTIVE;
100
101     @ToString.Include
102     private final String requestId;
103
104     @ToString.Include
105     private final String policyId;
106
107     /**
108      * Bumped each time the "complete" callback is invoked by the Actor, provided it's for
109      * this operation.
110      */
111     @ToString.Include
112     private int attempts = 0;
113
114     private final Deque<Operation> operationHistory = new ConcurrentLinkedDeque<>();
115
116     /**
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.
120      */
121     private boolean holdLast = false;
122
123     /**
124      * Queue of outcomes yet to be processed. Outcomes are added to this each time the
125      * "start" or "complete" callback is invoked.
126      */
127     @Getter(AccessLevel.PROTECTED)
128     private final transient Deque<OperationOutcome> outcomes = new ConcurrentLinkedDeque<>();
129
130     /**
131      * Used to cancel the running operation.
132      */
133     @Getter(AccessLevel.PROTECTED)
134     private transient CompletableFuture<OperationOutcome> future = null;
135
136     /**
137      * Target entity. Determined after the lock is granted, though it may require the
138      * custom query to be performed first.
139      */
140     @Getter
141     private String targetEntity;
142
143     @Getter(AccessLevel.PROTECTED)
144     private final transient ControlLoopOperationParams params;
145     private final transient PipelineUtil taskUtil;
146
147     @Getter
148     private ControlLoopResponse controlLoopResponse;
149
150     /**
151      * Time when the lock was first requested.
152      */
153     private transient AtomicReference<Instant> lockStart = new AtomicReference<>();
154
155     // values extracted from the policy
156     @Getter
157     private final String actor;
158     @Getter
159     private final String operation;
160
161     private final String targetStr;
162     private final OperationalTarget target;
163
164
165     /**
166      * Construct an instance.
167      *
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
172      */
173     public ControlLoopOperationManager2(ManagerContext operContext, ControlLoopEventContext context,
174                     org.onap.policy.drools.domain.models.operational.Operation operation2, Executor executor) {
175
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();
184
185         String targetType = (target != null ? target.getTargetType() : null);
186         Map<String, String> entityIds = (target != null ? target.getEntityIds() : null);
187
188         // TODO encode()?
189         this.targetStr = (target != null ? target.toString() : null);
190
191         // @formatter:off
192         params = ControlLoopOperationParams.builder()
193                         .actorService(operContext.getActorService())
194                         .actor(actor)
195                         .operation(operation)
196                         .context(context)
197                         .executor(executor)
198                         .targetType(TargetType.toTargetType(targetType))
199                         .targetEntityIds(entityIds)
200                         .startCallback(this::onStart)
201                         .completeCallback(this::onComplete)
202                         .build();
203         // @formatter:on
204
205         taskUtil = new PipelineUtil(params);
206     }
207
208     //
209     // Internal class used for tracking
210     //
211     @Getter
212     @ToString
213     private class Operation implements Serializable {
214         private static final long serialVersionUID = 1L;
215
216         private int attempt;
217         private OperationResult policyResult;
218         private ControlLoopOperation clOperation;
219         private ControlLoopResponse clResponse;
220
221         /**
222          * Constructs the object.
223          *
224          * @param outcome outcome of the operation
225          */
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);
232
233             if (outcome.getEnd() == null) {
234                 clOperation.setOutcome("Started");
235             } else if (clOperation.getOutcome() == null) {
236                 clOperation.setOutcome("");
237             }
238         }
239     }
240
241     /**
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.
244      *
245      * @param remainingMs time remaining, in milliseconds, for the control loop
246      */
247     @SuppressWarnings("unchecked")
248     public synchronized void start(long remainingMs) {
249         // this is synchronized while we update "future"
250
251         try {
252             // provide a default, in case something fails before requestLock() is called
253             lockStart.set(Instant.now());
254
255             // @formatter:off
256             future = taskUtil.sequence(
257                 this::detmTarget,
258                 this::requestLock,
259                 this::startOperation);
260             // @formatter:on
261
262             // handle any exceptions that may be thrown, set timeout, and handle timeout
263
264             // @formatter:off
265             future.exceptionally(this::handleException)
266                     .orTimeout(remainingMs, TimeUnit.MILLISECONDS)
267                     .exceptionally(this::handleTimeout);
268             // @formatter:on
269
270         } catch (RuntimeException e) {
271             handleException(e);
272         }
273     }
274
275     /**
276      * Start the operation, after the lock has been acquired.
277      *
278      * @return
279      */
280     private CompletableFuture<OperationOutcome> startOperation() {
281         // @formatter:off
282         ControlLoopOperationParams params2 = params.toBuilder()
283                     .payload(new LinkedHashMap<>())
284                     .retry(policy.getRetries())
285                     .timeoutSec(policy.getTimeout())
286                     .targetEntity(targetEntity)
287                     .build();
288         // @formatter:on
289
290         if (policy.getActorOperation().getPayload() != null) {
291             params2.getPayload().putAll(policy.getActorOperation().getPayload());
292         }
293
294         return params2.start();
295     }
296
297     /**
298      * Handles exceptions that may be generated.
299      *
300      * @param thrown exception that was generated
301      * @return {@code null}
302      */
303     private OperationOutcome handleException(Throwable thrown) {
304         if (thrown instanceof CancellationException || thrown.getCause() instanceof CancellationException) {
305             return null;
306         }
307
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);
313         onComplete(outcome);
314
315         // this outcome is not used so just return "null"
316         return null;
317     }
318
319     /**
320      * Handles control loop timeout exception.
321      *
322      * @param thrown exception that was generated
323      * @return {@code null}
324      */
325     private OperationOutcome handleTimeout(Throwable thrown) {
326         logger.warn("{}.{}: control loop timeout for {}", actor, operation, requestId, thrown);
327
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);
334         onComplete(outcome);
335
336         // cancel the operation, if it's still running
337         future.cancel(false);
338
339         // this outcome is not used so just return "null"
340         return null;
341     }
342
343     /**
344      * Cancels the operation.
345      */
346     public void cancel() {
347         synchronized (this) {
348             if (future == null) {
349                 return;
350             }
351         }
352
353         future.cancel(false);
354     }
355
356     /**
357      * Requests a lock on the {@link #targetEntity}.
358      *
359      * @return a future to await the lock
360      */
361     private CompletableFuture<OperationOutcome> requestLock() {
362         /*
363          * Failures are handled via the callback, and successes are discarded by
364          * sequence(), without passing them to onComplete().
365          *
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.
368          */
369         lockStart.set(Instant.now());
370         return operContext.requestLock(targetEntity, this::lockUnavailable).thenApply(outcome -> outcome);
371     }
372
373     /**
374      * Indicates that the lock on the target entity is unavailable.
375      *
376      * @param outcome lock outcome
377      */
378     private void lockUnavailable(OperationOutcome outcome) {
379
380         // Note: NEVER invoke onStart() for locks; only invoke onComplete()
381         onComplete(outcome);
382
383         /*
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.
386          */
387         cancel();
388     }
389
390     /**
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.
393      *
394      * @param outcome outcome provided to the callback
395      */
396     private void onStart(OperationOutcome outcome) {
397         if (outcome.isFor(actor, operation) || GUARD_ACTOR.equals(outcome.getActor())) {
398             addOutcome(outcome);
399         }
400     }
401
402     /**
403      * Handles responses provided via the "complete" callback. Note: this is never invoked
404      * for "successful" locks.
405      *
406      * @param outcome outcome provided to the callback
407      */
408     private void onComplete(OperationOutcome outcome) {
409
410         switch (outcome.getActor()) {
411             case LOCK_ACTOR:
412             case GUARD_ACTOR:
413             case CL_TIMEOUT_ACTOR:
414                 addOutcome(outcome);
415                 break;
416
417             default:
418                 if (outcome.isFor(actor, operation)) {
419                     addOutcome(outcome);
420                 }
421                 break;
422         }
423     }
424
425     /**
426      * Adds an outcome to {@link #outcomes}.
427      *
428      * @param outcome outcome to be added
429      */
430     private synchronized void addOutcome(OperationOutcome outcome) {
431         /*
432          * This is synchronized to prevent nextStep() from invoking processOutcome() at
433          * the same time.
434          */
435
436         logger.debug("added outcome={} for {}", outcome, requestId);
437         outcomes.add(outcome);
438
439         if (outcomes.peekFirst() == outcomes.peekLast()) {
440             // this is the first outcome in the queue - process it
441             processOutcome();
442         }
443     }
444
445     /**
446      * Looks for the next step in the queue.
447      *
448      * @return {@code true} if more responses are expected, {@code false} otherwise
449      */
450     public synchronized boolean nextStep() {
451         switch (state) {
452             case LOCK_DENIED:
453             case LOCK_LOST:
454             case GUARD_DENIED:
455             case CONTROL_LOOP_TIMEOUT:
456                 holdLast = false;
457                 return false;
458             default:
459                 break;
460         }
461
462         OperationOutcome outcome = outcomes.peek();
463         if (outcome == null) {
464             // empty queue
465             return true;
466         }
467
468         if (outcome.isFinalOutcome() && outcome.isFor(actor, operation)) {
469             controlLoopResponse = null;
470             return false;
471         }
472
473         // first item has been processed, remove it
474         outcomes.remove();
475         if (!outcomes.isEmpty()) {
476             // have a new "first" item - process it
477             processOutcome();
478         }
479
480         return true;
481     }
482
483     /**
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.
486      */
487     private synchronized void processOutcome() {
488         OperationOutcome outcome = outcomes.peek();
489         logger.debug("process outcome={} for {}", outcome, requestId);
490
491         controlLoopResponse = null;
492
493         switch (outcome.getActor()) {
494
495             case CL_TIMEOUT_ACTOR:
496                 state = State.CONTROL_LOOP_TIMEOUT;
497                 processAbort(outcome, OperationResult.FAILURE, "Control loop timed out");
498                 break;
499
500             case LOCK_ACTOR:
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");
505                 } else {
506                     state = State.LOCK_LOST;
507                     processAbort(outcome, OperationResult.FAILURE, "Operation aborted by Lock");
508                 }
509                 break;
510
511             case GUARD_ACTOR:
512                 if (outcome.getEnd() == null) {
513                     state = State.GUARD_STARTED;
514                 } else if (outcome.getResult() == OperationResult.SUCCESS) {
515                     state = State.GUARD_PERMITTED;
516                 } else {
517                     state = State.GUARD_DENIED;
518                     storeFailureInDataBase(outcome, OperationResult.FAILURE_GUARD, "Operation denied by Guard");
519                 }
520                 break;
521
522             default:
523                 if (outcome.getEnd() == null) {
524                     // operation started
525                     ++attempts;
526                     state = State.OPERATION_STARTED;
527
528                 } else {
529                     /*
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.
532                      */
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();
538                     }
539                 }
540
541                 operationHistory.add(new Operation(outcome));
542                 storeOperationInDataBase();
543                 break;
544         }
545
546         // indicate that this has changed
547         operContext.updated(this);
548     }
549
550     /**
551      * Processes an operation abort, updating the DB record, if an operation has been
552      * started.
553      *
554      * @param outcome operation outcome
555      * @param result result to put into the DB
556      * @param message message to put into the DB
557      */
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
561
562             // NOTE: do NOT generate control loop response since operation was not started
563
564             storeFailureInDataBase(outcome, result, message);
565             return;
566         }
567
568         // last item was a "start" operation - replace it with a failure
569         final Operation operOrig = operationHistory.removeLast();
570
571         // use start time from the operation, itself
572         if (operOrig != null && operOrig.getClOperation() != null) {
573             outcome.setStart(operOrig.getClOperation().getStart());
574         }
575
576         controlLoopResponse = makeControlLoopResponse(outcome);
577
578         storeFailureInDataBase(outcome, result, message);
579     }
580
581     /**
582      * Makes a control loop response.
583      *
584      * @param outcome operation outcome
585      * @return a new control loop response, or {@code null} if none is required
586      */
587     protected ControlLoopResponse makeControlLoopResponse(OperationOutcome outcome) {
588
589         // only generate response for certain actors.
590         if (outcome == null || !actor.equals(SdnrActor.NAME)) {
591             return null;
592         }
593
594         VirtualControlLoopEvent event = eventContext.getEvent();
595
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());
604
605         PciMessage msg = outcome.getResponse();
606         if (msg != null && msg.getBody() != null && msg.getBody().getOutput() != null) {
607             clRsp.setPayload(msg.getBody().getOutput().getPayload());
608         }
609
610         return clRsp;
611     }
612
613     /**
614      * Get the operation, as a message.
615      *
616      * @return the operation, as a message
617      */
618     public String getOperationMessage() {
619         Operation last = operationHistory.peekLast();
620         return (last == null ? null : last.getClOperation().toMessage());
621     }
622
623     /**
624      * Gets the operation result.
625      *
626      * @return the operation result
627      */
628     public OperationResult getOperationResult() {
629         Operation last = operationHistory.peekLast();
630         return (last == null ? OperationResult.FAILURE_EXCEPTION : last.getPolicyResult());
631     }
632
633     /**
634      * Get the latest operation history.
635      *
636      * @return the latest operation history
637      */
638     public String getOperationHistory() {
639         Operation last = operationHistory.peekLast();
640         return (last == null ? null : last.clOperation.toHistory());
641     }
642
643     /**
644      * Get the history.
645      *
646      * @return the list of control loop operations
647      */
648     public List<ControlLoopOperation> getHistory() {
649         Operation last = (holdLast ? operationHistory.removeLast() : null);
650
651         List<ControlLoopOperation> result = operationHistory.stream().map(Operation::getClOperation)
652                         .map(ControlLoopOperation::new).collect(Collectors.toList());
653
654         if (last != null) {
655             operationHistory.add(last);
656         }
657
658         return result;
659     }
660
661     /**
662      * Stores a failure in the DB.
663      *
664      * @param outcome operation outcome
665      * @param result result to put into the DB
666      * @param message message to put into the DB
667      */
668     private void storeFailureInDataBase(OperationOutcome outcome, OperationResult result, String message) {
669         // don't include this in history yet
670         holdLast = true;
671
672         outcome.setActor(actor);
673         outcome.setOperation(operation);
674         outcome.setMessage(message);
675         outcome.setResult(result);
676
677         operationHistory.add(new Operation(outcome));
678         storeOperationInDataBase();
679     }
680
681     /**
682      * Stores the latest operation in the DB.
683      */
684     private void storeOperationInDataBase() {
685         operContext.getDataManager().store(requestId, eventContext.getEvent(), targetEntity,
686                         operationHistory.peekLast().getClOperation());
687     }
688
689     /**
690      * Determines the target entity.
691      *
692      * @return a future to determine the target entity, or {@code null} if the entity has
693      *         already been determined
694      */
695     protected CompletableFuture<OperationOutcome> detmTarget() {
696         if (target == null) {
697             throw new IllegalArgumentException("The target is null");
698         }
699
700         if (target.getTargetType() == null) {
701             throw new IllegalArgumentException("The target type is null");
702         }
703
704         switch (TargetType.toTargetType(target.getTargetType())) {
705             case PNF:
706                 return detmPnfTarget();
707             case VM:
708             case VNF:
709             case VFMODULE:
710                 return detmVfModuleTarget();
711             default:
712                 throw new IllegalArgumentException("The target type is not supported");
713         }
714     }
715
716     /**
717      * Determines the PNF target entity.
718      *
719      * @return a future to determine the target entity, or {@code null} if the entity has
720      *         already been determined
721      */
722     private CompletableFuture<OperationOutcome> detmPnfTarget() {
723         if (!PNF_NAME.equalsIgnoreCase(eventContext.getEvent().getTarget())) {
724             throw new IllegalArgumentException("Target does not match target type");
725         }
726
727         targetEntity = eventContext.getEnrichment().get(PNF_NAME);
728         if (targetEntity == null) {
729             throw new IllegalArgumentException("AAI section is missing " + PNF_NAME);
730         }
731
732         return null;
733     }
734
735     /**
736      * Determines the VF Module target entity.
737      *
738      * @return a future to determine the target entity, or {@code null} if the entity has
739      *         already been determined
740      */
741     private CompletableFuture<OperationOutcome> detmVfModuleTarget() {
742         String targetFieldName = eventContext.getEvent().getTarget();
743         if (targetFieldName == null) {
744             throw new IllegalArgumentException("Target is null");
745         }
746
747         switch (targetFieldName.toLowerCase()) {
748             case VSERVER_VSERVER_NAME:
749                 targetEntity = eventContext.getEnrichment().get(VSERVER_VSERVER_NAME);
750                 break;
751             case GENERIC_VNF_VNF_ID:
752                 targetEntity = eventContext.getEnrichment().get(GENERIC_VNF_VNF_ID);
753                 break;
754             case GENERIC_VNF_VNF_NAME:
755                 return detmVnfName();
756             default:
757                 throw new IllegalArgumentException("Target does not match target type");
758         }
759
760         if (targetEntity == null) {
761             throw new IllegalArgumentException("Enrichment data is missing " + targetFieldName);
762         }
763
764         return null;
765     }
766
767     /**
768      * Determines the VNF Name target entity.
769      *
770      * @return a future to determine the target entity, or {@code null} if the entity has
771      *         already been determined
772      */
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) {
778             return null;
779         }
780
781         // vnf-id was not in the onset - obtain it via the custom query
782
783         // @formatter:off
784         ControlLoopOperationParams cqparams = params.toBuilder()
785                         .actor(AaiConstants.ACTOR_NAME)
786                         .operation(AaiCqResponse.OPERATION)
787                         .targetEntity("")
788                         .build();
789         // @formatter:on
790
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);
794     }
795
796     /**
797      * Extracts the VNF Name target entity from the custom query data.
798      *
799      * @return {@code null}
800      */
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");
806         }
807
808         targetEntity = cq.getDefaultGenericVnf().getVnfId();
809         if (targetEntity == null) {
810             throw new IllegalArgumentException("No vnf-id found");
811         }
812
813         return null;
814     }
815 }