447a2720d8ff556c42449bc9671aeb419545f4a0
[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 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 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.AppcLcmBody;
43 import org.onap.policy.appclcm.AppcLcmCommonHeader;
44 import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
45 import org.onap.policy.appclcm.AppcLcmInput;
46 import org.onap.policy.appclcm.AppcLcmOutput;
47 import org.onap.policy.appclcm.AppcLcmResponseCode;
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.rest.RestManager;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public class AppcLcmActorServiceProvider implements Actor {
58
59     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
60
61     /* To be used in future releases to restart a single vm */
62     private static final String APPC_VM_ID = "vm-id";
63
64     // Strings for targets
65     private static final String TARGET_VM = "VM";
66     private static final String TARGET_VNF = "VNF";
67
68     // Strings for recipes
69     private static final String RECIPE_RESTART = "Restart";
70     private static final String RECIPE_REBUILD = "Rebuild";
71     private static final String RECIPE_MIGRATE = "Migrate";
72     private static final String RECIPE_MODIFY = "ConfigModify";
73
74     /* To be used in future releases when LCM ConfigModify is used */
75     private static final String APPC_REQUEST_PARAMS = "request-parameters";
76     private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
77
78     private static final ImmutableList<String> recipes =
79             ImmutableList.of(RECIPE_RESTART, RECIPE_REBUILD, RECIPE_MIGRATE, RECIPE_MODIFY);
80     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
81             .put(RECIPE_RESTART, ImmutableList.of(TARGET_VM)).put(RECIPE_REBUILD, ImmutableList.of(TARGET_VM))
82             .put(RECIPE_MIGRATE, ImmutableList.of(TARGET_VM)).put(RECIPE_MODIFY, ImmutableList.of(TARGET_VNF)).build();
83     private static final ImmutableMap<String, List<String>> payloads =
84             new ImmutableMap.Builder<String, List<String>>().put(RECIPE_RESTART, ImmutableList.of(APPC_VM_ID))
85                     .put(RECIPE_MODIFY, ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
86
87     @Override
88     public String actor() {
89         return "APPC";
90     }
91
92     @Override
93     public List<String> recipes() {
94         return ImmutableList.copyOf(recipes);
95     }
96
97     @Override
98     public List<String> recipeTargets(String recipe) {
99         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
100     }
101
102     @Override
103     public List<String> recipePayloads(String recipe) {
104         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
105     }
106
107     /**
108      * This method recursively traverses the A&AI named query response to find the generic-vnf
109      * object that contains a model-invariant-id that matches the resourceId of the policy. Once
110      * this match is found the generic-vnf object's vnf-id is returned.
111      *
112      * @param items the list of items related to the vnf returned by A&AI
113      * @param resourceId the id of the target from the sdc catalog
114      *
115      * @return the vnf-id of the target vnf to act upon or null if not found
116      */
117     private static String parseAaiResponse(List<AaiNqInventoryResponseItem> items, String resourceId) {
118         String vnfId = null;
119         for (AaiNqInventoryResponseItem item : items) {
120             if ((item.getGenericVnf() != null) && (item.getGenericVnf().getModelInvariantId() != null)
121                     && (resourceId.equals(item.getGenericVnf().getModelInvariantId()))) {
122                 vnfId = item.getGenericVnf().getVnfId();
123                 break;
124             } else {
125                 if ((item.getItems() != null) && (item.getItems().getInventoryResponseItems() != null)) {
126                     vnfId = parseAaiResponse(item.getItems().getInventoryResponseItems(), resourceId);
127                 }
128             }
129         }
130         return vnfId;
131     }
132
133     /**
134      * Constructs an A&AI Named Query using a source vnf-id to determine the vnf-id of the target
135      * entity specified in the policy to act upon.
136      *
137      * @param resourceId the id of the target from the sdc catalog
138      *
139      * @param sourceVnfId the vnf id of the source entity reporting the alert
140      *
141      * @return the target entities vnf id to act upon
142      * @throws AaiException it an error occurs
143      */
144     public static String vnfNamedQuery(String resourceId, String sourceVnfId, String aaiUrl,
145             String aaiUser, String aaiPassword) throws AaiException {
146
147         // TODO: This request id should not be hard coded in future releases
148         UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
149
150         AaiNqRequest aaiRequest = new AaiNqRequest();
151         aaiRequest.setQueryParameters(new AaiNqQueryParameters());
152         aaiRequest.getQueryParameters().setNamedQuery(new AaiNqNamedQuery());
153         aaiRequest.getQueryParameters().getNamedQuery().setNamedQueryUuid(requestId);
154
155         Map<String, Map<String, String>> filter = new HashMap<>();
156         Map<String, String> filterItem = new HashMap<>();
157
158         filterItem.put("vnf-id", sourceVnfId);
159         filter.put("generic-vnf", filterItem);
160
161         aaiRequest.setInstanceFilters(new AaiNqInstanceFilters());
162         aaiRequest.getInstanceFilters().getInstanceFilter().add(filter);
163
164         AaiNqResponse aaiResponse = new AaiManager(new RestManager()).postQuery(aaiUrl,
165                 aaiUser, aaiPassword, aaiRequest, requestId);
166
167         if (aaiResponse == null) {
168             throw new AaiException("The named query response was null");
169         }
170
171         String targetVnfId = parseAaiResponse(aaiResponse.getInventoryResponseItems(), resourceId);
172         if (targetVnfId == null) {
173             throw new AaiException("Target vnf-id could not be found");
174         }
175
176         return targetVnfId;
177     }
178
179     /**
180      * Constructs an APPC request conforming to the lcm API. The actual request is constructed and
181      * then placed in a wrapper object used to send through DMAAP.
182      *
183      * @param onset the event that is reporting the alert for policy to perform an action
184      * @param operation the control loop operation specifying the actor, operation, target, etc.
185      * @param policy the policy the was specified from the yaml generated by CLAMP or through the
186      *        Policy GUI/API
187      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
188      */
189     public static AppcLcmDmaapWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
190             Policy policy, String targetVnf) {
191
192         /* Construct an APPC request using LCM Model */
193
194         /*
195          * The actual LCM request is placed in a wrapper used to send through dmaap. The current
196          * version is 2.0 as of R1.
197          */
198         AppcLcmRecipeFormatter lcmRecipeFormatter = new AppcLcmRecipeFormatter(policy.getRecipe());
199
200         AppcLcmDmaapWrapper dmaapRequest = new AppcLcmDmaapWrapper();
201         dmaapRequest.setVersion("2.0");
202         dmaapRequest.setCorrelationId(onset.getRequestId() + "-" + operation.getSubRequestId());
203         dmaapRequest.setRpcName(lcmRecipeFormatter.getUrlRecipe());
204         dmaapRequest.setType("request");
205
206         /* This is the actual request that is placed in the dmaap wrapper. */
207         final AppcLcmInput appcRequest = new AppcLcmInput();
208
209         /* The common header is a required field for all APPC requests. */
210         AppcLcmCommonHeader requestCommonHeader = new AppcLcmCommonHeader();
211         requestCommonHeader.setOriginatorId(onset.getRequestId().toString());
212         requestCommonHeader.setRequestId(onset.getRequestId());
213         requestCommonHeader.setSubRequestId(operation.getSubRequestId());
214
215         appcRequest.setCommonHeader(requestCommonHeader);
216
217         /*
218          * Action Identifiers are required for APPC LCM requests. For R1, the recipes supported by
219          * Policy only require a vnf-id.
220          */
221         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
222         requestActionIdentifiers.put("vnf-id", targetVnf);
223
224         appcRequest.setActionIdentifiers(requestActionIdentifiers);
225
226         /*
227          * An action is required for all APPC requests, this will be the recipe specified in the
228          * policy.
229          */
230         appcRequest.setAction(lcmRecipeFormatter.getBodyRecipe());
231
232         /*
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
235          * identifiers.
236          */
237         if (recipeSupportsPayload(policy.getRecipe()) && payloadSupplied(policy.getPayload())) {
238             appcRequest.setPayload(parsePayload(policy.getPayload()));
239         } else {
240             appcRequest.setPayload(null);
241         }
242
243         /*
244          * The APPC request must be wrapped in an input object.
245          */
246         AppcLcmBody body = new AppcLcmBody();
247         body.setInput(appcRequest);
248
249         /*
250          * Once the LCM request is constructed, add it into the body of the dmaap wrapper.
251          */
252         dmaapRequest.setBody(body);
253
254         /* Return the request to be sent through dmaap. */
255         return dmaapRequest;
256     }
257
258     private static boolean payloadSupplied(Map<String, String> payload) {
259         return payload != null && !payload.isEmpty();
260     }
261
262     private static boolean recipeSupportsPayload(String recipe) {
263         return !RECIPE_RESTART.equalsIgnoreCase(recipe) && !RECIPE_REBUILD.equalsIgnoreCase(recipe)
264                 && !RECIPE_MIGRATE.equalsIgnoreCase(recipe);
265     }
266
267     private static String parsePayload(Map<String, String> payload) {
268         StringBuilder payloadString = new StringBuilder("{");
269         payload
270             .forEach((key, value) -> payloadString.append("\"").append(key).append("\": ").append(value).append(","));
271         return payloadString.substring(0, payloadString.length() - 1) + "}";
272     }
273
274     /**
275      * Parses the operation attempt using the subRequestId of APPC response.
276      *
277      * @param subRequestId the sub id used to send to APPC, Policy sets this using the operation
278      *        attempt
279      *
280      * @return the current operation attempt
281      */
282     public static Integer parseOperationAttempt(String subRequestId) {
283         Integer operationAttempt;
284         try {
285             operationAttempt = Integer.parseInt(subRequestId);
286         } catch (NumberFormatException e) {
287             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
288             return null;
289         }
290         return operationAttempt;
291     }
292
293     /**
294      * Processes the APPC LCM response sent from APPC. Determines if the APPC operation was
295      * successful/unsuccessful and maps this to the corresponding Policy result.
296      *
297      * @param dmaapResponse the dmaap wrapper message that contains the actual APPC reponse inside
298      *        the body field
299      *
300      * @return an key-value pair that contains the Policy result and APPC response message
301      */
302     public static SimpleEntry<PolicyResult, String> processResponse(AppcLcmDmaapWrapper dmaapResponse) {
303         AppcLcmBody appcBody = dmaapResponse.getBody();
304         if (appcBody == null) {
305             throw new NullPointerException("APPC Body is null");
306         }
307
308         /* The actual APPC response is inside the dmaap wrapper's body.input field. */
309         AppcLcmOutput appcResponse = appcBody.getOutput();
310         if (appcResponse == null) {
311             throw new NullPointerException("APPC Response is null");
312         }
313
314         /* The message returned in the APPC response. */
315         String message;
316
317         /* The Policy result determined from the APPC Response. */
318         PolicyResult result;
319
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);
324         }
325
326         /* If there is no code, Policy cannot determine if the request was successful. */
327         String responseValue = AppcLcmResponseCode.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);
331         }
332
333         /* Save the APPC response's message for Policy notification message. */
334         message = appcResponse.getStatus().getMessage();
335
336         /* Maps the APPC response result to a Policy result. */
337         switch (responseValue) {
338             case AppcLcmResponseCode.ACCEPTED:
339                 /* Nothing to do if code is accept, continue processing */
340                 result = null;
341                 break;
342             case AppcLcmResponseCode.SUCCESS:
343                 result = PolicyResult.SUCCESS;
344                 break;
345             case AppcLcmResponseCode.FAILURE:
346                 result = PolicyResult.FAILURE;
347                 break;
348             case AppcLcmResponseCode.REJECT:
349             case AppcLcmResponseCode.ERROR:
350             default:
351                 result = PolicyResult.FAILURE_EXCEPTION;
352         }
353         return new AbstractMap.SimpleEntry<>(result, message);
354     }
355 }