2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controlloop.actorserviceprovider.impl;
23 import java.util.List;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.concurrent.Executor;
26 import java.util.function.BiConsumer;
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;
42 * Operation that uses a bidirectional topic.
44 * @param <S> response type
47 public abstract class BidirectionalTopicOperation<Q, S> extends OperationPartial {
48 private static final Logger logger = LoggerFactory.getLogger(BidirectionalTopicOperation.class);
54 SUCCESS, FAILURE, STILL_WAITING
58 * Configuration for this operation.
60 private final BidirectionalTopicConfig config;
65 private final Class<S> responseClass;
67 // fields extracted from "config"
69 private final BidirectionalTopicHandler topicHandler;
70 private final Forwarder forwarder;
74 * Constructs the object.
76 * @param params operation parameters
77 * @param config configuration for this operation
78 * @param clazz response class
80 public BidirectionalTopicOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config,
82 super(params, config);
84 this.responseClass = clazz;
85 this.forwarder = config.getForwarder();
86 this.topicHandler = config.getTopicHandler();
89 public long getTimeoutMs() {
90 return config.getTimeoutMs();
94 * If no timeout is specified, then it returns the default timeout.
97 protected long getTimeoutMs(Integer timeoutSec) {
98 // TODO move this method to the superclass
99 return (timeoutSec == null || timeoutSec == 0 ? getTimeoutMs() : super.getTimeoutMs(timeoutSec));
103 * Publishes the request and arranges to receive the response.
106 protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
108 final Q request = makeRequest(attempt);
109 final List<String> expectedKeyValues = getExpectedKeyValues(attempt, request);
111 final PipelineControllerFuture<OperationOutcome> controller = new PipelineControllerFuture<>();
112 final Executor executor = params.getExecutor();
114 // register a listener BEFORE publishing
116 BiConsumer<String, StandardCoderObject> listener = (rawResponse, scoResponse) -> {
118 OperationOutcome latestOutcome = processResponse(outcome, rawResponse, scoResponse);
119 if (latestOutcome != null) {
120 // final response - complete the controller
121 controller.completeAsync(() -> latestOutcome, executor);
123 } catch (RuntimeException e) {
124 logger.warn("{}: failed to process response for {}", getFullName(), params.getRequestId());
125 controller.completeExceptionally(e);
129 forwarder.register(expectedKeyValues, listener);
131 // ensure listener is unregistered if the controller is canceled
132 controller.add(() -> forwarder.unregister(expectedKeyValues, listener));
134 // publish the request
136 publishRequest(request);
137 } catch (RuntimeException e) {
138 logger.warn("{}: failed to publish request for {}", getFullName(), params.getRequestId());
139 forwarder.unregister(expectedKeyValues, listener);
149 * @param attempt operation attempt
150 * @return a new request
152 protected abstract Q makeRequest(int attempt);
155 * Gets values, expected in the response, that should match the selector keys.
157 * @param attempt operation attempt
158 * @param request request to be published
159 * @return a list of the values to be matched by the selector keys
161 protected abstract List<String> getExpectedKeyValues(int attempt, Q request);
164 * Publishes the request. Encodes the request, if it is not already a String.
166 * @param request request to be published
168 protected void publishRequest(Q request) {
169 String json = prettyPrint(request);
170 logMessage(EventType.OUT, topicHandler.getSinkTopicCommInfrastructure(), topicHandler.getSinkTopic(), json);
172 if (!topicHandler.send(json)) {
173 throw new IllegalStateException("nothing published");
178 * Processes a response.
180 * @param infra communication infrastructure on which the response was received
181 * @param outcome outcome to be populated
182 * @param response raw response to process
183 * @param scoResponse response, as a {@link StandardCoderObject}
184 * @return the outcome, or {@code null} if still waiting for completion
186 protected OperationOutcome processResponse(OperationOutcome outcome, String rawResponse,
187 StandardCoderObject scoResponse) {
189 logger.info("{}.{}: response received for {}", params.getActor(), params.getOperation(), params.getRequestId());
191 logMessage(EventType.IN, topicHandler.getSourceTopicCommInfrastructure(), topicHandler.getSourceTopic(),
194 // decode the response
196 if (responseClass == String.class) {
197 response = responseClass.cast(rawResponse);
199 } else if (responseClass == StandardCoderObject.class) {
200 response = responseClass.cast(scoResponse);
204 response = makeCoder().decode(rawResponse, responseClass);
205 } catch (CoderException e) {
206 logger.warn("{}.{} cannot decode response for {}", params.getActor(), params.getOperation(),
207 params.getRequestId());
208 throw new IllegalArgumentException("cannot decode response", e);
213 switch (detmStatus(rawResponse, response)) {
215 logger.info("{}.{} request succeeded for {}", params.getActor(), params.getOperation(),
216 params.getRequestId());
217 setOutcome(outcome, PolicyResult.SUCCESS, response);
218 postProcessResponse(outcome, rawResponse, response);
222 logger.info("{}.{} request failed for {}", params.getActor(), params.getOperation(),
223 params.getRequestId());
224 return setOutcome(outcome, PolicyResult.FAILURE, response);
228 logger.info("{}.{} request incomplete for {}", params.getActor(), params.getOperation(),
229 params.getRequestId());
235 * Sets an operation's outcome and default message based on the result.
237 * @param outcome operation to be updated
238 * @param result result of the operation
239 * @param response response used to populate the outcome
240 * @return the updated operation
242 public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, S response) {
243 outcome.setResponse(response);
244 return setOutcome(outcome, result);
248 * Processes a successful response.
250 * @param outcome outcome to be populated
251 * @param rawResponse raw response
252 * @param response decoded response
254 protected void postProcessResponse(OperationOutcome outcome, String rawResponse, S response) {
259 * Determines the status of the response.
261 * @param rawResponse raw response
262 * @param response decoded response
263 * @return the status of the response
265 protected abstract Status detmStatus(String rawResponse, S response);