5d256e8aec5acb0fe6f4fdec25cb4c2ad827321f
[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-2021 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         var header = new AppcLcmCommonHeader();
73         header.setOriginatorId(params.getRequestId().toString());
74         header.setRequestId(params.getRequestId());
75         header.setSubRequestId(subRequestId);
76
77         var inputRequest = new AppcLcmInput();
78         inputRequest.setCommonHeader(header);
79
80         var 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         String target = getRequiredProperty(OperationProperties.AAI_TARGET_ENTITY, "target entity");
88         inputRequest.setActionIdentifiers(Map.of(VNF_ID_KEY, target));
89
90         /*
91          * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate
92          * recipes. APPC will populate the payload based on A&AI look up of the vnd-id
93          * provided in the action identifiers. The payload is set when converPayload() is
94          * called.
95          */
96         if (operationSupportsPayload()) {
97             convertPayload(params.getPayload(), inputRequest);
98         } else {
99             inputRequest.setPayload(null);
100         }
101
102         var body = new AppcLcmBody();
103         body.setInput(inputRequest);
104
105         var dmaapRequest = new AppcLcmDmaapWrapper();
106         dmaapRequest.setBody(body);
107         dmaapRequest.setVersion("2.0");
108         dmaapRequest.setCorrelationId(params.getRequestId() + "-" + subRequestId);
109         dmaapRequest.setRpcName(recipeFormatter.getUrlRecipe());
110         dmaapRequest.setType("request");
111
112         body.setInput(inputRequest);
113         dmaapRequest.setBody(body);
114         return dmaapRequest;
115     }
116
117     /**
118      * Converts a payload. The original value is assumed to be a JSON string, which is
119      * decoded into an object.
120      *
121      * @param source source from which to get the values
122      * @param request where to place the decoded values
123      */
124     private void convertPayload(Map<String, Object> source, AppcLcmInput request) {
125         try {
126             var encodedPayloadString = getCoder().encode(source);
127             request.setPayload(encodedPayloadString);
128         } catch (CoderException e) {
129             throw new IllegalArgumentException("Cannot convert payload", e);
130         }
131     }
132
133     /**
134      * Note: these values must match {@link #SELECTOR_KEYS}.
135      */
136     @Override
137     protected List<String> getExpectedKeyValues(int attempt, AppcLcmDmaapWrapper request) {
138         return List.of(getSubRequestId());
139     }
140
141     @Override
142     protected Status detmStatus(String rawResponse, AppcLcmDmaapWrapper response) {
143         AppcLcmResponseStatus status = getStatus(response);
144         if (status == null) {
145             throw new IllegalArgumentException(MISSING_STATUS);
146         }
147
148         String code = AppcLcmResponseCode.toResponseValue(status.getCode());
149         if (code == null) {
150             throw new IllegalArgumentException("unknown APPC-LCM response status code: " + status.getCode());
151         }
152
153         switch (code) {
154             case AppcLcmResponseCode.SUCCESS:
155                 return Status.SUCCESS;
156             case AppcLcmResponseCode.FAILURE:
157                 return Status.FAILURE;
158             case AppcLcmResponseCode.ERROR:
159             case AppcLcmResponseCode.REJECT:
160                 throw new IllegalArgumentException("APPC-LCM request was not accepted, code=" + code);
161             case AppcLcmResponseCode.ACCEPTED:
162             default:
163                 return Status.STILL_WAITING;
164         }
165     }
166
167     /**
168      * Sets the message to the status description, if available.
169      */
170     @Override
171     public OperationOutcome setOutcome(OperationOutcome outcome, OperationResult result, AppcLcmDmaapWrapper response) {
172         outcome.setResponse(response);
173
174         AppcLcmResponseStatus status = getStatus(response);
175         if (status == null) {
176             return setOutcome(outcome, result);
177         }
178
179         String message = status.getMessage();
180         if (message == null) {
181             return setOutcome(outcome, result);
182         }
183
184         outcome.setResult(result);
185         outcome.setMessage(message);
186         return outcome;
187     }
188
189     /**
190      * Gets the status from the response.
191      *
192      * @param response the response from which to extract the status, or {@code null}
193      * @return the status, or {@code null} if it does not exist
194      */
195     protected AppcLcmResponseStatus getStatus(AppcLcmDmaapWrapper response) {
196         if (response == null) {
197             return null;
198         }
199
200         AppcLcmBody body = response.getBody();
201         if (body == null) {
202             return null;
203         }
204
205         AppcLcmOutput output = body.getOutput();
206         if (output == null) {
207             return null;
208         }
209
210         return output.getStatus();
211     }
212
213     /**
214      * Determines if the operation supports a payload.
215      *
216      * @return {@code true} if the operation supports a payload, {@code false} otherwise
217      */
218     protected boolean operationSupportsPayload() {
219         return params.getPayload() != null && !params.getPayload().isEmpty()
220                         && AppcLcmConstants.SUPPORTS_PAYLOAD.contains(params.getOperation().toLowerCase());
221     }
222 }