Fix exception message in Actors
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / impl / BidirectionalTopicOperation.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.List;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.concurrent.Executor;
26 import java.util.function.BiConsumer;
27 import lombok.Getter;
28 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
29 import org.onap.policy.common.utils.coder.CoderException;
30 import org.onap.policy.common.utils.coder.StandardCoderObject;
31 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
32 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
33 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
34 import org.onap.policy.controlloop.actorserviceprovider.pipeline.PipelineControllerFuture;
35 import org.onap.policy.controlloop.actorserviceprovider.topic.BidirectionalTopicHandler;
36 import org.onap.policy.controlloop.actorserviceprovider.topic.Forwarder;
37 import org.onap.policy.controlloop.policy.PolicyResult;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Operation that uses a bidirectional topic.
43  *
44  * @param <S> response type
45  */
46 @Getter
47 public abstract class BidirectionalTopicOperation<Q, S> extends OperationPartial {
48     private static final Logger logger = LoggerFactory.getLogger(BidirectionalTopicOperation.class);
49
50     /**
51      * Response status.
52      */
53     public enum Status {
54         SUCCESS, FAILURE, STILL_WAITING
55     }
56
57     /**
58      * Configuration for this operation.
59      */
60     private final BidirectionalTopicConfig config;
61
62     /**
63      * Response class.
64      */
65     private final Class<S> responseClass;
66
67     // fields extracted from "config"
68
69     private final BidirectionalTopicHandler topicHandler;
70     private final Forwarder forwarder;
71
72
73     /**
74      * Constructs the object.
75      *
76      * @param params operation parameters
77      * @param config configuration for this operation
78      * @param clazz response class
79      */
80     public BidirectionalTopicOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config,
81                     Class<S> clazz) {
82         super(params, config);
83         this.config = config;
84         this.responseClass = clazz;
85         this.forwarder = config.getForwarder();
86         this.topicHandler = config.getTopicHandler();
87     }
88
89     public long getTimeoutMs() {
90         return config.getTimeoutMs();
91     }
92
93     /**
94      * If no timeout is specified, then it returns the default timeout.
95      */
96     @Override
97     protected long getTimeoutMs(Integer timeoutSec) {
98         // TODO move this method to the superclass
99         return (timeoutSec == null || timeoutSec == 0 ? getTimeoutMs() : super.getTimeoutMs(timeoutSec));
100     }
101
102     /**
103      * Publishes the request and arranges to receive the response.
104      */
105     @Override
106     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
107
108         final Q request = makeRequest(attempt);
109         final List<String> expectedKeyValues = getExpectedKeyValues(attempt, request);
110
111         final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
112         final Executor executor = params.getExecutor();
113
114         // register a listener BEFORE publishing
115
116         BiConsumer<String, StandardCoderObject> listener = (rawResponse, scoResponse) -> {
117             OperationOutcome latestOutcome = processResponse(outcome, rawResponse, scoResponse);
118             if (latestOutcome != null) {
119                 // final response - complete the controller
120                 controller.completeAsync(() -> latestOutcome, executor);
121             }
122         };
123
124         forwarder.register(expectedKeyValues, listener);
125
126         // ensure listener is unregistered if the controller is canceled
127         controller.add(() -> forwarder.unregister(expectedKeyValues, listener));
128
129         // publish the request
130         try {
131             publishRequest(request);
132         } catch (RuntimeException e) {
133             logger.warn("{}: failed to publish request for {}", getFullName(), params.getRequestId());
134             forwarder.unregister(expectedKeyValues, listener);
135             throw e;
136         }
137
138         return controller;
139     }
140
141     /**
142      * Makes the request.
143      *
144      * @param attempt operation attempt
145      * @return a new request
146      */
147     protected abstract Q makeRequest(int attempt);
148
149     /**
150      * Gets values, expected in the response, that should match the selector keys.
151      *
152      * @param attempt operation attempt
153      * @param request request to be published
154      * @return a list of the values to be matched by the selector keys
155      */
156     protected abstract List<String> getExpectedKeyValues(int attempt, Q request);
157
158     /**
159      * Publishes the request. Encodes the request, if it is not already a String.
160      *
161      * @param request request to be published
162      */
163     protected void publishRequest(Q request) {
164         String json;
165         try {
166             if (request instanceof String) {
167                 json = request.toString();
168             } else {
169                 json = makeCoder().encode(request);
170             }
171         } catch (CoderException e) {
172             throw new IllegalArgumentException("cannot encode request", e);
173         }
174
175         logMessage(EventType.OUT, topicHandler.getSinkTopicCommInfrastructure(), topicHandler.getSinkTopic(), request);
176
177         if (!topicHandler.send(json)) {
178             throw new IllegalStateException("nothing published");
179         }
180     }
181
182     /**
183      * Processes a response.
184      *
185      * @param infra communication infrastructure on which the response was received
186      * @param outcome outcome to be populated
187      * @param response raw response to process
188      * @param scoResponse response, as a {@link StandardCoderObject}
189      * @return the outcome, or {@code null} if still waiting for completion
190      */
191     protected OperationOutcome processResponse(OperationOutcome outcome, String rawResponse,
192                     StandardCoderObject scoResponse) {
193
194         logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
195
196         logMessage(EventType.IN, topicHandler.getSourceTopicCommInfrastructure(), topicHandler.getSourceTopic(),
197                         rawResponse);
198
199         // decode the response
200         S response;
201         if (responseClass == String.class) {
202             response = responseClass.cast(rawResponse);
203
204         } else if (responseClass == StandardCoderObject.class) {
205             response = responseClass.cast(scoResponse);
206
207         } else {
208             try {
209                 response = makeCoder().decode(rawResponse, responseClass);
210             } catch (CoderException e) {
211                 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
212                                 params.getRequestId());
213                 throw new IllegalArgumentException("cannot decode response", e);
214             }
215         }
216
217         // check its status
218         switch (detmStatus(rawResponse, response)) {
219             case SUCCESS:
220                 logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(),
221                                 params.getRequestId());
222                 setOutcome(outcome, PolicyResult.SUCCESS, response);
223                 postProcessResponse(outcome, rawResponse, response);
224                 return outcome;
225
226             case FAILURE:
227                 logger.info("{}.{} request failed for {}", params.getActor(), params.getOperation(),
228                                 params.getRequestId());
229                 return setOutcome(outcome, PolicyResult.FAILURE, response);
230
231             case STILL_WAITING:
232             default:
233                 logger.info("{}.{} request incomplete for {}", params.getActor(), params.getOperation(),
234                                 params.getRequestId());
235                 return null;
236         }
237     }
238
239     /**
240      * Sets an operation's outcome and default message based on the result.
241      *
242      * @param outcome operation to be updated
243      * @param result result of the operation
244      * @param response response used to populate the outcome
245      * @return the updated operation
246      */
247     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, S response) {
248         return setOutcome(outcome, result);
249     }
250
251     /**
252      * Processes a successful response.
253      *
254      * @param outcome outcome to be populated
255      * @param rawResponse raw response
256      * @param response decoded response
257      */
258     protected void postProcessResponse(OperationOutcome outcome, String rawResponse, S response) {
259         // do nothing
260     }
261
262     /**
263      * Determines the status of the response.
264      *
265      * @param rawResponse raw response
266      * @param response decoded response
267      * @return the status of the response
268      */
269     protected abstract Status detmStatus(String rawResponse, S response);
270 }