Merge "Add debugging of REST call"
[policy/drools-applications.git] / controlloop / common / actors / actor.appclcm / src / main / java / org / onap / policy / controlloop / actor / appclcm / AppcLcmActorServiceProvider.java
1 /*-
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.appclcm;
23
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.collect.ImmutableMap;
26
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;
32 import java.util.Map;
33 import java.util.UUID;
34
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;
58
59 public class AppcLcmActorServiceProvider implements Actor {
60
61     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
62
63     /* To be used in future releases to restart a single vm */
64     private static final String APPC_VM_ID = "vm-id";
65
66     // Strings for targets
67     private static final String TARGET_VM = "VM";
68     private static final String TARGET_VNF = "VNF";
69
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";
75
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";
79
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();
88
89     @Override
90     public String actor() {
91         return "APPC";
92     }
93
94     @Override
95     public List<String> recipes() {
96         return ImmutableList.copyOf(recipes);
97     }
98
99     @Override
100     public List<String> recipeTargets(String recipe) {
101         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
102     }
103
104     @Override
105     public List<String> recipePayloads(String recipe) {
106         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
107     }
108
109     /**
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.
113      * 
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
116      * 
117      * @return the vnf-id of the target vnf to act upon or null if not found
118      */
119     private static String parseAaiResponse(List<AaiNqInventoryResponseItem> items, String resourceId) {
120         String vnfId = null;
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();
125                 break;
126             } else {
127                 if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
128                     vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
129                 }
130             }
131         }
132         return vnfId;
133     }
134
135     /**
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.
138      * 
139      * @param resourceId the id of the target from the sdc catalog
140      * 
141      * @param sourceVnfId the vnf id of the source entity reporting the alert
142      * 
143      * @return the target entities vnf id to act upon
144      * @throws AaiException it an error occurs
145      */
146     public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AaiException {
147
148         // TODO: This request id should not be hard coded in future releases
149         UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
150
151         AaiNqRequest aaiRequest = new AaiNqRequest();
152         aaiRequest.setQueryParameters(new AaiNqQueryParameters());
153         aaiRequest.getQueryParameters().setNamedQuery(new AaiNqNamedQuery());
154         aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUuid(requestId);
155
156         Map<String, Map<String, String>> filter = new HashMap<>();
157         Map<String, String> filterItem = new HashMap<>();
158
159         filterItem.put("vnf-id", sourceVnfId);
160         filter.put("generic-vnf", filterItem);
161
162         aaiRequest.setInstanceFilters(new AaiNqInstanceFilters());
163         aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
164
165         AaiNqResponse aaiResponse = new AaiManager(new RestManager()).postQuery(getPeManagerEnvProperty("aai.url"),
166                 getPeManagerEnvProperty("aai.username"), getPeManagerEnvProperty("aai.password"), aaiRequest,
167                 requestId);
168
169         if (aaiResponse == null) {
170             throw new AaiException("The named query response was null");
171         }
172
173         String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
174         if (targetVnfId == null) {
175             throw new AaiException("Target vnf-id could not be found");
176         }
177
178         return targetVnfId;
179     }
180
181     /**
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.
184      * 
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
188      *        Policy GUI/API
189      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
190      */
191     public static LcmRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
192             Policy policy, String targetVnf) {
193
194         /* Construct an APPC request using LCM Model */
195
196         /*
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.
199          */
200         AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
201
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");
207
208         /* This is the actual request that is placed in the dmaap wrapper. */
209         final LcmRequest appcRequest = new LcmRequest();
210
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());
216
217         appcRequest.setCommonHeader(requestCommonHeader);
218
219         /*
220          * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
221          * Policy only require a vnf-id.
222          */
223         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
224         requestActionIdentifiers.put("vnf-id", targetVnf);
225
226         appcRequest.setActionIdentifiers(requestActionIdentifiers);
227
228         /*
229          * An action is required for all APPC requests, this will be the recipe specified in the
230          * policy.
231          */
232         appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
233
234         /*
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
237          * identifiers.
238          */
239         if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
240             appcRequest.setPayload(parsePayload(policy.getPayload()));
241         } else {
242             appcRequest.setPayload(null);
243         }
244
245         /*
246          * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
247          */
248         dmaapRequest.setBody(appcRequest);
249
250         /* Return the request to be sent through dmaap. */
251         return dmaapRequest;
252     }
253
254     private static boolean payloadSupplied(Map<String, String> payload) {
255         return payload != null && !payload.isEmpty();
256     }
257
258     private static boolean recipeSupportsPayload(String recipe) {
259         return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
260                 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
261     }
262
263     private static String parsePayload(Map<String, String> payload) {
264         StringBuilder payloadString = new StringBuilder("{");
265         payload
266             .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
267         return payloadString.substring(0, payloadString.length() - 1) + "}";
268     }
269
270     /**
271      * Parses the operation attempt using the subRequestId of APPC response.
272      * 
273      * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
274      *        attempt
275      * 
276      * @return the current operation attempt
277      */
278     public static Integer parseOperationAttempt(String subRequestId) {
279         Integer operationAttempt;
280         try {
281             operationAttempt = Integer.parseInt(subRequestId);
282         } catch (NumberFormatException e) {
283             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
284             return null;
285         }
286         return operationAttempt;
287     }
288
289     /**
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.
292      * 
293      * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
294      *        the body field
295      * 
296      * @return an key-value pair that contains the Policy result and APPC response message
297      */
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();
301
302         /* The message returned in the APPC response. */
303         String message;
304
305         /* The Policy result determined from the APPC Response. */
306         PolicyResult result;
307
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);
312         }
313
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);
319         }
320
321         /* Save the APPC response's message for Policy notification message. */
322         message = appcResponse.getStatus().getMessage();
323
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 */
328                 result = null;
329                 break;
330             case LcmResponseCode.SUCCESS:
331                 result = PolicyResult.SUCCESS;
332                 break;
333             case LcmResponseCode.FAILURE:
334                 result = PolicyResult.FAILURE;
335                 break;
336             case LcmResponseCode.REJECT:
337             case LcmResponseCode.ERROR:
338             default:
339                 result = PolicyResult.FAILURE_EXCEPTION;
340         }
341         return new AbstractMap.SimpleEntry<>(result, message);
342     }
343
344     /**
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
347      * 
348      * @param enginePropertyName the name of the parameter to retrieve
349      * @return the property value
350      */
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");
356         }
357         return enginePropertyValue;
358     }
359 }