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