Merge "Adding 'name' to yamls and json in model"
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / impl / HttpOperation.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.impl;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.concurrent.CompletableFuture;
26 import java.util.concurrent.Executor;
27 import java.util.concurrent.Future;
28 import java.util.concurrent.TimeUnit;
29 import java.util.function.Function;
30 import javax.ws.rs.client.InvocationCallback;
31 import javax.ws.rs.core.Response;
32 import lombok.Getter;
33 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
34 import org.onap.policy.common.endpoints.http.client.HttpClient;
35 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
36 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
37 import org.onap.policy.common.utils.coder.CoderException;
38 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
42 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
43 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
44 import org.onap.policy.controlloop.policy.PolicyResult;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Operator that uses HTTP. The operator's parameters must be an {@link HttpParams}.
50  *
51  * @param <T> response type
52  */
53 @Getter
54 public abstract class HttpOperation<T> extends OperationPartial {
55     private static final Logger logger = LoggerFactory.getLogger(HttpOperation.class);
56
57     /**
58      * Response status.
59      */
60     public enum Status {
61         SUCCESS, FAILURE, STILL_WAITING
62     }
63
64     /**
65      * Configuration for this operation.
66      */
67     private final HttpConfig config;
68
69     /**
70      * Response class.
71      */
72     private final Class<T> responseClass;
73
74     /**
75      * {@code True} to use polling, {@code false} otherwise.
76      */
77     @Getter
78     private boolean usePolling;
79
80     /**
81      * Number of polls issued so far, on the current operation attempt.
82      */
83     @Getter
84     private int pollCount;
85
86
87     /**
88      * Constructs the object.
89      *
90      * @param params operation parameters
91      * @param config configuration for this operation
92      * @param clazz response class
93      */
94     public HttpOperation(ControlLoopOperationParams params, HttpConfig config, Class<T> clazz) {
95         super(params, config);
96         this.config = config;
97         this.responseClass = clazz;
98     }
99
100     /**
101      * Indicates that polling should be used.
102      */
103     protected void setUsePolling() {
104         if (!(config instanceof HttpPollingConfig)) {
105             throw new IllegalStateException("cannot poll without polling parameters");
106         }
107
108         usePolling = true;
109     }
110
111     public HttpClient getClient() {
112         return config.getClient();
113     }
114
115     /**
116      * Gets the path to be used when performing the request; this is typically appended to
117      * the base URL. This method simply invokes {@link #getPath()}.
118      *
119      * @return the path URI suffix
120      */
121     public String getPath() {
122         return config.getPath();
123     }
124
125     public long getTimeoutMs() {
126         return config.getTimeoutMs();
127     }
128
129     /**
130      * If no timeout is specified, then it returns the operator's configured timeout.
131      */
132     @Override
133     protected long getTimeoutMs(Integer timeoutSec) {
134         return (timeoutSec == null || timeoutSec == 0 ? getTimeoutMs() : super.getTimeoutMs(timeoutSec));
135     }
136
137     /**
138      * Makes the request headers. This simply returns an empty map.
139      *
140      * @return request headers, a non-null, modifiable map
141      */
142     protected Map<String, Object> makeHeaders() {
143         return new HashMap<>();
144     }
145
146     /**
147      * Makes the URL to which the HTTP request should be posted. This is primarily used
148      * for logging purposes. This particular method returns the base URL appended with the
149      * return value from {@link #getPath()}.
150      *
151      * @return the URL to which from which to get
152      */
153     public String getUrl() {
154         return (getClient().getBaseUrl() + getPath());
155     }
156
157     /**
158      * Resets the polling count
159      *
160      * <p/>
161      * Note: This should be invoked at the start of each operation (i.e., in
162      * {@link #startOperationAsync(int, OperationOutcome)}.
163      */
164     protected void resetPollCount() {
165         pollCount = 0;
166     }
167
168     /**
169      * Arranges to handle a response.
170      *
171      * @param outcome outcome to be populate
172      * @param url URL to which to request was sent
173      * @param requester function to initiate the request and invoke the given callback
174      *        when it completes
175      * @return a future for the response
176      */
177     protected CompletableFuture<OperationOutcome> handleResponse(OperationOutcome outcome, String url,
178                     Function<InvocationCallback<Response>, Future<Response>> requester) {
179
180         final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
181         final CompletableFuture<Response> future = new CompletableFuture<>();
182         final Executor executor = params.getExecutor();
183
184         // arrange for the callback to complete "future"
185         InvocationCallback<Response> callback = new InvocationCallback<>() {
186             @Override
187             public void completed(Response response) {
188                 future.complete(response);
189             }
190
191             @Override
192             public void failed(Throwable throwable) {
193                 logger.warn("{}.{}: response failure for {}", params.getActor(), params.getOperation(),
194                                 params.getRequestId());
195                 future.completeExceptionally(throwable);
196             }
197         };
198
199         // start the request and arrange to cancel it if the controller is canceled
200         controller.add(requester.apply(callback));
201
202         // once "future" completes, process the response, and then complete the controller
203         future.thenComposeAsync(response -> processResponse(outcome, url, response), executor)
204                         .whenCompleteAsync(controller.delayedComplete(), executor);
205
206         return controller;
207     }
208
209     /**
210      * Processes a response. This method decodes the response, sets the outcome based on
211      * the response, and then returns a completed future.
212      *
213      * @param outcome outcome to be populate
214      * @param url URL to which to request was sent
215      * @param response raw response to process
216      * @return a future to cancel or await the outcome
217      */
218     protected CompletableFuture<OperationOutcome> processResponse(OperationOutcome outcome, String url,
219                     Response rawResponse) {
220
221         logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
222
223         String strResponse = rawResponse.readEntity(String.class);
224
225         logMessage(EventType.IN, CommInfrastructure.REST, url, strResponse);
226
227         T response;
228         if (responseClass == String.class) {
229             response = responseClass.cast(strResponse);
230         } else {
231             try {
232                 response = getCoder().decode(strResponse, responseClass);
233             } catch (CoderException e) {
234                 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
235                                 params.getRequestId(), e);
236                 throw new IllegalArgumentException("cannot decode response");
237             }
238         }
239
240         if (!isSuccess(rawResponse, response)) {
241             logger.info("{}.{} request failed with http error code {} for {}", params.getActor(), params.getOperation(),
242                             rawResponse.getStatus(), params.getRequestId());
243             return CompletableFuture.completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
244         }
245
246         logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(), params.getRequestId());
247         setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response);
248         return postProcessResponse(outcome, url, rawResponse, response);
249     }
250
251     /**
252      * Sets an operation's outcome and default message based on the result.
253      *
254      * @param outcome operation to be updated
255      * @param result result of the operation
256      * @param rawResponse raw response
257      * @param response decoded response
258      * @return the updated operation
259      */
260     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, Response rawResponse,
261                     T response) {
262
263         outcome.setResponse(response);
264         return setOutcome(outcome, result);
265     }
266
267     /**
268      * Processes a successful response. This method simply returns the outcome wrapped in
269      * a completed future.
270      *
271      * @param outcome outcome to be populate
272      * @param url URL to which to request was sent
273      * @param rawResponse raw response
274      * @param response decoded response
275      * @return a future to cancel or await the outcome
276      */
277     protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url,
278                     Response rawResponse, T response) {
279
280         if (!usePolling) {
281             // doesn't use polling - just return the completed future
282             return CompletableFuture.completedFuture(outcome);
283         }
284
285         HttpPollingConfig cfg = (HttpPollingConfig) config;
286
287         switch (detmStatus(rawResponse, response)) {
288             case SUCCESS:
289                 logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(),
290                                 params.getRequestId());
291                 return CompletableFuture
292                                 .completedFuture(setOutcome(outcome, PolicyResult.SUCCESS, rawResponse, response));
293
294             case FAILURE:
295                 logger.info("{}.{} request failed for {}", params.getActor(), params.getOperation(),
296                                 params.getRequestId());
297                 return CompletableFuture
298                                 .completedFuture(setOutcome(outcome, PolicyResult.FAILURE, rawResponse, response));
299
300             case STILL_WAITING:
301             default:
302                 logger.info("{}.{} request incomplete for {}", params.getActor(), params.getOperation(),
303                                 params.getRequestId());
304                 break;
305         }
306
307         // still incomplete
308
309         // see if the limit for the number of polls has been reached
310         if (pollCount++ >= cfg.getMaxPolls()) {
311             logger.warn("{}: execeeded 'poll' limit {} for {}", getFullName(), cfg.getMaxPolls(),
312                             params.getRequestId());
313             setOutcome(outcome, PolicyResult.FAILURE_TIMEOUT);
314             return CompletableFuture.completedFuture(outcome);
315         }
316
317         // sleep and then poll
318         Function<Void, CompletableFuture<OperationOutcome>> doPoll = unused -> issuePoll(outcome);
319         return sleep(getPollWaitMs(), TimeUnit.MILLISECONDS).thenComposeAsync(doPoll);
320     }
321
322     /**
323      * Polls to see if the original request is complete. This method polls using an HTTP
324      * "get" request whose URL is constructed by appending the extracted "poll ID" to the
325      * poll path from the configuration data.
326      *
327      * @param outcome outcome to be populated with the response
328      * @return a future that can be used to cancel the poll or await its response
329      */
330     protected CompletableFuture<OperationOutcome> issuePoll(OperationOutcome outcome) {
331         String path = getPollingPath();
332         String url = getClient().getBaseUrl() + path;
333
334         logger.debug("{}: 'poll' count {} for {}", getFullName(), pollCount, params.getRequestId());
335
336         logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
337
338         return handleResponse(outcome, url, callback -> getClient().get(callback, path, null));
339     }
340
341     /**
342      * Determines the status of the response. This particular method simply throws an
343      * exception.
344      *
345      * @param rawResponse raw response
346      * @param response decoded response
347      * @return the status of the response
348      */
349     protected Status detmStatus(Response rawResponse, T response) {
350         throw new UnsupportedOperationException("cannot determine response status");
351     }
352
353     /**
354      * Gets the URL to use when polling. Typically, this is some unique ID appended to the
355      * polling path found within the configuration data. This particular method simply
356      * returns the polling path from the configuration data.
357      *
358      * @return the URL to use when polling
359      */
360     protected String getPollingPath() {
361         return ((HttpPollingConfig) config).getPollPath();
362     }
363
364     /**
365      * Determines if the response indicates success. This method simply checks the HTTP
366      * status code.
367      *
368      * @param rawResponse raw response
369      * @param response decoded response
370      * @return {@code true} if the response indicates success, {@code false} otherwise
371      */
372     protected boolean isSuccess(Response rawResponse, T response) {
373         return (rawResponse.getStatus() == 200);
374     }
375
376     @Override
377     public <Q> String logMessage(EventType direction, CommInfrastructure infra, String sink, Q request) {
378         String json = super.logMessage(direction, infra, sink, request);
379         NetLoggerUtil.log(direction, infra, sink, json);
380         return json;
381     }
382
383     // these may be overridden by junit tests
384
385     protected long getPollWaitMs() {
386         HttpPollingConfig cfg = (HttpPollingConfig) config;
387
388         return TimeUnit.MILLISECONDS.convert(cfg.getPollWaitSec(), TimeUnit.SECONDS);
389     }
390 }