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