2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.controlloop.actor.appclcm;
23 import java.util.List;
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;
47 public abstract class AppcLcmOperation extends BidirectionalTopicOperation<AppcLcmDmaapWrapper, AppcLcmDmaapWrapper> {
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";
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.
57 * Note: if these change, then {@link #getExpectedKeyValues(int, Request)} must be
58 * updated accordingly.
60 public static final List<SelectorKey> SELECTOR_KEYS = List.of(new SelectorKey("common-header", "sub-request-id"));
63 * Constructs the object.
65 * @param params operation parameters
66 * @param config configuration for this operation
68 public AppcLcmOperation(ControlLoopOperationParams params, BidirectionalTopicConfig config) {
69 super(params, config, AppcLcmDmaapWrapper.class);
73 * Ensures that A&AI customer query has been performed, and then runs the guard query.
74 * Starts the GUARD using startGuardAsync.
77 @SuppressWarnings("unchecked")
78 protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
80 ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
81 .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
83 // run Custom Query and Guard, in parallel
84 return allOf(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams), this::startGuardAsync);
86 return startGuardAsync();
90 protected AppcLcmDmaapWrapper makeRequest(int attempt) {
91 AaiCqResponse cq = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
93 GenericVnf genvnf = cq.getGenericVnfByModelInvariantId(params.getTarget().getResourceID());
95 logger.info("{}: target entity could not be found for {}", getFullName(), params.getRequestId());
96 throw new IllegalArgumentException("target vnf-id could not be found");
99 return makeRequest(attempt, genvnf.getVnfId());
103 * Makes a request, given the target VNF. This is a support function for
104 * {@link #makeRequest(int)}.
106 * @param attempt attempt number
107 * @param targetVnf target VNF
108 * @return a new request
110 protected AppcLcmDmaapWrapper makeRequest(int attempt, String targetVnf) {
111 VirtualControlLoopEvent onset = params.getContext().getEvent();
112 String subRequestId = UUID.randomUUID().toString();
114 AppcLcmCommonHeader header = new AppcLcmCommonHeader();
115 header.setOriginatorId(onset.getRequestId().toString());
116 header.setRequestId(onset.getRequestId());
117 header.setSubRequestId(subRequestId);
119 AppcLcmInput inputRequest = new AppcLcmInput();
120 inputRequest.setCommonHeader(header);
121 inputRequest.setAction(getName());
124 * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
125 * Policy only require a vnf-id.
127 if (inputRequest.getActionIdentifiers() != null) {
128 inputRequest.getActionIdentifiers().put(VNF_ID_KEY, targetVnf);
130 inputRequest.setActionIdentifiers(Map.of(VNF_ID_KEY, targetVnf));
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.
138 if (operationSupportsPayload()) {
139 convertPayload(params.getPayload(), inputRequest);
141 inputRequest.setPayload(null);
144 AppcLcmBody body = new AppcLcmBody();
145 body.setInput(inputRequest);
147 AppcLcmRecipeFormatter recipeFormatter = new AppcLcmRecipeFormatter(getName());
148 inputRequest.setAction(recipeFormatter.getBodyRecipe());
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");
157 body.setInput(inputRequest);
158 dmaapRequest.setBody(body);
163 * Converts a payload. The original value is assumed to be a JSON string, which is
164 * decoded into an object.
166 * @param source source from which to get the values
167 * @param map where to place the decoded values
169 private static void convertPayload(Map<String, Object> source, AppcLcmInput request) {
170 String encodedPayloadString = null;
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.");
181 * Note: these values must match {@link #SELECTOR_KEYS}.
184 protected List<String> getExpectedKeyValues(int attempt, AppcLcmDmaapWrapper request) {
185 return List.of(request.getBody().getInput().getCommonHeader().getSubRequestId());
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");
195 String code = AppcLcmResponseCode.toResponseValue(response.getBody().getOutput().getStatus().getCode());
198 throw new IllegalArgumentException(
199 "unknown APPC-LCM response status code: " + response.getBody().getOutput().getStatus().getCode());
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:
212 return Status.STILL_WAITING;
217 * Sets the message to the status description, if available.
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);
227 outcome.setResult(result);
228 outcome.setMessage(response.getBody().getOutput().getStatus().getMessage());
232 protected boolean operationSupportsPayload() {
233 return params.getPayload() != null && !params.getPayload().isEmpty();