Add subrequest ID to OperationOutcome
[policy/models.git] / models-interactions / model-actors / actor.appclcm / src / main / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmOperation.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.actor.appclcm;
22
23 import java.util.List;
24 import java.util.Map;
25 import java.util.UUID;
26 import java.util.concurrent.CompletableFuture;
27 import org.apache.commons.lang3.StringUtils;
28 import org.apache.commons.lang3.tuple.Pair;
29 import org.onap.policy.appclcm.AppcLcmBody;
30 import org.onap.policy.appclcm.AppcLcmCommonHeader;
31 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
32 import org.onap.policy.appclcm.AppcLcmInput;
33 import org.onap.policy.appclcm.AppcLcmOutput;
34 import org.onap.policy.appclcm.AppcLcmResponseCode;
35 import org.onap.policy.appclcm.AppcLcmResponseStatus;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.controlloop.VirtualControlLoopEvent;
38 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
39 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
40 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
41 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
42 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
43 import org.onap.policy.controlloop.policy.PolicyResult;
44
45 public class AppcLcmOperation extends BidirectionalTopicOperation<AppcLcmDmaapWrapper, AppcLcmDmaapWrapper> {
46
47     private static final String MISSING_STATUS = "APPC-LCM response is missing the response status";
48     public static final String VNF_ID_KEY = "vnf-id";
49
50     /**
51      * Keys used to match the response with the request listener. The sub request ID is a
52      * UUID, so it can be used to uniquely identify the response.
53      * <p/>
54      * Note: if these change, then {@link #getExpectedKeyValues(int, AppcLcmDmaapWrapper)}
55      * must be updated accordingly.
56      */
57     public static final List<SelectorKey> SELECTOR_KEYS =
58                     List.of(new SelectorKey("body", "output", "common-header", "sub-request-id"));
59
60     /**
61      * Constructs the object.
62      *
63      * @param params operation parameters
64      * @param config configuration for this operation
65      */
66     public AppcLcmOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
67         super(params, config, AppcLcmDmaapWrapper.class);
68
69         if (StringUtils.isBlank(params.getTargetEntity())) {
70             throw new IllegalArgumentException("missing targetEntity");
71         }
72     }
73
74     /**
75      * Ensures that A&AI customer query has been performed, and then runs the guard query.
76      * Starts the GUARD using startGuardAsync.
77      */
78     @Override
79     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
80         return startGuardAsync();
81     }
82
83     @Override
84     protected Pair<String, AppcLcmDmaapWrapper> makeRequest(int attempt) {
85         VirtualControlLoopEvent onset = params.getContext().getEvent();
86         String subRequestId = UUID.randomUUID().toString();
87
88         AppcLcmCommonHeader header = new AppcLcmCommonHeader();
89         header.setOriginatorId(onset.getRequestId().toString());
90         header.setRequestId(onset.getRequestId());
91         header.setSubRequestId(subRequestId);
92
93         AppcLcmInput inputRequest = new AppcLcmInput();
94         inputRequest.setCommonHeader(header);
95
96         AppcLcmRecipeFormatter recipeFormatter = new AppcLcmRecipeFormatter(getName());
97         inputRequest.setAction(recipeFormatter.getBodyRecipe());
98
99         /*
100          * Action Identifiers are required for APPC LCM requests. For R1, the recipes
101          * supported by Policy only require a vnf-id.
102          */
103         inputRequest.setActionIdentifiers(Map.of(VNF_ID_KEY, params.getTargetEntity()));
104
105         /*
106          * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate
107          * recipes. APPC will populate the payload based on A&AI look up of the vnd-id
108          * provided in the action identifiers. The payload is set when converPayload() is
109          * called.
110          */
111         if (operationSupportsPayload()) {
112             convertPayload(params.getPayload(), inputRequest);
113         } else {
114             inputRequest.setPayload(null);
115         }
116
117         AppcLcmBody body = new AppcLcmBody();
118         body.setInput(inputRequest);
119
120         AppcLcmDmaapWrapper dmaapRequest = new AppcLcmDmaapWrapper();
121         dmaapRequest.setBody(body);
122         dmaapRequest.setVersion("2.0");
123         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + subRequestId);
124         dmaapRequest.setRpcName(recipeFormatter.getUrlRecipe());
125         dmaapRequest.setType("request");
126
127         body.setInput(inputRequest);
128         dmaapRequest.setBody(body);
129         return Pair.of(subRequestId, dmaapRequest);
130     }
131
132     /**
133      * Converts a payload. The original value is assumed to be a JSON string, which is
134      * decoded into an object.
135      *
136      * @param source source from which to get the values
137      * @param map where to place the decoded values
138      */
139     private void convertPayload(Map<String, Object> source, AppcLcmInput request) {
140         try {
141             String encodedPayloadString = makeCoder().encode(source);
142             request.setPayload(encodedPayloadString);
143         } catch (CoderException e) {
144             throw new IllegalArgumentException("Cannot convert payload", e);
145         }
146     }
147
148     /**
149      * Note: these values must match {@link #SELECTOR_KEYS}.
150      */
151     @Override
152     protected List<String> getExpectedKeyValues(int attempt, AppcLcmDmaapWrapper request) {
153         return List.of(request.getBody().getInput().getCommonHeader().getSubRequestId());
154     }
155
156     @Override
157     protected Status detmStatus(String rawResponse, AppcLcmDmaapWrapper response) {
158         AppcLcmResponseStatus status = getStatus(response);
159         if (status == null) {
160             throw new IllegalArgumentException(MISSING_STATUS);
161         }
162
163         String code = AppcLcmResponseCode.toResponseValue(status.getCode());
164         if (code == null) {
165             throw new IllegalArgumentException("unknown APPC-LCM response status code: " + status.getCode());
166         }
167
168         switch (code) {
169             case AppcLcmResponseCode.SUCCESS:
170                 return Status.SUCCESS;
171             case AppcLcmResponseCode.FAILURE:
172                 return Status.FAILURE;
173             case AppcLcmResponseCode.ERROR:
174             case AppcLcmResponseCode.REJECT:
175                 throw new IllegalArgumentException("APPC-LCM request was not accepted, code=" + code);
176             case AppcLcmResponseCode.ACCEPTED:
177             default:
178                 return Status.STILL_WAITING;
179         }
180     }
181
182     /**
183      * Sets the message to the status description, if available.
184      */
185     @Override
186     public OperationOutcome setOutcome(OperationOutcome outcome, PolicyResult result, AppcLcmDmaapWrapper response) {
187         AppcLcmResponseStatus status = getStatus(response);
188         if (status == null) {
189             return setOutcome(outcome, result);
190         }
191
192         String message = status.getMessage();
193         if (message == null) {
194             return setOutcome(outcome, result);
195         }
196
197         outcome.setResult(result);
198         outcome.setMessage(message);
199         return outcome;
200     }
201
202     /**
203      * Gets the status from the response.
204      *
205      * @param response the response from which to extract the status, or {@code null}
206      * @return the status, or {@code null} if it does not exist
207      */
208     protected AppcLcmResponseStatus getStatus(AppcLcmDmaapWrapper response) {
209         if (response == null) {
210             return null;
211         }
212
213         AppcLcmBody body = response.getBody();
214         if (body == null) {
215             return null;
216         }
217
218         AppcLcmOutput output = body.getOutput();
219         if (output == null) {
220             return null;
221         }
222
223         return output.getStatus();
224     }
225
226     /**
227      * Determines if the operation supports a payload.
228      *
229      * @return {@code true} if the operation supports a payload, {@code false} otherwise
230      */
231     protected boolean operationSupportsPayload() {
232         return params.getPayload() != null && !params.getPayload().isEmpty()
233                         && AppcLcmConstants.SUPPORTS_PAYLOAD.contains(params.getOperation().toLowerCase());
234     }
235 }