2 * ============LICENSE_START=======================================================
3 * AppcLcmActorServiceProvider
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Modifications copyright (c) 2018 Nokia
7 * Modifications Copyright (C) 2019 Nordix Foundation.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.controlloop.actor.appclcm;
25 import com.google.common.collect.ImmutableList;
26 import com.google.common.collect.ImmutableMap;
27 import java.util.AbstractMap;
28 import java.util.AbstractMap.SimpleEntry;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.UUID;
34 import org.onap.policy.aai.AaiManager;
35 import org.onap.policy.aai.AaiNqInstanceFilters;
36 import org.onap.policy.aai.AaiNqInventoryResponseItem;
37 import org.onap.policy.aai.AaiNqNamedQuery;
38 import org.onap.policy.aai.AaiNqQueryParameters;
39 import org.onap.policy.aai.AaiNqRequest;
40 import org.onap.policy.aai.AaiNqResponse;
41 import org.onap.policy.aai.util.AaiException;
42 import org.onap.policy.appclcm.AppcLcmBody;
43 import org.onap.policy.appclcm.AppcLcmCommonHeader;
44 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
45 import org.onap.policy.appclcm.AppcLcmInput;
46 import org.onap.policy.appclcm.AppcLcmOutput;
47 import org.onap.policy.appclcm.AppcLcmResponseCode;
48 import org.onap.policy.controlloop.ControlLoopOperation;
49 import org.onap.policy.controlloop.VirtualControlLoopEvent;
50 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
51 import org.onap.policy.controlloop.policy.Policy;
52 import org.onap.policy.controlloop.policy.PolicyResult;
53 import org.onap.policy.rest.RestManager;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 public class AppcLcmActorServiceProvider implements Actor {
59 private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
61 /* To be used in future releases to restart a single vm */
62 private static final String APPC_VM_ID = "vm-id";
64 // Strings for targets
65 private static final String TARGET_VM = "VM";
66 private static final String TARGET_VNF = "VNF";
68 // Strings for recipes
69 private static final String RECIPE_RESTART = "Restart";
70 private static final String RECIPE_REBUILD = "Rebuild";
71 private static final String RECIPE_MIGRATE = "Migrate";
72 private static final String RECIPE_MODIFY = "ConfigModify";
74 /* To be used in future releases when LCM ConfigModify is used */
75 private static final String APPC_REQUEST_PARAMS = "request-parameters";
76 private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
78 private static final ImmutableList<String> recipes =
79 ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
80 private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
81 .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
82 .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
83 private static final ImmutableMap<String, List<String>> payloads =
84 new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
85 .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
88 public String actor() {
93 public List<String> recipes() {
94 return ImmutableList.copyOf(recipes);
98 public List<String> recipeTargets(String recipe) {
99 return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
103 public List<String> recipePayloads(String recipe) {
104 return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
108 * This method recursively traverses the A&AI named query response to find the generic-vnf
109 * object that contains a model-invariant-id that matches the resourceId of the policy. Once
110 * this match is found the generic-vnf object's vnf-id is returned.
112 * @param items the list of items related to the vnf returned by A&AI
113 * @param resourceId the id of the target from the sdc catalog
115 * @return the vnf-id of the target vnf to act upon or null if not found
117 private static String parseAaiResponse(List<AaiNqInventoryResponseItem> items, String resourceId) {
119 for (AaiNqInventoryResponseItem item : items) {
120 if ((item.getGenericVnf() != null) && (item.getGenericVnf().getModelInvariantId() != null)
121 && (resourceId.equals(item.getGenericVnf().getModelInvariantId()))) {
122 vnfId = item.getGenericVnf().getVnfId();
125 if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
126 vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
134 * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target
135 * entity specified in the policy to act upon.
137 * @param resourceId the id of the target from the sdc catalog
139 * @param sourceVnfId the vnf id of the source entity reporting the alert
141 * @return the target entities vnf id to act upon
142 * @throws AaiException it an error occurs
144 public static String vnfNamedQuery(String resourceId, String sourceVnfId, String aaiUrl,
145 String aaiUser, String aaiPassword) throws AaiException {
147 // TODO: This request id should not be hard coded in future releases
148 UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
150 AaiNqRequest aaiRequest = new AaiNqRequest();
151 aaiRequest.setQueryParameters(new AaiNqQueryParameters());
152 aaiRequest.getQueryParameters().setNamedQuery(new AaiNqNamedQuery());
153 aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUuid(requestId);
155 Map<String, Map<String, String>> filter = new HashMap<>();
156 Map<String, String> filterItem = new HashMap<>();
158 filterItem.put("vnf-id", sourceVnfId);
159 filter.put("generic-vnf", filterItem);
161 aaiRequest.setInstanceFilters(new AaiNqInstanceFilters());
162 aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
164 AaiNqResponse aaiResponse = new AaiManager(new RestManager()).postQuery(aaiUrl,
165 aaiUser, aaiPassword, aaiRequest, requestId);
167 if (aaiResponse == null) {
168 throw new AaiException("The named query response was null");
171 String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
172 if (targetVnfId == null) {
173 throw new AaiException("Target vnf-id could not be found");
180 * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
181 * then placed in a wrapper object used to send through DMAAP.
183 * @param onset the event that is reporting the alert for policy to perform an action
184 * @param operation the control loop operation specifying the actor, operation, target, etc.
185 * @param policy the policy the was specified from the yaml generated by CLAMP or through the
187 * @return an APPC request conforming to the lcm API using the DMAAP wrapper
189 public static AppcLcmDmaapWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
190 Policy policy, String targetVnf) {
192 /* Construct an APPC request using LCM Model */
195 * The actual LCM request is placed in a wrapper used to send through dmaap. The current
196 * version is 2.0 as of R1.
198 AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
200 AppcLcmDmaapWrapper dmaapRequest = new AppcLcmDmaapWrapper();
201 dmaapRequest.setVersion("2.0");
202 dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
203 dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
204 dmaapRequest.setType("request");
206 /* This is the actual request that is placed in the dmaap wrapper. */
207 final AppcLcmInput appcRequest = new AppcLcmInput();
209 /* The common header is a required field for all APPC requests. */
210 AppcLcmCommonHeader requestCommonHeader = new AppcLcmCommonHeader();
211 requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
212 requestCommonHeader.setRequestId(onset.getRequestId());
213 requestCommonHeader.setSubRequestId(operation.getSubRequestId());
215 appcRequest.setCommonHeader(requestCommonHeader);
218 * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
219 * Policy only require a vnf-id.
221 HashMap<String, String> requestActionIdentifiers = new HashMap<>();
222 requestActionIdentifiers.put("vnf-id", targetVnf);
224 appcRequest.setActionIdentifiers(requestActionIdentifiers);
227 * An action is required for all APPC requests, this will be the recipe specified in the
230 appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
233 * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate recipes.
234 * APPC will populate the payload based on A&AI look up of the vnd-id provided in the action
237 if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
238 appcRequest.setPayload(parsePayload(policy.getPayload()));
240 appcRequest.setPayload(null);
244 * The APPC request must be wrapped in an input object.
246 AppcLcmBody body = new AppcLcmBody();
247 body.setInput(appcRequest);
250 * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
252 dmaapRequest.setBody(body);
254 /* Return the request to be sent through dmaap. */
258 private static boolean payloadSupplied(Map<String, String> payload) {
259 return payload != null && !payload.isEmpty();
262 private static boolean recipeSupportsPayload(String recipe) {
263 return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
264 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
267 private static String parsePayload(Map<String, String> payload) {
268 StringBuilder payloadString = new StringBuilder("{");
270 .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
271 return payloadString.substring(0, payloadString.length() - 1) + "}";
275 * Parses the operation attempt using the subRequestId of APPC response.
277 * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
280 * @return the current operation attempt
282 public static Integer parseOperationAttempt(String subRequestId) {
283 Integer operationAttempt;
285 operationAttempt = Integer.parseInt(subRequestId);
286 } catch (NumberFormatException e) {
287 logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
290 return operationAttempt;
294 * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
295 * successful/unsuccessful and maps this to the corresponding Policy result.
297 * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
300 * @return an key-value pair that contains the Policy result and APPC response message
302 public static SimpleEntry<PolicyResult, String> processResponse(AppcLcmDmaapWrapper dmaapResponse) {
303 AppcLcmBody appcBody = dmaapResponse.getBody();
304 if (appcBody == null) {
305 throw new NullPointerException("APPC Body is null");
308 /* The actual APPC response is inside the dmaap wrapper's body.input field. */
309 AppcLcmOutput appcResponse = appcBody.getOutput();
310 if (appcResponse == null) {
311 throw new NullPointerException("APPC Response is null");
314 /* The message returned in the APPC response. */
317 /* The Policy result determined from the APPC Response. */
320 /* If there is no status, Policy cannot determine if the request was successful. */
321 if (appcResponse.getStatus() == null) {
322 message = "Policy was unable to parse APP-C response status field (it was null).";
323 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
326 /* If there is no code, Policy cannot determine if the request was successful. */
327 String responseValue = AppcLcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
328 if (responseValue == null) {
329 message = "Policy was unable to parse APP-C response status code field.";
330 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
333 /* Save the APPC response's message for Policy notification message. */
334 message = appcResponse.getStatus().getMessage();
336 /* Maps the APPC response result to a Policy result. */
337 switch (responseValue) {
338 case AppcLcmResponseCode.ACCEPTED:
339 /* Nothing to do if code is accept, continue processing */
342 case AppcLcmResponseCode.SUCCESS:
343 result = PolicyResult.SUCCESS;
345 case AppcLcmResponseCode.FAILURE:
346 result = PolicyResult.FAILURE;
348 case AppcLcmResponseCode.REJECT:
349 case AppcLcmResponseCode.ERROR:
351 result = PolicyResult.FAILURE_EXCEPTION;
353 return new AbstractMap.SimpleEntry<>(result, message);