b738cefe109a1a776746c84ab4f2f188e119e1a7
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.eventmanager;
22
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;
26
27 import java.io.Serializable;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.LinkedList;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.UUID;
34 import java.util.concurrent.CompletableFuture;
35 import java.util.concurrent.Executor;
36 import java.util.concurrent.ExecutorService;
37 import java.util.concurrent.ForkJoinPool;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.atomic.AtomicLong;
40 import java.util.concurrent.atomic.AtomicReference;
41 import java.util.function.Consumer;
42 import java.util.stream.Collectors;
43 import java.util.stream.Stream;
44 import lombok.Getter;
45 import lombok.ToString;
46 import org.apache.commons.lang3.StringUtils;
47 import org.onap.policy.controlloop.ControlLoopEventStatus;
48 import org.onap.policy.controlloop.ControlLoopException;
49 import org.onap.policy.controlloop.ControlLoopNotificationType;
50 import org.onap.policy.controlloop.ControlLoopOperation;
51 import org.onap.policy.controlloop.ControlLoopResponse;
52 import org.onap.policy.controlloop.VirtualControlLoopEvent;
53 import org.onap.policy.controlloop.VirtualControlLoopNotification;
54 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
55 import org.onap.policy.controlloop.actorserviceprovider.OperationFinalResult;
56 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
57 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
58 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
59 import org.onap.policy.controlloop.ophistory.OperationHistoryDataManager;
60 import org.onap.policy.controlloop.processor.ControlLoopProcessor;
61 import org.onap.policy.drools.core.lock.LockCallback;
62 import org.onap.policy.drools.domain.models.operational.Operation;
63 import org.onap.policy.drools.system.PolicyEngineConstants;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 /**
68  * Manager for a single control loop event. Once this has been created, the event can be
69  * retracted from working memory. Once this has been created, {@link #start()} should be
70  * invoked, and then {@link #nextStep()} should be invoked continually until
71  * {@link #isActive()} returns {@code false}, indicating that all steps have completed.
72  */
73 @ToString(onlyExplicitlyIncluded = true)
74 public abstract class ControlLoopEventManager2 implements ManagerContext, Serializable {
75     private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager2.class);
76     private static final long serialVersionUID = -1216568161322872641L;
77
78     private static final String EVENT_MANAGER_SERVICE_CONFIG = "event-manager";
79     public static final String PROV_STATUS_ACTIVE = "ACTIVE";
80     private static final String VM_NAME = "VM_NAME";
81     private static final String VNF_NAME = "VNF_NAME";
82     public static final String GENERIC_VNF_VNF_ID = "generic-vnf.vnf-id";
83     public static final String GENERIC_VNF_VNF_NAME = "generic-vnf.vnf-name";
84     public static final String VSERVER_VSERVER_NAME = "vserver.vserver-name";
85     public static final String GENERIC_VNF_IS_CLOSED_LOOP_DISABLED = "generic-vnf.is-closed-loop-disabled";
86     public static final String VSERVER_IS_CLOSED_LOOP_DISABLED = "vserver.is-closed-loop-disabled";
87     public static final String PNF_IS_IN_MAINT = "pnf.in-maint";
88     public static final String GENERIC_VNF_PROV_STATUS = "generic-vnf.prov-status";
89     public static final String VSERVER_PROV_STATUS = "vserver.prov-status";
90     public static final String PNF_ID = "pnf.pnf-id";
91     public static final String PNF_NAME = "pnf.pnf-name";
92
93     private static final Set<String> VALID_TARGETS = Stream
94                     .of(VM_NAME, VNF_NAME, VSERVER_VSERVER_NAME, GENERIC_VNF_VNF_ID, GENERIC_VNF_VNF_NAME, PNF_NAME)
95                     .map(String::toLowerCase).collect(Collectors.toSet());
96
97     private static final Set<String> TRUE_VALUES = Set.of("true", "t", "yes", "y");
98
99     /**
100      * Counts the number of these objects that have been created.  This is used by junit
101      * tests.
102      */
103     private static final AtomicLong createCount = new AtomicLong(0);
104
105     public enum NewEventStatus {
106         FIRST_ONSET, SUBSEQUENT_ONSET, FIRST_ABATEMENT, SUBSEQUENT_ABATEMENT, SYNTAX_ERROR
107     }
108
109     /**
110      * {@code True} if this object was created by this JVM instance, {@code false}
111      * otherwise. This will be {@code false} if this object is reconstituted from a
112      * persistent store or by transfer from another server.
113      */
114     private transient boolean createdByThisJvmInstance;
115
116     @Getter
117     @ToString.Include
118     public final String closedLoopControlName;
119     @Getter
120     @ToString.Include
121     private final UUID requestId;
122     @Getter
123     private final ControlLoopEventContext context;
124     @ToString.Include
125     private int numOnsets = 1;
126     @ToString.Include
127     private int numAbatements = 0;
128     private VirtualControlLoopEvent abatement = null;
129
130     /**
131      * Time, in milliseconds, when the control loop will time out.
132      */
133     @Getter
134     private final long endTimeMs;
135
136     // fields extracted from the ControlLoopParams
137     @Getter
138     private final String policyName;
139     private final String policyScope;
140     private final String policyVersion;
141
142     private final LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
143
144     /**
145      * Maps a target entity to its lock.
146      */
147     private final transient Map<String, LockData> target2lock = new HashMap<>();
148
149     private final ControlLoopProcessor processor;
150     private final AtomicReference<ControlLoopOperationManager2> currentOperation = new AtomicReference<>();
151
152     private OperationFinalResult finalResult = null;
153
154     @Getter
155     private VirtualControlLoopNotification notification;
156     @Getter
157     private ControlLoopResponse controlLoopResponse;
158
159     @Getter
160     private boolean updated = false;
161
162
163     /**
164      * Constructs the object.
165      *
166      * @param params control loop parameters
167      * @param event event to be managed by this object
168      * @throws ControlLoopException if the event is invalid or if a YAML processor cannot
169      *         be created
170      */
171     public ControlLoopEventManager2(ControlLoopParams params, VirtualControlLoopEvent event)
172                     throws ControlLoopException {
173
174         createCount.incrementAndGet();
175
176         checkEventSyntax(event);
177
178         if (isClosedLoopDisabled(event)) {
179             throw new IllegalStateException("is-closed-loop-disabled is set to true on VServer or VNF");
180         }
181
182         if (isProvStatusInactive(event)) {
183             throw new IllegalStateException("prov-status is not ACTIVE on VServer or VNF");
184         }
185
186         this.createdByThisJvmInstance = true;
187         this.closedLoopControlName = params.getClosedLoopControlName();
188         this.requestId = event.getRequestId();
189         this.context = new ControlLoopEventContext(event);
190         this.policyName = params.getPolicyName();
191         this.policyScope = params.getPolicyScope();
192         this.policyVersion = params.getPolicyVersion();
193         this.processor = new ControlLoopProcessor(params.getToscaPolicy());
194         this.endTimeMs = System.currentTimeMillis() + detmControlLoopTimeoutMs();
195     }
196
197     /**
198      * Gets the number of managers objects that have been created.
199      * @return the number of managers objects that have been created
200      */
201     public static long getCreateCount() {
202         return createCount.get();
203     }
204
205     /**
206      * Starts the manager.
207      *
208      * @throws ControlLoopException if the processor cannot get a policy
209      */
210     public void start() throws ControlLoopException {
211         if (!isActive()) {
212             throw new IllegalStateException("manager is no longer active");
213         }
214
215         startHook();
216
217         if (currentOperation.get() != null) {
218             throw new IllegalStateException("manager already started");
219         }
220
221         startOperation();
222     }
223
224     /**
225      * Starts an operation for the current processor policy.
226      *
227      * @throws ControlLoopException if the processor cannot get a policy
228      */
229     private synchronized void startOperation() throws ControlLoopException {
230
231         if ((finalResult = processor.checkIsCurrentPolicyFinal()) == null) {
232             // not final - start the next operation
233             currentOperation.set(makeOperationManager(context, processor.getCurrentPolicy()));
234             currentOperation.get().start(endTimeMs - System.currentTimeMillis());
235             return;
236         }
237
238         logger.info("final={} oper state={} for {}", finalResult, currentOperation.get().getState(), requestId);
239
240         controlLoopResponse = null;
241         notification = makeNotification();
242         notification.setHistory(controlLoopHistory);
243
244         switch (finalResult) {
245             case FINAL_FAILURE_EXCEPTION:
246                 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
247                 notification.setMessage("Exception in processing closed loop");
248                 break;
249             case FINAL_SUCCESS:
250                 notification.setNotification(ControlLoopNotificationType.FINAL_SUCCESS);
251                 break;
252             case FINAL_OPENLOOP:
253                 notification.setNotification(ControlLoopNotificationType.FINAL_OPENLOOP);
254                 break;
255             case FINAL_FAILURE:
256             default:
257                 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
258                 break;
259         }
260     }
261
262     /**
263      * Starts the next step, whatever that may be.
264      */
265     public synchronized void nextStep() {
266         if (!isActive()) {
267             return;
268         }
269
270         updated = false;
271
272         try {
273             if (!currentOperation.get().nextStep()) {
274                 // current operation is done - try the next
275                 controlLoopHistory.addAll(currentOperation.get().getHistory());
276                 processor.nextPolicyForResult(currentOperation.get().getOperationResult());
277                 startOperation();
278             }
279
280         } catch (ControlLoopException | RuntimeException e) {
281             // processor problem - this is fatal
282             logger.warn("{}: cannot start next step for {}", closedLoopControlName, requestId, e);
283             finalResult = OperationFinalResult.FINAL_FAILURE_EXCEPTION;
284             controlLoopResponse = null;
285             notification = makeNotification();
286             notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
287             notification.setMessage("Policy processing aborted due to policy error");
288             notification.setHistory(controlLoopHistory);
289         }
290     }
291
292     /**
293      * Determines if the manager is still active.
294      *
295      * @return {@code true} if the manager is still active, {@code false} otherwise
296      */
297     public synchronized boolean isActive() {
298         return (createdByThisJvmInstance && finalResult == null);
299     }
300
301     /**
302      * Updates working memory if this changes.
303      *
304      * @param operation operation manager that was updated
305      */
306     @Override
307     public synchronized void updated(ControlLoopOperationManager2 operation) {
308         if (!isActive() || operation != currentOperation.get()) {
309             // no longer working on the given operation
310             return;
311         }
312
313         controlLoopResponse = operation.getControlLoopResponse();
314         notification = makeNotification();
315
316         VirtualControlLoopEvent event = context.getEvent();
317
318         switch (operation.getState()) {
319             case LOCK_DENIED:
320                 notification.setNotification(ControlLoopNotificationType.REJECTED);
321                 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is already locked");
322                 break;
323             case LOCK_LOST:
324                 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
325                 notification.setMessage("The target " + event.getAai().get(event.getTarget()) + " is no longer locked");
326                 break;
327             case GUARD_STARTED:
328                 notification.setNotification(ControlLoopNotificationType.OPERATION);
329                 notification.setMessage(
330                                 "Sending guard query for " + operation.getActor() + " " + operation.getOperation());
331                 break;
332             case GUARD_PERMITTED:
333                 notification.setNotification(ControlLoopNotificationType.OPERATION);
334                 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
335                                 + " is Permit");
336                 break;
337             case GUARD_DENIED:
338                 notification.setNotification(ControlLoopNotificationType.OPERATION);
339                 notification.setMessage("Guard result for " + operation.getActor() + " " + operation.getOperation()
340                                 + " is Deny");
341                 break;
342             case OPERATION_STARTED:
343                 notification.setNotification(ControlLoopNotificationType.OPERATION);
344                 notification.setMessage(operation.getOperationMessage());
345                 notification.setHistory(Collections.emptyList());
346                 break;
347             case OPERATION_SUCCESS:
348                 notification.setNotification(ControlLoopNotificationType.OPERATION_SUCCESS);
349                 break;
350
351             case CONTROL_LOOP_TIMEOUT:
352                 logger.warn("{}: control loop timed out for {}", closedLoopControlName, requestId);
353                 controlLoopHistory.addAll(currentOperation.get().getHistory());
354                 notification.setNotification(ControlLoopNotificationType.FINAL_FAILURE);
355                 notification.setMessage("Control Loop timed out");
356                 notification.setHistory(controlLoopHistory);
357                 finalResult = OperationFinalResult.FINAL_FAILURE;
358                 break;
359
360             case OPERATION_FAILURE:
361             default:
362                 notification.setNotification(ControlLoopNotificationType.OPERATION_FAILURE);
363                 break;
364         }
365
366         updated = true;
367         notifyUpdate();
368     }
369
370     /**
371      * Cancels the current operation and frees all locks.
372      */
373     public synchronized void destroy() {
374         ControlLoopOperationManager2 oper = currentOperation.get();
375         if (oper != null) {
376             oper.cancel();
377         }
378
379         getBlockingExecutor().execute(this::freeAllLocks);
380     }
381
382     /**
383      * Frees all locks.
384      */
385     private void freeAllLocks() {
386         target2lock.values().forEach(LockData::free);
387     }
388
389     /**
390      * Makes a notification message for the current operation.
391      *
392      * @return a new notification
393      */
394     public synchronized VirtualControlLoopNotification makeNotification() {
395         VirtualControlLoopNotification notif = new VirtualControlLoopNotification(context.getEvent());
396         notif.setNotification(ControlLoopNotificationType.OPERATION);
397         notif.setFrom("policy");
398         notif.setPolicyScope(policyScope);
399         notif.setPolicyVersion(policyVersion);
400
401         if (finalResult == null) {
402             ControlLoopOperationManager2 oper = currentOperation.get();
403             if (oper != null) {
404                 notif.setMessage(oper.getOperationHistory());
405                 notif.setHistory(oper.getHistory());
406             }
407         }
408
409         return notif;
410     }
411
412     /**
413      * An event onset/abatement.
414      *
415      * @param event the event
416      * @return the status
417      */
418     public synchronized NewEventStatus onNewEvent(VirtualControlLoopEvent event) {
419         try {
420             checkEventSyntax(event);
421
422             if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ONSET) {
423                 if (event.equals(context.getEvent())) {
424                     return NewEventStatus.FIRST_ONSET;
425                 }
426
427                 numOnsets++;
428                 return NewEventStatus.SUBSEQUENT_ONSET;
429
430             } else {
431                 if (abatement == null) {
432                     abatement = event;
433                     numAbatements++;
434                     return NewEventStatus.FIRST_ABATEMENT;
435                 } else {
436                     numAbatements++;
437                     return NewEventStatus.SUBSEQUENT_ABATEMENT;
438                 }
439             }
440         } catch (ControlLoopException e) {
441             logger.error("{}: onNewEvent threw an exception", this, e);
442             return NewEventStatus.SYNTAX_ERROR;
443         }
444     }
445
446     /**
447      * Determines the overall control loop timeout.
448      *
449      * @return the policy timeout, in milliseconds, if specified, a default timeout
450      *         otherwise
451      */
452     private long detmControlLoopTimeoutMs() {
453         // validation checks preclude null or 0 timeout values in the policy
454         Integer timeout = processor.getPolicy().getProperties().getTimeout();
455         return TimeUnit.MILLISECONDS.convert(timeout, TimeUnit.SECONDS);
456     }
457
458     /**
459      * Check an event syntax.
460      *
461      * @param event the event syntax
462      * @throws ControlLoopException if an error occurs
463      */
464     protected void checkEventSyntax(VirtualControlLoopEvent event) throws ControlLoopException {
465         validateStatus(event);
466         if (StringUtils.isBlank(event.getClosedLoopControlName())) {
467             throw new ControlLoopException("No control loop name");
468         }
469         if (event.getRequestId() == null) {
470             throw new ControlLoopException("No request ID");
471         }
472         if (event.getClosedLoopEventStatus() == ControlLoopEventStatus.ABATED) {
473             return;
474         }
475         if (StringUtils.isBlank(event.getTarget())) {
476             throw new ControlLoopException("No target field");
477         } else if (!VALID_TARGETS.contains(event.getTarget().toLowerCase())) {
478             throw new ControlLoopException("target field invalid");
479         }
480         validateAaiData(event);
481     }
482
483     private void validateStatus(VirtualControlLoopEvent event) throws ControlLoopException {
484         if (event.getClosedLoopEventStatus() != ControlLoopEventStatus.ONSET
485                         && event.getClosedLoopEventStatus() != ControlLoopEventStatus.ABATED) {
486             throw new ControlLoopException("Invalid value in closedLoopEventStatus");
487         }
488     }
489
490     private void validateAaiData(VirtualControlLoopEvent event) throws ControlLoopException {
491         Map<String, String> eventAai = event.getAai();
492         if (eventAai == null) {
493             throw new ControlLoopException("AAI is null");
494         }
495         if (event.getTargetType() == null) {
496             throw new ControlLoopException("The Target type is null");
497         }
498         switch (event.getTargetType()) {
499             case VM:
500             case VNF:
501                 validateAaiVmVnfData(eventAai);
502                 return;
503             case PNF:
504                 validateAaiPnfData(eventAai);
505                 return;
506             default:
507                 throw new ControlLoopException("The target type is not supported");
508         }
509     }
510
511     private void validateAaiVmVnfData(Map<String, String> eventAai) throws ControlLoopException {
512         if (eventAai.get(GENERIC_VNF_VNF_ID) == null && eventAai.get(VSERVER_VSERVER_NAME) == null
513                         && eventAai.get(GENERIC_VNF_VNF_NAME) == null) {
514             throw new ControlLoopException(
515                             "generic-vnf.vnf-id or generic-vnf.vnf-name or vserver.vserver-name information missing");
516         }
517     }
518
519     private void validateAaiPnfData(Map<String, String> eventAai) throws ControlLoopException {
520         if (eventAai.get(PNF_NAME) == null) {
521             throw new ControlLoopException("AAI PNF object key pnf-name is missing");
522         }
523     }
524
525     /**
526      * Is closed loop disabled for an event.
527      *
528      * @param event the event
529      * @return <code>true</code> if the control loop is disabled, <code>false</code>
530      *         otherwise
531      */
532     private static boolean isClosedLoopDisabled(VirtualControlLoopEvent event) {
533         Map<String, String> aai = event.getAai();
534         return (isAaiTrue(aai.get(VSERVER_IS_CLOSED_LOOP_DISABLED))
535                         || isAaiTrue(aai.get(GENERIC_VNF_IS_CLOSED_LOOP_DISABLED))
536                         || isAaiTrue(aai.get(PNF_IS_IN_MAINT)));
537     }
538
539     /**
540      * Does provisioning status, for an event, have a value other than ACTIVE.
541      *
542      * @param event the event
543      * @return {@code true} if the provisioning status is neither ACTIVE nor {@code null},
544      *         {@code false} otherwise
545      */
546     private static boolean isProvStatusInactive(VirtualControlLoopEvent event) {
547         Map<String, String> aai = event.getAai();
548         return !(PROV_STATUS_ACTIVE.equals(aai.getOrDefault(VSERVER_PROV_STATUS, PROV_STATUS_ACTIVE))
549                         && PROV_STATUS_ACTIVE.equals(aai.getOrDefault(GENERIC_VNF_PROV_STATUS, PROV_STATUS_ACTIVE)));
550     }
551
552     /**
553      * Determines the boolean value represented by the given AAI field value.
554      *
555      * @param aaiValue value to be examined
556      * @return the boolean value represented by the field value, or {@code false} if the
557      *         value is {@code null}
558      */
559     private static boolean isAaiTrue(String aaiValue) {
560         return (aaiValue != null && TRUE_VALUES.contains(aaiValue.toLowerCase()));
561     }
562
563     /**
564      * Requests a lock. This requests the lock for the time that remains before the
565      * timeout expires. This avoids having to extend the lock.
566      *
567      * @param targetEntity entity to be locked
568      * @param lockUnavailableCallback function to be invoked if the lock is
569      *        unavailable/lost
570      * @return a future that can be used to await the lock
571      */
572     @Override
573     public synchronized CompletableFuture<OperationOutcome> requestLock(String targetEntity,
574                     Consumer<OperationOutcome> lockUnavailableCallback) {
575
576         long remainingMs = endTimeMs - System.currentTimeMillis();
577         int remainingSec = 15 + Math.max(0, (int) TimeUnit.SECONDS.convert(remainingMs, TimeUnit.MILLISECONDS));
578
579         LockData data = target2lock.computeIfAbsent(targetEntity, key -> {
580             LockData data2 = new LockData(key, requestId);
581             makeLock(targetEntity, requestId.toString(), remainingSec, data2);
582             return data2;
583         });
584
585         data.addUnavailableCallback(lockUnavailableCallback);
586
587         return data.getFuture();
588     }
589
590     /**
591      * Initializes various components, on demand.
592      */
593     private static class LazyInitData {
594         private static final OperationHistoryDataManager DATA_MANAGER;
595         private static final ActorService ACTOR_SERVICE;
596
597         static {
598             EventManagerServices services = new EventManagerServices(EVENT_MANAGER_SERVICE_CONFIG);
599             ACTOR_SERVICE = services.getActorService();
600             DATA_MANAGER = services.getDataManager();
601         }
602     }
603
604     // the following methods may be overridden by junit tests
605
606     protected ControlLoopOperationManager2 makeOperationManager(ControlLoopEventContext ctx, Operation operation) {
607         return new ControlLoopOperationManager2(this, ctx, operation, getExecutor());
608     }
609
610     protected Executor getExecutor() {
611         return ForkJoinPool.commonPool();
612     }
613
614     protected ExecutorService getBlockingExecutor() {
615         return PolicyEngineConstants.getManager().getExecutorService();
616     }
617
618     protected void makeLock(String targetEntity, String requestId, int holdSec, LockCallback callback) {
619         PolicyEngineConstants.getManager().createLock(targetEntity, requestId, holdSec, callback, false);
620     }
621
622     @Override
623     public ActorService getActorService() {
624         return LazyInitData.ACTOR_SERVICE;
625     }
626
627     @Override
628     public OperationHistoryDataManager getDataManager() {
629         return LazyInitData.DATA_MANAGER;
630     }
631
632     /* ============================================================ */
633
634     /**
635      * This is a method, invoked from the 'start' method -- it gives subclasses
636      * the ability to add operations. The default implementation does nothing.
637      */
638     protected void startHook() {
639     }
640
641     /**
642      * This is an abstract method that is called after a notable update has
643      * occurred to the 'ControlLoopEventManager2' object. It gives subclasses
644      * the ability to add a callback method to process state changes.
645      */
646     protected abstract void notifyUpdate();
647 }