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