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