2 * ============LICENSE_START=======================================================
3 * AppcLcmActorServiceProvider
4 * ================================================================================
5 * Copyright (C) 2017 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.AAINQInstanceFilters;
35 import org.onap.policy.aai.AAINQInventoryResponseItem;
36 import org.onap.policy.aai.AAIGETVnfResponse;
37 import org.onap.policy.aai.AAIManager;
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.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class AppcLcmActorServiceProvider implements Actor {
60 private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
62 /* The source vnf-id provided from the DCAE onset */
63 private static final String DCAE_VNF_ID = "generic-vnf.vnf-id";
65 /* To be used in future releases to restart a single vm */
66 private static final String APPC_VM_ID = "vm-id";
68 /* To be used in future releases when LCM ConfigModify is used */
69 private static final String APPC_REQUEST_PARAMS = "request-parameters";
70 private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
72 private static final ImmutableList<String> recipes = ImmutableList.of("Restart", "Rebuild", "Migrate",
74 private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
75 .put("Restart", ImmutableList.of("VM")).put("Rebuild", ImmutableList.of("VM"))
76 .put("Migrate", ImmutableList.of("VM")).put("ConfigModify", ImmutableList.of("VNF")).build();
77 private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>()
78 .put("Restart", ImmutableList.of(APPC_VM_ID))
79 .put("ConfigModify", ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
82 public String actor() {
87 public List<String> recipes() {
88 return ImmutableList.copyOf(recipes);
92 public List<String> recipeTargets(String recipe) {
93 return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
97 public List<String> recipePayloads(String recipe) {
98 return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
102 * This method recursively traverses the A&AI named query response
103 * to find the generic-vnf object that contains a model-invariant-id
104 * that matches the resourceId of the policy. Once this match is found
105 * the generic-vnf object's vnf-id is returned.
108 * the list of items related to the vnf returned by A&AI
110 * the id of the target from the sdc catalog
112 * @return the vnf-id of the target vnf to act upon or null if not found
114 private static String parseAAIResponse(List<AAINQInventoryResponseItem> items, String resourceId) {
116 for (AAINQInventoryResponseItem item: items) {
117 if ((item.genericVNF != null)
118 && (item.genericVNF.modelInvariantId != null)
119 && (resourceId.equals(item.genericVNF.modelInvariantId))) {
120 vnfId = item.genericVNF.vnfID;
124 if((item.items != null) && (item.items.inventoryResponseItems != null)) {
125 vnfId = parseAAIResponse(item.items.inventoryResponseItems, resourceId);
133 * Constructs an A&AI Named Query using a source vnf-id to determine
134 * the vnf-id of the target entity specified in the policy to act upon.
137 * the id of the target from the sdc catalog
140 * the vnf id of the source entity reporting the alert
142 * @return the target entities vnf id to act upon
143 * @throws AAIException
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.queryParameters = new AAINQQueryParameters();
152 aaiRequest.queryParameters.namedQuery = new AAINQNamedQuery();
153 aaiRequest.queryParameters.namedQuery.namedQueryUUID = 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.instanceFilters = new AAINQInstanceFilters();
162 aaiRequest.instanceFilters.instanceFilter.add(filter);
165 * Obtain A&AI credentials from properties.environment file
166 * TODO: What if these are null?
168 String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url");
169 String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username");
170 String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
172 AAINQResponse aaiResponse = AAIManager.postQuery(
174 aaiUsername, aaiPassword,
175 aaiRequest, requestId);
177 if (aaiResponse == null) {
178 throw new AAIException("The named query response was null");
181 String targetVnfId = parseAAIResponse(aaiResponse.inventoryResponseItems, resourceId);
182 if (targetVnfId == null) {
183 throw new AAIException("Target vnf-id could not be found");
190 * Constructs an APPC request conforming to the lcm API.
191 * The actual request is constructed and then placed in a
192 * wrapper object used to send through DMAAP.
195 * the event that is reporting the alert for policy
196 * to perform an action
198 * the control loop operation specifying the actor,
199 * operation, target, etc.
201 * the policy the was specified from the yaml generated
202 * by CLAMP or through the Policy GUI/API
203 * @return an APPC request conforming to the lcm API using the DMAAP wrapper
204 * @throws AAIException
206 public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset,
207 ControlLoopOperation operation, Policy policy, AAIGETVnfResponse vnfResponse) throws AAIException {
209 /* Construct an APPC request using LCM Model */
212 * The actual LCM request is placed in a wrapper used to send
213 * through dmaap. The current version is 2.0 as of R1.
215 LCMRequestWrapper dmaapRequest = new LCMRequestWrapper();
216 dmaapRequest.setVersion("2.0");
217 dmaapRequest.setCorrelationId(onset.requestID + "-" + operation.subRequestId);
218 dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
219 dmaapRequest.setType("request");
221 /* This is the actual request that is placed in the dmaap wrapper. */
222 LCMRequest appcRequest = new LCMRequest();
224 /* The common header is a required field for all APPC requests. */
225 LCMCommonHeader requestCommonHeader = new LCMCommonHeader();
226 requestCommonHeader.setOriginatorId(onset.requestID.toString());
227 requestCommonHeader.setRequestId(onset.requestID);
228 requestCommonHeader.setSubRequestId(operation.subRequestId);
230 appcRequest.setCommonHeader(requestCommonHeader);
233 * Action Identifiers are required for APPC LCM requests.
234 * For R1, the recipes supported by Policy only require
237 HashMap<String, String> requestActionIdentifiers = new HashMap<>();
238 String vnfId = onset.AAI.get(DCAE_VNF_ID);
240 vnfId = vnfResponse.vnfID;
242 throw new AAIException("No vnf-id found");
245 requestActionIdentifiers.put("vnf-id", vnfId);
247 appcRequest.setActionIdentifiers(requestActionIdentifiers);
250 * An action is required for all APPC requests, this will
251 * be the recipe specified in the policy.
253 appcRequest.setAction(policy.getRecipe().substring(0, 1).toUpperCase()
254 + policy.getRecipe().substring(1).toLowerCase());
257 * For R1, the payloads will not be required for the Restart,
258 * Rebuild, or Migrate recipes. APPC will populate the payload
259 * based on A&AI look up of the vnd-id provided in the action
262 if ("Restart".equalsIgnoreCase(policy.getRecipe()) || "Rebuild".equalsIgnoreCase(policy.getRecipe())
263 || "Migrate".equalsIgnoreCase(policy.getRecipe())) {
264 appcRequest.setPayload(null);
268 * Once the LCM request is constructed, add it into the
269 * body of the dmaap wrapper.
271 dmaapRequest.setBody(appcRequest);
273 /* Return the request to be sent through dmaap. */
278 * Parses the operation attempt using the subRequestId
281 * @param subRequestId
282 * the sub id used to send to APPC, Policy sets
283 * this using the operation attempt
285 * @return the current operation attempt
287 public static Integer parseOperationAttempt(String subRequestId) {
288 Integer operationAttempt;
290 operationAttempt = Integer.parseInt(subRequestId);
291 } catch (NumberFormatException e) {
292 logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
295 return operationAttempt;
299 * Processes the APPC LCM response sent from APPC. Determines
300 * if the APPC operation was successful/unsuccessful and maps
301 * this to the corresponding Policy result.
303 * @param dmaapResponse
304 * the dmaap wrapper message that contains the
305 * actual APPC reponse inside the body field
307 * @return an key-value pair that contains the Policy result
308 * and APPC response message
310 public static SimpleEntry<PolicyResult, String> processResponse(LCMResponseWrapper dmaapResponse) {
311 /* The actual APPC response is inside the wrapper's body field. */
312 LCMResponse appcResponse = dmaapResponse.getBody();
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 = LCMResponseCode.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 noticiation message. */
334 message = appcResponse.getStatus().getMessage();
336 /* Maps the APPC response result to a Policy result. */
337 switch (responseValue) {
338 case LCMResponseCode.ACCEPTED:
339 /* Nothing to do if code is accept, continue processing */
342 case LCMResponseCode.SUCCESS:
343 result = PolicyResult.SUCCESS;
345 case LCMResponseCode.FAILURE:
346 result = PolicyResult.FAILURE;
348 case LCMResponseCode.REJECT:
349 case LCMResponseCode.ERROR:
351 result = PolicyResult.FAILURE_EXCEPTION;
353 return new AbstractMap.SimpleEntry<>(result, message);