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;
28 import java.util.AbstractMap;
29 import java.util.AbstractMap.SimpleEntry;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.List;
34 import java.util.UUID;
36 import org.onap.policy.aai.AaiManager;
37 import org.onap.policy.aai.AaiNqInstanceFilters;
38 import org.onap.policy.aai.AaiNqInventoryResponseItem;
39 import org.onap.policy.aai.AaiNqNamedQuery;
40 import org.onap.policy.aai.AaiNqQueryParameters;
41 import org.onap.policy.aai.AaiNqRequest;
42 import org.onap.policy.aai.AaiNqResponse;
43 import org.onap.policy.aai.util.AaiException;
44 import org.onap.policy.appclcm.LcmCommonHeader;
45 import org.onap.policy.appclcm.LcmRequest;
46 import org.onap.policy.appclcm.LcmRequestWrapper;
47 import org.onap.policy.appclcm.LcmResponse;
48 import org.onap.policy.appclcm.LcmResponseCode;
49 import org.onap.policy.appclcm.LcmResponseWrapper;
50 import org.onap.policy.controlloop.ControlLoopOperation;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
53 import org.onap.policy.controlloop.policy.Policy;
54 import org.onap.policy.controlloop.policy.PolicyResult;
55 import org.onap.policy.drools.system.PolicyEngine;
56 import org.onap.policy.rest.RestManager;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 public class AppcLcmActorServiceProvider implements Actor {
62 private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
64 /* To be used in future releases to restart a single vm */
65 private static final String APPC_VM_ID = "vm-id";
67 // Strings for targets
68 private static final String TARGET_VM = "VM";
69 private static final String TARGET_VNF = "VNF";
71 // Strings for recipes
72 private static final String RECIPE_RESTART = "Restart";
73 private static final String RECIPE_REBUILD = "Rebuild";
74 private static final String RECIPE_MIGRATE = "Migrate";
75 private static final String RECIPE_MODIFY = "ConfigModify";
77 /* To be used in future releases when LCM ConfigModify is used */
78 private static final String APPC_REQUEST_PARAMS = "request-parameters";
79 private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
81 private static final ImmutableList<String> recipes =
82 ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
83 private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
84 .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
85 .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
86 private static final ImmutableMap<String, List<String>> payloads =
87 new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
88 .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
91 public String actor() {
96 public List<String> recipes() {
97 return ImmutableList.copyOf(recipes);
101 public List<String> recipeTargets(String recipe) {
102 return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
106 public List<String> recipePayloads(String recipe) {
107 return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
111 * This method recursively traverses the A&AI named query response to find the generic-vnf
112 * object that contains a model-invariant-id that matches the resourceId of the policy. Once
113 * this match is found the generic-vnf object's vnf-id is returned.
115 * @param items the list of items related to the vnf returned by A&AI
116 * @param resourceId the id of the target from the sdc catalog
118 * @return the vnf-id of the target vnf to act upon or null if not found
120 private static String parseAaiResponse(List<AaiNqInventoryResponseItem> items, String resourceId) {
122 for (AaiNqInventoryResponseItem item : items) {
123 if ((item.getGenericVnf() != null) && (item.getGenericVnf().getModelInvariantId() != null)
124 && (resourceId.equals(item.getGenericVnf().getModelInvariantId()))) {
125 vnfId = item.getGenericVnf().getVnfId();
128 if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
129 vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
137 * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target
138 * entity specified in the policy to act upon.
140 * @param resourceId the id of the target from the sdc catalog
142 * @param sourceVnfId the vnf id of the source entity reporting the alert
144 * @return the target entities vnf id to act upon
145 * @throws AaiException it an error occurs
147 public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AaiException {
149 // TODO: This request id should not be hard coded in future releases
150 UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
152 AaiNqRequest aaiRequest = new AaiNqRequest();
153 aaiRequest.setQueryParameters(new AaiNqQueryParameters());
154 aaiRequest.getQueryParameters().setNamedQuery(new AaiNqNamedQuery());
155 aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUuid(requestId);
157 Map<String, Map<String, String>> filter = new HashMap<>();
158 Map<String, String> filterItem = new HashMap<>();
160 filterItem.put("vnf-id", sourceVnfId);
161 filter.put("generic-vnf", filterItem);
163 aaiRequest.setInstanceFilters(new AaiNqInstanceFilters());
164 aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
166 AaiNqResponse aaiResponse = new AaiManager(new RestManager()).postQuery(getPeManagerEnvProperty("aai.url"),
167 getPeManagerEnvProperty("aai.username"), getPeManagerEnvProperty("aai.password"), aaiRequest,
170 if (aaiResponse == null) {
171 throw new AaiException("The named query response was null");
174 String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
175 if (targetVnfId == null) {
176 throw new AaiException("Target vnf-id could not be found");
183 * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
184 * then placed in a wrapper object used to send through DMAAP.
186 * @param onset the event that is reporting the alert for policy to perform an action
187 * @param operation the control loop operation specifying the actor, operation, target, etc.
188 * @param policy the policy the was specified from the yaml generated by CLAMP or through the
190 * @return an APPC request conforming to the lcm API using the DMAAP wrapper
192 public static LcmRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
193 Policy policy, String targetVnf) {
195 /* Construct an APPC request using LCM Model */
198 * The actual LCM request is placed in a wrapper used to send through dmaap. The current
199 * version is 2.0 as of R1.
201 AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
203 LcmRequestWrapper dmaapRequest = new LcmRequestWrapper();
204 dmaapRequest.setVersion("2.0");
205 dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
206 dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
207 dmaapRequest.setType("request");
209 /* This is the actual request that is placed in the dmaap wrapper. */
210 final LcmRequest appcRequest = new LcmRequest();
212 /* The common header is a required field for all APPC requests. */
213 LcmCommonHeader requestCommonHeader = new LcmCommonHeader();
214 requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
215 requestCommonHeader.setRequestId(onset.getRequestId());
216 requestCommonHeader.setSubRequestId(operation.getSubRequestId());
218 appcRequest.setCommonHeader(requestCommonHeader);
221 * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
222 * Policy only require a vnf-id.
224 HashMap<String, String> requestActionIdentifiers = new HashMap<>();
225 requestActionIdentifiers.put("vnf-id", targetVnf);
227 appcRequest.setActionIdentifiers(requestActionIdentifiers);
230 * An action is required for all APPC requests, this will be the recipe specified in the
233 appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
236 * For R1, the payloads will not be required for the Restart, Rebuild, or Migrate recipes.
237 * APPC will populate the payload based on A&AI look up of the vnd-id provided in the action
240 if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
241 appcRequest.setPayload(parsePayload(policy.getPayload()));
243 appcRequest.setPayload(null);
247 * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
249 dmaapRequest.setBody(appcRequest);
251 /* Return the request to be sent through dmaap. */
255 private static boolean payloadSupplied(Map<String, String> payload) {
256 return payload != null && !payload.isEmpty();
259 private static boolean recipeSupportsPayload(String recipe) {
260 return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
261 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
264 private static String parsePayload(Map<String, String> payload) {
265 StringBuilder payloadString = new StringBuilder("{");
267 .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
268 return payloadString.substring(0, payloadString.length() - 1) + "}";
272 * Parses the operation attempt using the subRequestId of APPC response.
274 * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
277 * @return the current operation attempt
279 public static Integer parseOperationAttempt(String subRequestId) {
280 Integer operationAttempt;
282 operationAttempt = Integer.parseInt(subRequestId);
283 } catch (NumberFormatException e) {
284 logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
287 return operationAttempt;
291 * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
292 * successful/unsuccessful and maps this to the corresponding Policy result.
294 * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
297 * @return an key-value pair that contains the Policy result and APPC response message
299 public static SimpleEntry<PolicyResult, String> processResponse(LcmResponseWrapper dmaapResponse) {
300 /* The actual APPC response is inside the wrapper's body field. */
301 LcmResponse appcResponse = dmaapResponse.getBody();
303 /* The message returned in the APPC response. */
306 /* The Policy result determined from the APPC Response. */
309 /* If there is no status, Policy cannot determine if the request was successful. */
310 if (appcResponse.getStatus() == null) {
311 message = "Policy was unable to parse APP-C response status field (it was null).";
312 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
315 /* If there is no code, Policy cannot determine if the request was successful. */
316 String responseValue = LcmResponseCode.toResponseValue(appcResponse.getStatus().getCode());
317 if (responseValue == null) {
318 message = "Policy was unable to parse APP-C response status code field.";
319 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
322 /* Save the APPC response's message for Policy notification message. */
323 message = appcResponse.getStatus().getMessage();
325 /* Maps the APPC response result to a Policy result. */
326 switch (responseValue) {
327 case LcmResponseCode.ACCEPTED:
328 /* Nothing to do if code is accept, continue processing */
331 case LcmResponseCode.SUCCESS:
332 result = PolicyResult.SUCCESS;
334 case LcmResponseCode.FAILURE:
335 result = PolicyResult.FAILURE;
337 case LcmResponseCode.REJECT:
338 case LcmResponseCode.ERROR:
340 result = PolicyResult.FAILURE_EXCEPTION;
342 return new AbstractMap.SimpleEntry<>(result, message);
346 * This method reads and validates environmental properties coming from the policy engine. Null
347 * properties cause an {@link IllegalArgumentException} runtime exception to be thrown
349 * @param enginePropertyName the name of the parameter to retrieve
350 * @return the property value
352 private static String getPeManagerEnvProperty(String enginePropertyName) {
353 String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName);
354 if (enginePropertyValue == null) {
355 throw new IllegalArgumentException("The value of policy engine manager environment property \""
356 + enginePropertyName + "\" may not be null");
358 return enginePropertyValue;