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.AAIManager;
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 /* To be used in future releases when LCM ConfigModify is used */
66 private static final String APPC_REQUEST_PARAMS = "request-parameters";
67 private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
69 private static final ImmutableList<String> recipes = ImmutableList.of("Restart", "Rebuild", "Migrate",
71 private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
72 .put("Restart", ImmutableList.of("VM")).put("Rebuild", ImmutableList.of("VM"))
73 .put("Migrate", ImmutableList.of("VM")).put("ConfigModify", ImmutableList.of("VNF")).build();
74 private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>()
75 .put("Restart", ImmutableList.of(APPC_VM_ID))
76 .put("ConfigModify", ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
79 public String actor() {
84 public List<String> recipes() {
85 return ImmutableList.copyOf(recipes);
89 public List<String> recipeTargets(String recipe) {
90 return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
94 public List<String> recipePayloads(String recipe) {
95 return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
99 * This method recursively traverses the A&AI named query response
100 * to find the generic-vnf object that contains a model-invariant-id
101 * that matches the resourceId of the policy. Once this match is found
102 * the generic-vnf object's vnf-id is returned.
105 * the list of items related to the vnf returned by A&AI
107 * the id of the target from the sdc catalog
109 * @return the vnf-id of the target vnf to act upon or null if not found
111 private static String parseAAIResponse(List<AAINQInventoryResponseItem> items, String resourceId) {
113 for (AAINQInventoryResponseItem item: items) {
114 if ((item.getGenericVNF() != null)
115 && (item.getGenericVNF().getModelInvariantId() != null)
116 && (resourceId.equals(item.getGenericVNF().getModelInvariantId()))) {
117 vnfId = item.getGenericVNF().getVnfID();
121 if((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
122 vnfId = parseAAIResponse(item.getItems().getInventoryResponseItems(), resourceId);
130 * Constructs an A&AI Named Query using a source vnf-id to determine
131 * the vnf-id of the target entity specified in the policy to act upon.
134 * the id of the target from the sdc catalog
137 * the vnf id of the source entity reporting the alert
139 * @return the target entities vnf id to act upon
140 * @throws AAIException
142 public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AAIException {
144 //TODO: This request id should not be hard coded in future releases
145 UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
147 AAINQRequest aaiRequest = new AAINQRequest();
148 aaiRequest.setQueryParameters(new AAINQQueryParameters());
149 aaiRequest.getQueryParameters().setNamedQuery(new AAINQNamedQuery());
150 aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUUID(requestId);
152 Map<String, Map<String, String>> filter = new HashMap<>();
153 Map<String, String> filterItem = new HashMap<>();
155 filterItem.put("vnf-id", sourceVnfId);
156 filter.put("generic-vnf", filterItem);
158 aaiRequest.setInstanceFilters(new AAINQInstanceFilters());
159 aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
162 * Obtain A&AI credentials from properties.environment file
163 * TODO: What if these are null?
165 String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url");
166 String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username");
167 String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
169 AAINQResponse aaiResponse = new AAIManager(new RESTManager()).postQuery(
171 aaiUsername, aaiPassword,
172 aaiRequest, requestId);
174 if (aaiResponse == null) {
175 throw new AAIException("The named query response was null");
178 String targetVnfId = parseAAIResponse(aaiResponse.getInventoryResponseItems(), resourceId);
179 if (targetVnfId == null) {
180 throw new AAIException("Target vnf-id could not be found");
187 * Constructs an APPC request conforming to the lcm API.
188 * The actual request is constructed and then placed in a
189 * wrapper object used to send through DMAAP.
192 * the event that is reporting the alert for policy
193 * to perform an action
195 * the control loop operation specifying the actor,
196 * operation, target, etc.
198 * the policy the was specified from the yaml generated
199 * by CLAMP or through the Policy GUI/API
200 * @return an APPC request conforming to the lcm API using the DMAAP wrapper
201 * @throws AAIException
203 public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset,
204 ControlLoopOperation operation, Policy policy, String targetVnf) throws AAIException {
206 /* Construct an APPC request using LCM Model */
209 * The actual LCM request is placed in a wrapper used to send
210 * through dmaap. The current version is 2.0 as of R1.
212 LCMRequestWrapper dmaapRequest = new LCMRequestWrapper();
213 dmaapRequest.setVersion("2.0");
214 dmaapRequest.setCorrelationId(onset.getRequestID() + "-" + operation.getSubRequestId());
215 dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
216 dmaapRequest.setType("request");
218 /* This is the actual request that is placed in the dmaap wrapper. */
219 LCMRequest appcRequest = new LCMRequest();
221 /* The common header is a required field for all APPC requests. */
222 LCMCommonHeader requestCommonHeader = new LCMCommonHeader();
223 requestCommonHeader.setOriginatorId(onset.getRequestID().toString());
224 requestCommonHeader.setRequestId(onset.getRequestID());
225 requestCommonHeader.setSubRequestId(operation.getSubRequestId());
227 appcRequest.setCommonHeader(requestCommonHeader);
230 * Action Identifiers are required for APPC LCM requests.
231 * For R1, the recipes supported by Policy only require
234 HashMap<String, String> requestActionIdentifiers = new HashMap<>();
235 requestActionIdentifiers.put("vnf-id", targetVnf);
237 appcRequest.setActionIdentifiers(requestActionIdentifiers);
240 * An action is required for all APPC requests, this will
241 * be the recipe specified in the policy.
243 appcRequest.setAction(policy.getRecipe().substring(0, 1).toUpperCase()
244 + policy.getRecipe().substring(1).toLowerCase());
247 * For R1, the payloads will not be required for the Restart,
248 * Rebuild, or Migrate recipes. APPC will populate the payload
249 * based on A&AI look up of the vnd-id provided in the action
252 if ("Restart".equalsIgnoreCase(policy.getRecipe()) || "Rebuild".equalsIgnoreCase(policy.getRecipe())
253 || "Migrate".equalsIgnoreCase(policy.getRecipe())) {
254 appcRequest.setPayload(null);
258 * Once the LCM request is constructed, add it into the
259 * body of the dmaap wrapper.
261 dmaapRequest.setBody(appcRequest);
263 /* Return the request to be sent through dmaap. */
268 * Parses the operation attempt using the subRequestId
271 * @param subRequestId
272 * the sub id used to send to APPC, Policy sets
273 * this using the operation attempt
275 * @return the current operation attempt
277 public static Integer parseOperationAttempt(String subRequestId) {
278 Integer operationAttempt;
280 operationAttempt = Integer.parseInt(subRequestId);
281 } catch (NumberFormatException e) {
282 logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
285 return operationAttempt;
289 * Processes the APPC LCM response sent from APPC. Determines
290 * if the APPC operation was successful/unsuccessful and maps
291 * this to the corresponding Policy result.
293 * @param dmaapResponse
294 * the dmaap wrapper message that contains the
295 * actual APPC reponse inside the body field
297 * @return an key-value pair that contains the Policy result
298 * and APPC response message
300 public static SimpleEntry<PolicyResult, String> processResponse(LCMResponseWrapper dmaapResponse) {
301 /* The actual APPC response is inside the wrapper's body field. */
302 LCMResponse appcResponse = dmaapResponse.getBody();
304 /* The message returned in the APPC response. */
307 /* The Policy result determined from the APPC Response. */
310 /* If there is no status, Policy cannot determine if the request was successful. */
311 if (appcResponse.getStatus() == null) {
312 message = "Policy was unable to parse APP-C response status field (it was null).";
313 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
316 /* If there is no code, Policy cannot determine if the request was successful. */
317 String responseValue = LCMResponseCode.toResponseValue(appcResponse.getStatus().getCode());
318 if (responseValue == null) {
319 message = "Policy was unable to parse APP-C response status code field.";
320 return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
323 /* Save the APPC response's message for Policy noticiation message. */
324 message = appcResponse.getStatus().getMessage();
326 /* Maps the APPC response result to a Policy result. */
327 switch (responseValue) {
328 case LCMResponseCode.ACCEPTED:
329 /* Nothing to do if code is accept, continue processing */
332 case LCMResponseCode.SUCCESS:
333 result = PolicyResult.SUCCESS;
335 case LCMResponseCode.FAILURE:
336 result = PolicyResult.FAILURE;
338 case LCMResponseCode.REJECT:
339 case LCMResponseCode.ERROR:
341 result = PolicyResult.FAILURE_EXCEPTION;
343 return new AbstractMap.SimpleEntry<>(result, message);