Remove dmaap from models
[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  * Modifications Copyright (C) 2023-2024 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.appclcm;
23
24 import java.util.List;
25 import java.util.Map;
26 import org.onap.policy.appclcm.AppcLcmBody;
27 import org.onap.policy.appclcm.AppcLcmCommonHeader;
28 import org.onap.policy.appclcm.AppcLcmInput;
29 import org.onap.policy.appclcm.AppcLcmMessageWrapper;
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.OperationResult;
37 import org.onap.policy.controlloop.actorserviceprovider.impl.BidirectionalTopicOperation;
38 import org.onap.policy.controlloop.actorserviceprovider.parameters.BidirectionalTopicConfig;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
40 import org.onap.policy.controlloop.actorserviceprovider.topic.SelectorKey;
41
42 public class AppcLcmOperation extends BidirectionalTopicOperation<AppcLcmMessageWrapper, AppcLcmMessageWrapper> {
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, AppcLcmMessageWrapper)}
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, AppcLcmMessageWrapper.class, PROPERTY_NAMES);
67     }
68
69     @Override
70     protected AppcLcmMessageWrapper makeRequest(int attempt) {
71         String subRequestId = getSubRequestId();
72
73         var header = new AppcLcmCommonHeader();
74         header.setOriginatorId(params.getRequestId().toString());
75         header.setRequestId(params.getRequestId());
76         header.setSubRequestId(subRequestId);
77
78         var inputRequest = new AppcLcmInput();
79         inputRequest.setCommonHeader(header);
80
81         var recipeFormatter = new AppcLcmRecipeFormatter(getName());
82         inputRequest.setAction(recipeFormatter.getBodyRecipe());
83
84         /*
85          * Action Identifiers are required for APPC LCM requests. For R1, the recipes
86          * supported by Policy only require a vnf-id.
87          */
88         String target = getRequiredProperty(OperationProperties.AAI_TARGET_ENTITY, "target entity");
89         inputRequest.setActionIdentifiers(Map.of(VNF_ID_KEY, target));
90
91         /*
92          * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate
93          * recipes. APPC will populate the payload based on A&AI look up of the vnd-id
94          * provided in the action identifiers. The payload is set when convertPayload() is
95          * called.
96          */
97         if (operationSupportsPayload()) {
98             convertPayload(params.getPayload(), inputRequest);
99         } else {
100             inputRequest.setPayload(null);
101         }
102
103         var body = new AppcLcmBody();
104         body.setInput(inputRequest);
105
106         var messageRequest = new AppcLcmMessageWrapper();
107         messageRequest.setBody(body);
108         messageRequest.setVersion("2.0");
109         messageRequest.setCorrelationId(params.getRequestId() + "-" + subRequestId);
110         messageRequest.setRpcName(recipeFormatter.getUrlRecipe());
111         messageRequest.setType("request");
112
113         body.setInput(inputRequest);
114         messageRequest.setBody(body);
115         return messageRequest;
116     }
117
118     /**
119      * Converts a payload. The original value is assumed to be a JSON string, which is
120      * decoded into an object.
121      *
122      * @param source source from which to get the values
123      * @param request where to place the decoded values
124      */
125     private void convertPayload(Map<String, Object> source, AppcLcmInput request) {
126         try {
127             var encodedPayloadString = getCoder().encode(source);
128             request.setPayload(encodedPayloadString);
129         } catch (CoderException e) {
130             throw new IllegalArgumentException("Cannot convert payload", e);
131         }
132     }
133
134     /**
135      * Note: these values must match {@link #SELECTOR_KEYS}.
136      */
137     @Override
138     protected List<String> getExpectedKeyValues(int attempt, AppcLcmMessageWrapper request) {
139         return List.of(getSubRequestId());
140     }
141
142     @Override
143     protected Status detmStatus(String rawResponse, AppcLcmMessageWrapper response) {
144         AppcLcmResponseStatus status = getStatus(response);
145         if (status == null) {
146             throw new IllegalArgumentException(MISSING_STATUS);
147         }
148
149         String code = AppcLcmResponseCode.toResponseValue(status.getCode());
150         if (code == null) {
151             throw new IllegalArgumentException("unknown APPC-LCM response status code: " + status.getCode());
152         }
153
154         return switch (code) {
155             case AppcLcmResponseCode.SUCCESS -> Status.SUCCESS;
156             case AppcLcmResponseCode.FAILURE -> Status.FAILURE;
157             case AppcLcmResponseCode.ERROR, AppcLcmResponseCode.REJECT ->
158                 throw new IllegalArgumentException("APPC-LCM request was not accepted, code=" + code);
159             default -> Status.STILL_WAITING;
160         };
161     }
162
163     /**
164      * Sets the message to the status description, if available.
165      */
166     @Override
167     public OperationOutcome setOutcome(OperationOutcome outcome, OperationResult result,
168                                        AppcLcmMessageWrapper response) {
169         outcome.setResponse(response);
170
171         AppcLcmResponseStatus status = getStatus(response);
172         if (status == null) {
173             return setOutcome(outcome, result);
174         }
175
176         String message = status.getMessage();
177         if (message == null) {
178             return setOutcome(outcome, result);
179         }
180
181         outcome.setResult(result);
182         outcome.setMessage(message);
183         return outcome;
184     }
185
186     /**
187      * Gets the status from the response.
188      *
189      * @param response the response from which to extract the status, or {@code null}
190      * @return the status, or {@code null} if it does not exist
191      */
192     protected AppcLcmResponseStatus getStatus(AppcLcmMessageWrapper response) {
193         if (response == null) {
194             return null;
195         }
196
197         AppcLcmBody body = response.getBody();
198         if (body == null) {
199             return null;
200         }
201
202         AppcLcmOutput output = body.getOutput();
203         if (output == null) {
204             return null;
205         }
206
207         return output.getStatus();
208     }
209
210     /**
211      * Determines if the operation supports a payload.
212      *
213      * @return {@code true} if the operation supports a payload, {@code false} otherwise
214      */
215     protected boolean operationSupportsPayload() {
216         return params.getPayload() != null && !params.getPayload().isEmpty()
217                         && AppcLcmConstants.SUPPORTS_PAYLOAD.contains(params.getOperation().toLowerCase());
218     }
219 }