2 * ============LICENSE_START=======================================================
3 * AppcLcmActorServiceProvider
4 * ================================================================================
5 * Copyright (C) 2017-2018 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 com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
26 import java.util.AbstractMap;
27 import java.util.AbstractMap.SimpleEntry;
28 import java.util.Collections;
29 import java.util.HashMap;
30 import java.util.List;
32 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.LCMCommonHeader;
43 import org.onap.policy.appclcm.LCMRequest;
44 import org.onap.policy.appclcm.LCMRequestWrapper;
45 import org.onap.policy.appclcm.LCMResponse;
46 import org.onap.policy.appclcm.LCMResponseCode;
47 import org.onap.policy.appclcm.LCMResponseWrapper;
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.drools.system.PolicyEngine;
54 import org.onap.policy.rest.RESTManager;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class AppcLcmActorServiceProvider implements Actor {
60 private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
62 /* To be used in future releases to restart a single vm */
63 private static final String APPC_VM_ID = "vm-id";
65 // Strings for targets
66 private static final String TARGET_VM = "VM";
67 private static final String TARGET_VNF = "VNF";
69 // Strings for recipes
70 private static final String RECIPE_RESTART = "Restart";
71 private static final String RECIPE_REBUILD = "Rebuild";
72 private static final String RECIPE_MIGRATE = "Migrate";
73 private static final String RECIPE_MODIFY = "ConfigModify";
75 /* To be used in future releases when LCM ConfigModify is used */
76 private static final String APPC_REQUEST_PARAMS = "request-parameters";
77 private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
79 private static final ImmutableList<String> recipes =
80 ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
81 private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
82 .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
83 .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
84 private static final ImmutableMap<String, List<String>> payloads =
85 new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
86 .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
89 public String actor() {
94 public List<String> recipes() {
95 return ImmutableList.copyOf(recipes);
99 public List<String> recipeTargets(String recipe) {
100 return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
104 public List<String> recipePayloads(String recipe) {
105 return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
109 * This method recursively traverses the A&AI named query response to find the generic-vnf
110 * object that contains a model-invariant-id that matches the resourceId of the policy. Once
111 * this match is found the generic-vnf object's vnf-id is returned.
113 * @param items the list of items related to the vnf returned by A&AI
114 * @param resourceId the id of the target from the sdc catalog
116 * @return the vnf-id of the target vnf to act upon or null if not found
118 private static String parseAaiResponse(List<AAINQInventoryResponseItem> items, String resourceId) {
120 for (AAINQInventoryResponseItem item : items) {
121 if ((item.getGenericVNF() != null) && (item.getGenericVNF().getModelInvariantId() != null)
122 && (resourceId.equals(item.getGenericVNF().getModelInvariantId()))) {
123 vnfId = item.getGenericVNF().getVnfID();
126 if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
127 vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
135 * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target
136 * entity specified in the policy to act upon.
138 * @param resourceId the id of the target from the sdc catalog
140 * @param sourceVnfId the vnf id of the source entity reporting the alert
142 * @return the target entities vnf id to act upon
143 * @throws AAIException it an error occurs
145 public static String vnfNamedQuery(String resourceId, String sourceVnfId) 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(getPeManagerEnvProperty("aai.url"),
165 getPeManagerEnvProperty("aai.username"), getPeManagerEnvProperty("aai.password"), aaiRequest,
168 if (aaiResponse == null) {
169 throw new AAIException("The named query response was null");
172 String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
173 if (targetVnfId == null) {
174 throw new AAIException("Target vnf-id could not be found");
181 * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
182 * then placed in a wrapper object used to send through DMAAP.
184 * @param onset the event that is reporting the alert for policy to perform an action
185 * @param operation the control loop operation specifying the actor, operation, target, etc.
186 * @param policy the policy the was specified from the yaml generated by CLAMP or through the
188 * @return an APPC request conforming to the lcm API using the DMAAP wrapper
190 public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
191 Policy policy, String targetVnf) {
193 /* Construct an APPC request using LCM Model */
196 * The actual LCM request is placed in a wrapper used to send through dmaap. The current
197 * version is 2.0 as of R1.
199 LCMRequestWrapper dmaapRequest = new LCMRequestWrapper();
200 dmaapRequest.setVersion("2.0");
201 dmaapRequest.setCorrelationId(onset.getRequestID() + "-" + operation.getSubRequestId());
202 dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
203 dmaapRequest.setType("request");
205 /* This is the actual request that is placed in the dmaap wrapper. */
206 final LCMRequest appcRequest = new LCMRequest();
208 /* The common header is a required field for all APPC requests. */
209 LCMCommonHeader requestCommonHeader = new LCMCommonHeader();
210 requestCommonHeader.setOriginatorId(onset.getRequestID().toString());
211 requestCommonHeader.setRequestId(onset.getRequestID());
212 requestCommonHeader.setSubRequestId(operation.getSubRequestId());
214 appcRequest.setCommonHeader(requestCommonHeader);
217 * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
218 * Policy only require a vnf-id.
220 HashMap<String, String> requestActionIdentifiers = new HashMap<>();
221 requestActionIdentifiers.put("vnf-id", targetVnf);
223 appcRequest.setActionIdentifiers(requestActionIdentifiers);
226 * An action is required for all APPC requests, this will be the recipe specified in the
229 appcRequest.setAction(
230 policy.getRecipe().substring(0, 1).toUpperCase() + policy.getRecipe().substring(1).toLowerCase());
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 (RECIPE_RESTART.equalsIgnoreCase(policy.getRecipe()) || RECIPE_REBUILD.equalsIgnoreCase(policy.getRecipe())
238 || RECIPE_MIGRATE.equalsIgnoreCase(policy.getRecipe())) {
239 appcRequest.setPayload(null);
243 * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
245 dmaapRequest.setBody(appcRequest);
247 /* Return the request to be sent through dmaap. */
252 * Parses the operation attempt using the subRequestId of APPC response.
254 * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
257 * @return the current operation attempt
259 public static Integer parseOperationAttempt(String subRequestId) {
260 Integer operationAttempt;
262 operationAttempt = Integer.parseInt(subRequestId);
263 } catch (NumberFormatException e) {
264 logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
267 return operationAttempt;
271 * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
272 * successful/unsuccessful and maps this to the corresponding Policy result.
274 * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
277 * @return an key-value pair that contains the Policy result and APPC response message
279 public static SimpleEntry<PolicyResult, String> processResponse(LCMResponseWrapper dmaapResponse) {
280 /* The actual APPC response is inside the wrapper's body field. */
281 LCMResponse appcResponse = dmaapResponse.getBody();
283 /* The message returned in the APPC response. */
286 /* The Policy result determined from the APPC Response. */
289 /* If there is no status, Policy cannot determine if the request was successful. */
290 if (appcResponse.getStatus() == null) {
291 message = "Policy was unable to parse APP-C response status field (it was null).";
292 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
295 /* If there is no code, Policy cannot determine if the request was successful. */
296 String responseValue = LCMResponseCode.toResponseValue(appcResponse.getStatus().getCode());
297 if (responseValue == null) {
298 message = "Policy was unable to parse APP-C response status code field.";
299 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
302 /* Save the APPC response's message for Policy noticiation message. */
303 message = appcResponse.getStatus().getMessage();
305 /* Maps the APPC response result to a Policy result. */
306 switch (responseValue) {
307 case LCMResponseCode.ACCEPTED:
308 /* Nothing to do if code is accept, continue processing */
311 case LCMResponseCode.SUCCESS:
312 result = PolicyResult.SUCCESS;
314 case LCMResponseCode.FAILURE:
315 result = PolicyResult.FAILURE;
317 case LCMResponseCode.REJECT:
318 case LCMResponseCode.ERROR:
320 result = PolicyResult.FAILURE_EXCEPTION;
322 return new AbstractMap.SimpleEntry<>(result, message);
326 * This method reads and validates environmental properties coming from the policy engine. Null
327 * properties cause an {@link IllegalArgumentException} runtime exception to be thrown
329 * @param string the name of the parameter to retrieve
330 * @return the property value
332 private static String getPeManagerEnvProperty(String enginePropertyName) {
333 String enginePropertyValue = PolicyEngine.manager.getEnvironmentProperty(enginePropertyName);
334 if (enginePropertyValue == null) {
335 throw new IllegalArgumentException("The value of policy engine manager environment property \""
336 + enginePropertyName + "\" may not be null");
338 return enginePropertyValue;