1c7ee90898060df59e3034f24a03de88fdb2d4df
[policy/drools-applications.git] /
1 /*-
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.appclcm;
22
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.collect.ImmutableMap;
25
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;
31 import java.util.Map;
32 import java.util.UUID;
33
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;
57
58 public class AppcLcmActorServiceProvider implements Actor {
59     
60     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
61     
62     /* The source vnf-id provided from the DCAE onset */
63     private static final String DCAE_VNF_ID = "generic-vnf.vnf-id";
64
65     /* To be used in future releases to restart a single vm */
66     private static final String APPC_VM_ID = "vm-id";
67     
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";
71
72     private static final ImmutableList<String> recipes = ImmutableList.of("Restart", "Rebuild", "Migrate",
73             "ConfigModify");
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();
80
81     @Override
82     public String actor() {
83         return "APPC";
84     }
85
86     @Override
87     public List<String> recipes() {
88         return ImmutableList.copyOf(recipes);
89     }
90
91     @Override
92     public List<String> recipeTargets(String recipe) {
93         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
94     }
95
96     @Override
97     public List<String> recipePayloads(String recipe) {
98         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
99     }
100     
101     /**
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.
106      * 
107      * @param items
108      *          the list of items related to the vnf returned by A&AI
109      * @param resourceId
110      *          the id of the target from the sdc catalog
111      *          
112      * @return the vnf-id of the target vnf to act upon or null if not found
113      */
114     private static String parseAAIResponse(List<AAINQInventoryResponseItem> items, String resourceId) {
115         String vnfId = null;
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;
121                 break;
122             } 
123             else {
124                 if((item.items != null) && (item.items.inventoryResponseItems != null)) {
125                     vnfId = parseAAIResponse(item.items.inventoryResponseItems, resourceId);
126                 }
127             }
128         }
129         return vnfId;
130     }
131         
132     /**
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.
135      * 
136      * @param resourceId
137      *            the id of the target from the sdc catalog
138      *            
139      * @param sourceVnfId
140      *            the vnf id of the source entity reporting the alert
141      *            
142      * @return the target entities vnf id to act upon
143      * @throws AAIException 
144      */
145     public static String vnfNamedQuery(String resourceId, String sourceVnfId) 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.queryParameters = new AAINQQueryParameters();
152         aaiRequest.queryParameters.namedQuery = new AAINQNamedQuery();
153         aaiRequest.queryParameters.namedQuery.namedQueryUUID = 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.instanceFilters = new AAINQInstanceFilters();
162         aaiRequest.instanceFilters.instanceFilter.add(filter);
163         
164         /*
165          * Obtain A&AI credentials from properties.environment file
166          * TODO: What if these are null?
167          */
168         String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url");
169         String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username");
170         String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
171         
172         AAINQResponse aaiResponse = AAIManager.postQuery(
173                         aaiUrl,
174                         aaiUsername, aaiPassword, 
175                         aaiRequest, requestId);
176         
177         if (aaiResponse == null) {
178             throw new AAIException("The named query response was null");
179         }
180
181         String targetVnfId = parseAAIResponse(aaiResponse.inventoryResponseItems, resourceId);
182         if (targetVnfId == null) {
183             throw new AAIException("Target vnf-id could not be found"); 
184         }
185         
186         return targetVnfId;
187     }
188     
189     /**
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.
193      * 
194      * @param onset
195      *            the event that is reporting the alert for policy
196      *            to perform an action        
197      * @param operation
198      *            the control loop operation specifying the actor,
199      *            operation, target, etc.  
200      * @param policy
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 
205      */
206     public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset, 
207                 ControlLoopOperation operation, Policy policy, AAIGETVnfResponse vnfResponse) throws AAIException {
208         
209         /* Construct an APPC request using LCM Model */
210         
211         /*
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.
214          */
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");
220         
221         /* This is the actual request that is placed in the dmaap wrapper. */
222         LCMRequest appcRequest = new LCMRequest();
223         
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);
229         
230         appcRequest.setCommonHeader(requestCommonHeader);
231
232         /* 
233          * Action Identifiers are required for APPC LCM requests.
234          * For R1, the recipes supported by Policy only require
235          * a vnf-id.
236          */
237         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
238         String vnfId = onset.AAI.get(DCAE_VNF_ID);
239         if (vnfId == null) {
240             vnfId = vnfResponse.vnfID;
241             if (vnfId == null) {
242                 throw new AAIException("No vnf-id found");
243             }
244         }
245         requestActionIdentifiers.put("vnf-id", vnfId);
246         
247         appcRequest.setActionIdentifiers(requestActionIdentifiers);
248         
249         /* 
250          * An action is required for all APPC requests, this will 
251          * be the recipe specified in the policy.
252          */
253         appcRequest.setAction(policy.getRecipe().substring(0, 1).toUpperCase() 
254                 + policy.getRecipe().substring(1).toLowerCase());
255
256         /*
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
260          * identifiers.
261          */
262         if ("Restart".equalsIgnoreCase(policy.getRecipe()) || "Rebuild".equalsIgnoreCase(policy.getRecipe())
263                 || "Migrate".equalsIgnoreCase(policy.getRecipe())) {
264             appcRequest.setPayload(null);
265         }
266         
267         /* 
268          * Once the LCM request is constructed, add it into the 
269          * body of the dmaap wrapper.
270          */
271         dmaapRequest.setBody(appcRequest);
272         
273         /* Return the request to be sent through dmaap. */
274         return dmaapRequest;
275     }
276     
277     /**
278      * Parses the operation attempt using the subRequestId
279      * of APPC response.
280      * 
281      * @param subRequestId
282      *            the sub id used to send to APPC, Policy sets
283      *            this using the operation attempt
284      *            
285      * @return the current operation attempt
286      */
287     public static Integer parseOperationAttempt(String subRequestId) {
288         Integer operationAttempt;
289         try {
290             operationAttempt = Integer.parseInt(subRequestId);
291         } catch (NumberFormatException e) {
292             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
293             return null;
294         }
295         return operationAttempt;
296     }
297     
298     /**
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.
302      * 
303      * @param dmaapResponse
304      *            the dmaap wrapper message that contains the
305      *            actual APPC reponse inside the body field
306      *                       
307      * @return an key-value pair that contains the Policy result
308      * and APPC response message
309      */
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();
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 = 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);
331         }
332         
333         /* Save the APPC response's message for Policy noticiation message. */
334         message = appcResponse.getStatus().getMessage();
335         
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 */
340                 result = null;
341                 break;
342             case LCMResponseCode.SUCCESS:
343                 result = PolicyResult.SUCCESS;
344                 break;
345             case LCMResponseCode.FAILURE:
346                 result = PolicyResult.FAILURE;
347                 break;
348             case LCMResponseCode.REJECT:
349             case LCMResponseCode.ERROR:
350             default:
351                 result = PolicyResult.FAILURE_EXCEPTION;
352         }
353         return new AbstractMap.SimpleEntry<>(result, message);
354     }
355
356 }