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 * ================================================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.policy.controlloop.actor.appclcm;
24 import com.google.common.collect.ImmutableList;
25 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;
35 import org.onap.policy.aai.AaiManager;
36 import org.onap.policy.aai.AaiNqInstanceFilters;
37 import org.onap.policy.aai.AaiNqInventoryResponseItem;
38 import org.onap.policy.aai.AaiNqNamedQuery;
39 import org.onap.policy.aai.AaiNqQueryParameters;
40 import org.onap.policy.aai.AaiNqRequest;
41 import org.onap.policy.aai.AaiNqResponse;
42 import org.onap.policy.aai.util.AaiException;
43 import org.onap.policy.appclcm.LcmCommonHeader;
44 import org.onap.policy.appclcm.LcmRequest;
45 import org.onap.policy.appclcm.LcmRequestWrapper;
46 import org.onap.policy.appclcm.LcmResponse;
47 import org.onap.policy.appclcm.LcmResponseCode;
48 import org.onap.policy.appclcm.LcmResponseWrapper;
49 import org.onap.policy.controlloop.ControlLoopOperation;
50 import org.onap.policy.controlloop.VirtualControlLoopEvent;
51 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
52 import org.onap.policy.controlloop.policy.Policy;
53 import org.onap.policy.controlloop.policy.PolicyResult;
54 import org.onap.policy.drools.system.PolicyEngine;
55 import org.onap.policy.rest.RestManager;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public class AppcLcmActorServiceProvider implements Actor {
61 private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
63 /* To be used in future releases to restart a single vm */
64 private static final String APPC_VM_ID = "vm-id";
66 // Strings for targets
67 private static final String TARGET_VM = "VM";
68 private static final String TARGET_VNF = "VNF";
70 // Strings for recipes
71 private static final String RECIPE_RESTART = "Restart";
72 private static final String RECIPE_REBUILD = "Rebuild";
73 private static final String RECIPE_MIGRATE = "Migrate";
74 private static final String RECIPE_MODIFY = "ConfigModify";
76 /* To be used in future releases when LCM ConfigModify is used */
77 private static final String APPC_REQUEST_PARAMS = "request-parameters";
78 private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
80 private static final ImmutableList<String> recipes =
81 ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
82 private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
83 .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
84 .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
85 private static final ImmutableMap<String, List<String>> payloads =
86 new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
87 .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
90 public String actor() {
95 public List<String> recipes() {
96 return ImmutableList.copyOf(recipes);
100 public List<String> recipeTargets(String recipe) {
101 return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
105 public List<String> recipePayloads(String recipe) {
106 return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
110 * This method recursively traverses the A&AI named query response to find the generic-vnf
111 * object that contains a model-invariant-id that matches the resourceId of the policy. Once
112 * this match is found the generic-vnf object's vnf-id is returned.
114 * @param items the list of items related to the vnf returned by A&AI
115 * @param resourceId the id of the target from the sdc catalog
117 * @return the vnf-id of the target vnf to act upon or null if not found
119 private static String parseAaiResponse(List<AaiNqInventoryResponseItem> items, String resourceId) {
121 for (AaiNqInventoryResponseItem item : items) {
122 if ((item.getGenericVnf() != null) && (item.getGenericVnf().getModelInvariantId() != null)
123 && (resourceId.equals(item.getGenericVnf().getModelInvariantId()))) {
124 vnfId = item.getGenericVnf().getVnfId();
127 if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
128 vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
136 * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target
137 * entity specified in the policy to act upon.
139 * @param resourceId the id of the target from the sdc catalog
141 * @param sourceVnfId the vnf id of the source entity reporting the alert
143 * @return the target entities vnf id to act upon
144 * @throws AaiException it an error occurs
146 public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AaiException {
148 // TODO: This request id should not be hard coded in future releases
149 UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
151 AaiNqRequest aaiRequest = new AaiNqRequest();
152 aaiRequest.setQueryParameters(new AaiNqQueryParameters());
153 aaiRequest.getQueryParameters().setNamedQuery(new AaiNqNamedQuery());
154 aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUuid(requestId);
156 Map<String, Map<String, String>> filter = new HashMap<>();
157 Map<String, String> filterItem = new HashMap<>();
159 filterItem.put("vnf-id", sourceVnfId);
160 filter.put("generic-vnf", filterItem);
162 aaiRequest.setInstanceFilters(new AaiNqInstanceFilters());
163 aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
165 AaiNqResponse aaiResponse = new AaiManager(new RestManager()).postQuery(getPeManagerEnvProperty("aai.url"),
166 getPeManagerEnvProperty("aai.username"), getPeManagerEnvProperty("aai.password"), aaiRequest,
169 if (aaiResponse == null) {
170 throw new AaiException("The named query response was null");
173 String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
174 if (targetVnfId == null) {
175 throw new AaiException("Target vnf-id could not be found");
182 * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
183 * then placed in a wrapper object used to send through DMAAP.
185 * @param onset the event that is reporting the alert for policy to perform an action
186 * @param operation the control loop operation specifying the actor, operation, target, etc.
187 * @param policy the policy the was specified from the yaml generated by CLAMP or through the
189 * @return an APPC request conforming to the lcm API using the DMAAP wrapper
191 public static LcmRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
192 Policy policy, String targetVnf) {
194 /* Construct an APPC request using LCM Model */
197 * The actual LCM request is placed in a wrapper used to send through dmaap. The current
198 * version is 2.0 as of R1.
200 AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
202 LcmRequestWrapper dmaapRequest = new LcmRequestWrapper();
203 dmaapRequest.setVersion("2.0");
204 dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
205 dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
206 dmaapRequest.setType("request");
208 /* This is the actual request that is placed in the dmaap wrapper. */
209 final LcmRequest appcRequest = new LcmRequest();
211 /* The common header is a required field for all APPC requests. */
212 LcmCommonHeader requestCommonHeader = new LcmCommonHeader();
213 requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
214 requestCommonHeader.setRequestId(onset.getRequestId());
215 requestCommonHeader.setSubRequestId(operation.getSubRequestId());
217 appcRequest.setCommonHeader(requestCommonHeader);
220 * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
221 * Policy only require a vnf-id.
223 HashMap<String, String> requestActionIdentifiers = new HashMap<>();
224 requestActionIdentifiers.put("vnf-id", targetVnf);
226 appcRequest.setActionIdentifiers(requestActionIdentifiers);
229 * An action is required for all APPC requests, this will be the recipe specified in the
232 appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
235 * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate recipes.
236 * APPC will populate the payload based on A&AI look up of the vnd-id provided in the action
239 if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
240 appcRequest.setPayload(parsePayload(policy.getPayload()));
242 appcRequest.setPayload(null);
246 * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
248 dmaapRequest.setBody(appcRequest);
250 /* Return the request to be sent through dmaap. */
254 private static boolean payloadSupplied(Map<String, String> payload) {
255 return payload != null && !payload.isEmpty();
258 private static boolean recipeSupportsPayload(String recipe) {
259 return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
260 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
263 private static String parsePayload(Map<String, String> payload) {
264 StringBuilder payloadString = new StringBuilder("{");
266 .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
267 return payloadString.substring(0, payloadString.length() - 1) + "}";
271 * Parses the operation attempt using the subRequestId of APPC response.
273 * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
276 * @return the current operation attempt
278 public static Integer parseOperationAttempt(String subRequestId) {
279 Integer operationAttempt;
281 operationAttempt = Integer.parseInt(subRequestId);
282 } catch (NumberFormatException e) {
283 logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
286 return operationAttempt;
290 * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
291 * successful/unsuccessful and maps this to the corresponding Policy result.
293 * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
296 * @return an key-value pair that contains the Policy result and APPC response message
298 public static SimpleEntry<PolicyResult, String> processResponse(LcmResponseWrapper dmaapResponse) {
299 /* The actual APPC response is inside the wrapper's body field. */
300 LcmResponse appcResponse = dmaapResponse.getBody();
302 /* The message returned in the APPC response. */
305 /* The Policy result determined from the APPC Response. */
308 /* If there is no status, Policy cannot determine if the request was successful. */
309 if (appcResponse.getStatus() == null) {
310 message = "Policy was unable to parse APP-C response status field (it was null).";
311 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
314 /* If there is no code, Policy cannot determine if the request was successful. */
315 String responseValue = LcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
316 if (responseValue == null) {
317 message = "Policy was unable to parse APP-C response status code field.";
318 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
321 /* Save the APPC response's message for Policy notification message. */
322 message = appcResponse.getStatus().getMessage();
324 /* Maps the APPC response result to a Policy result. */
325 switch (responseValue) {
326 case LcmResponseCode.ACCEPTED:
327 /* Nothing to do if code is accept, continue processing */
330 case LcmResponseCode.SUCCESS:
331 result = PolicyResult.SUCCESS;
333 case LcmResponseCode.FAILURE:
334 result = PolicyResult.FAILURE;
336 case LcmResponseCode.REJECT:
337 case LcmResponseCode.ERROR:
339 result = PolicyResult.FAILURE_EXCEPTION;
341 return new AbstractMap.SimpleEntry<>(result, message);
345 * This method reads and validates environmental properties coming from the policy engine. Null
346 * properties cause an {@link IllegalArgumentException} runtime exception to be thrown
348 * @param enginePropertyName the name of the parameter to retrieve
349 * @return the property value
351 private static String getPeManagerEnvProperty(String enginePropertyName) {
352 String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName);
353 if (enginePropertyValue == null) {
354 throw new IllegalArgumentException("The value of policy engine manager environment property \""
355 + enginePropertyName + "\" may not be null");
357 return enginePropertyValue;