Remove targetEntity from makeOutcome
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / parameters / ControlLoopOperationParams.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 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.actorserviceprovider.parameters;
22
23 import java.util.Map;
24 import java.util.UUID;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.concurrent.Executor;
27 import java.util.concurrent.ForkJoinPool;
28 import java.util.function.Consumer;
29 import lombok.AllArgsConstructor;
30 import lombok.Builder;
31 import lombok.EqualsAndHashCode;
32 import lombok.Getter;
33 import org.onap.policy.common.parameters.BeanValidationResult;
34 import org.onap.policy.common.parameters.BeanValidator;
35 import org.onap.policy.common.parameters.annotations.NotNull;
36 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
37 import org.onap.policy.controlloop.actorserviceprovider.Operation;
38 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
39 import org.onap.policy.controlloop.actorserviceprovider.TargetType;
40 import org.onap.policy.controlloop.actorserviceprovider.Util;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Parameters for control loop operations. The executor defaults to
46  * {@link ForkJoinPool#commonPool()}, but may be overridden.
47  */
48 @Getter
49 @Builder(toBuilder = true)
50 @AllArgsConstructor
51 @EqualsAndHashCode
52 public class ControlLoopOperationParams {
53     private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationParams.class);
54
55     /*
56      * Optional keys within the "targetEntityIds" map.
57      */
58     public static final String PARAMS_ENTITY_RESOURCEID = "resourceID";
59     public static final String PARAMS_ENTITY_MODEL_INVARIANT_ID = "modelInvariantId";
60     public static final String PARAMS_ENTITY_MODEL_VERSION_ID = "modelVersionId";
61     public static final String PARAMS_ENTITY_MODEL_NAME = "modelName";
62     public static final String PARAMS_ENTITY_MODEL_VERSION = "modelVersion";
63     public static final String PARAMS_ENTITY_MODEL_CUSTOMIZATION_ID = "modelCustomizationId";
64
65     /**
66      * Actor name.
67      */
68     @NotNull
69     private String actor;
70
71     /**
72      * Actor service in which to find the actor/operation.
73      */
74     @NotNull
75     private ActorService actorService;
76
77     /**
78      * Request ID with which all actor operations are associated. Used to track requests
79      * across various components/servers.
80      */
81     @NotNull
82     private UUID requestId;
83
84     /**
85      * Executor to use to run the operation.
86      */
87     @NotNull
88     @Builder.Default
89     private Executor executor = ForkJoinPool.commonPool();
90
91     /**
92      * Operation name.
93      */
94     @NotNull
95     private String operation;
96
97     /**
98      * Payload data for the request.
99      */
100     private Map<String, Object> payload;
101
102     /**
103      * Number of retries allowed, or {@code null} if no retries.
104      */
105     private Integer retry;
106
107     /**
108      * The Target Type information, extracted from the Policy. May be {@code null}, depending
109      * on the requirement of the operation to be invoked.
110      */
111     private TargetType targetType;
112
113     /**
114      * Target entitiy ids, extracted from the Policy. May be (@code null}, depending on
115      * the requirement of the operation to be invoked.
116      */
117     private Map<String, String> targetEntityIds;
118
119     /**
120      * Timeout, in seconds, or {@code null} if no timeout. Zero and negative values also
121      * imply no timeout.
122      */
123     @Builder.Default
124     private Integer timeoutSec = 300;
125
126     /**
127      * The function to invoke when the operation starts. This is optional.
128      * <p/>
129      * Note: this may be invoked multiple times, but with different actor/operations. That
130      * may happen if the current operation requires other operations to be performed first
131      * (e.g., A&AI queries, guard checks).
132      */
133     private Consumer<OperationOutcome> startCallback;
134
135     /**
136      * The function to invoke when the operation completes. This is optional.
137      * <p/>
138      * Note: this may be invoked multiple times, but with different actor/operations. That
139      * may happen if the current operation requires other operations to be performed first
140      * (e.g., A&AI queries, guard checks).
141      */
142     private Consumer<OperationOutcome> completeCallback;
143
144     /**
145      * Starts the specified operation.
146      *
147      * @return a future that will return the result of the operation
148      * @throws IllegalArgumentException if the parameters are invalid
149      */
150     public CompletableFuture<OperationOutcome> start() {
151         return build().start();
152     }
153
154     /**
155      * Builds the specified operation.
156      *
157      * @return a new operation
158      * @throws IllegalArgumentException if the parameters are invalid
159      */
160     public Operation build() {
161         BeanValidationResult result = validate();
162         if (!result.isValid()) {
163             logger.warn("parameter error in operation {}.{} for {}:\n{}", getActor(), getOperation(), getRequestId(),
164                             result.getResult());
165             throw new IllegalArgumentException("invalid parameters");
166         }
167
168         // @formatter:off
169         return actorService
170                     .getActor(getActor())
171                     .getOperator(getOperation())
172                     .buildOperation(this);
173         // @formatter:on
174     }
175
176     /**
177      * Gets the requested ID of the associated event.
178      *
179      * @return the event's request ID, or {@code null} if no request ID is available
180      */
181     public UUID getRequestId() {
182         return requestId;
183     }
184
185     /**
186      * Makes an operation outcome, populating it from the parameters.
187      *
188      * @return a new operation outcome
189      */
190     public OperationOutcome makeOutcome() {
191         OperationOutcome outcome = new OperationOutcome();
192         outcome.setActor(getActor());
193         outcome.setOperation(getOperation());
194
195         return outcome;
196     }
197
198     /**
199      * Invokes the callback to indicate that the operation has started. Any exceptions
200      * generated by the callback are logged, but not re-thrown.
201      *
202      * @param operation the operation that is being started
203      */
204     public void callbackStarted(OperationOutcome operation) {
205         logger.info("started operation {}.{} for {}", operation.getActor(), operation.getOperation(), getRequestId());
206
207         if (startCallback != null) {
208             Util.runFunction(() -> startCallback.accept(operation), "{}.{}: start-callback threw an exception for {}",
209                             operation.getActor(), operation.getOperation(), getRequestId());
210         }
211     }
212
213     /**
214      * Invokes the callback to indicate that the operation has completed. Any exceptions
215      * generated by the callback are logged, but not re-thrown.
216      *
217      * @param operation the operation that is being started
218      */
219     public void callbackCompleted(OperationOutcome operation) {
220         logger.info("completed operation {}.{} outcome={} for {}", operation.getActor(), operation.getOperation(),
221                         operation.getResult(), getRequestId());
222
223         if (completeCallback != null) {
224             Util.runFunction(() -> completeCallback.accept(operation),
225                             "{}.{}: complete-callback threw an exception for {}", operation.getActor(),
226                             operation.getOperation(), getRequestId());
227         }
228     }
229
230     /**
231      * Validates the parameters.
232      *
233      * @return the validation result
234      */
235     public BeanValidationResult validate() {
236         return new BeanValidator().validateTop(ControlLoopOperationParams.class.getSimpleName(), this);
237     }
238 }