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