ed59aafc5bc0e634c635845aaf8ee1e24cae7872
[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.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.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     /* To be used in future releases when LCM ConfigModify is used */
65     private static final String APPC_REQUEST_PARAMS = "request-parameters";
66     private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
67
68     private static final ImmutableList<String> recipes = ImmutableList.of("Restart", "Rebuild", "Migrate",
69             "ConfigModify");
70     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
71             .put("Restart", ImmutableList.of("VM")).put("Rebuild", ImmutableList.of("VM"))
72             .put("Migrate", ImmutableList.of("VM")).put("ConfigModify", ImmutableList.of("VNF")).build();
73     private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>()
74             .put("Restart", ImmutableList.of(APPC_VM_ID))
75             .put("ConfigModify", ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
76
77     @Override
78     public String actor() {
79         return "APPC";
80     }
81
82     @Override
83     public List<String> recipes() {
84         return ImmutableList.copyOf(recipes);
85     }
86
87     @Override
88     public List<String> recipeTargets(String recipe) {
89         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
90     }
91
92     @Override
93     public List<String> recipePayloads(String recipe) {
94         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
95     }
96     
97     /**
98      * This method recursively traverses the A&AI named query response
99      * to find the generic-vnf object that contains a model-invariant-id
100      * that matches the resourceId of the policy. Once this match is found
101      * the generic-vnf object's vnf-id is returned.
102      * 
103      * @param items
104      *          the list of items related to the vnf returned by A&AI
105      * @param resourceId
106      *          the id of the target from the sdc catalog
107      *          
108      * @return the vnf-id of the target vnf to act upon or null if not found
109      */
110     private static String parseAAIResponse(List<AAINQInventoryResponseItem> items, String resourceId) {
111         String vnfId = null;
112         for (AAINQInventoryResponseItem item: items) {
113             if ((item.genericVNF != null)
114                     && (item.genericVNF.modelInvariantId != null) 
115                     && (resourceId.equals(item.genericVNF.modelInvariantId))) {
116                 vnfId = item.genericVNF.vnfID;
117                 break;
118             } 
119             else {
120                 if((item.items != null) && (item.items.inventoryResponseItems != null)) {
121                     vnfId = parseAAIResponse(item.items.inventoryResponseItems, resourceId);
122                 }
123             }
124         }
125         return vnfId;
126     }
127         
128     /**
129      * Constructs an A&AI Named Query using a source vnf-id to determine 
130      * the vnf-id of the target entity specified in the policy to act upon.
131      * 
132      * @param resourceId
133      *            the id of the target from the sdc catalog
134      *            
135      * @param sourceVnfId
136      *            the vnf id of the source entity reporting the alert
137      *            
138      * @return the target entities vnf id to act upon
139      * @throws AAIException 
140      */
141     public static String vnfNamedQuery(String resourceId, String sourceVnfId) throws AAIException {
142         
143         //TODO: This request id should not be hard coded in future releases
144         UUID requestId = UUID.fromString("a93ac487-409c-4e8c-9e5f-334ae8f99087");
145         
146         AAINQRequest aaiRequest = new AAINQRequest();
147         aaiRequest.queryParameters = new AAINQQueryParameters();
148         aaiRequest.queryParameters.namedQuery = new AAINQNamedQuery();
149         aaiRequest.queryParameters.namedQuery.namedQueryUUID = requestId;
150         
151         Map<String, Map<String, String>> filter = new HashMap<>();        
152         Map<String, String> filterItem = new HashMap<>();
153         
154         filterItem.put("vnf-id", sourceVnfId);
155         filter.put("generic-vnf", filterItem);
156         
157         aaiRequest.instanceFilters = new AAINQInstanceFilters();
158         aaiRequest.instanceFilters.instanceFilter.add(filter);
159         
160         /*
161          * Obtain A&AI credentials from properties.environment file
162          * TODO: What if these are null?
163          */
164         String aaiUrl = PolicyEngine.manager.getEnvironmentProperty("aai.url");
165         String aaiUsername = PolicyEngine.manager.getEnvironmentProperty("aai.username");
166         String aaiPassword = PolicyEngine.manager.getEnvironmentProperty("aai.password");
167         
168         AAINQResponse aaiResponse = AAIManager.postQuery(
169                         aaiUrl,
170                         aaiUsername, aaiPassword, 
171                         aaiRequest, requestId);
172         
173         if (aaiResponse == null) {
174             throw new AAIException("The named query response was null");
175         }
176
177         String targetVnfId = parseAAIResponse(aaiResponse.inventoryResponseItems, resourceId);
178         if (targetVnfId == null) {
179             throw new AAIException("Target vnf-id could not be found"); 
180         }
181         
182         return targetVnfId;
183     }
184     
185     /**
186      * Constructs an APPC request conforming to the lcm API.
187      * The actual request is constructed and then placed in a 
188      * wrapper object used to send through DMAAP.
189      * 
190      * @param onset
191      *            the event that is reporting the alert for policy
192      *            to perform an action        
193      * @param operation
194      *            the control loop operation specifying the actor,
195      *            operation, target, etc.  
196      * @param policy
197      *            the policy the was specified from the yaml generated
198      *            by CLAMP or through the Policy GUI/API                        
199      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
200      * @throws AAIException 
201      */
202     public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset, 
203                 ControlLoopOperation operation, Policy policy, String targetVnf) throws AAIException {
204         
205         /* Construct an APPC request using LCM Model */
206         
207         /*
208          * The actual LCM request is placed in a wrapper used to send
209          * through dmaap. The current version is 2.0 as of R1.
210          */
211         LCMRequestWrapper dmaapRequest = new LCMRequestWrapper();
212         dmaapRequest.setVersion("2.0");
213         dmaapRequest.setCorrelationId(onset.requestID + "-" + operation.subRequestId);
214         dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
215         dmaapRequest.setType("request");
216         
217         /* This is the actual request that is placed in the dmaap wrapper. */
218         LCMRequest appcRequest = new LCMRequest();
219         
220         /* The common header is a required field for all APPC requests. */
221         LCMCommonHeader requestCommonHeader = new LCMCommonHeader();
222         requestCommonHeader.setOriginatorId(onset.requestID.toString());
223         requestCommonHeader.setRequestId(onset.requestID);
224         requestCommonHeader.setSubRequestId(operation.subRequestId);
225         
226         appcRequest.setCommonHeader(requestCommonHeader);
227
228         /* 
229          * Action Identifiers are required for APPC LCM requests.
230          * For R1, the recipes supported by Policy only require
231          * a vnf-id.
232          */
233         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
234         requestActionIdentifiers.put("vnf-id", targetVnf);
235         
236         appcRequest.setActionIdentifiers(requestActionIdentifiers);
237         
238         /* 
239          * An action is required for all APPC requests, this will 
240          * be the recipe specified in the policy.
241          */
242         appcRequest.setAction(policy.getRecipe().substring(0, 1).toUpperCase() 
243                 + policy.getRecipe().substring(1).toLowerCase());
244
245         /*
246          * For R1, the payloads will not be required for the Restart, 
247          * Rebuild, or Migrate recipes. APPC will populate the payload
248          * based on A&AI look up of the vnd-id provided in the action
249          * identifiers.
250          */
251         if ("Restart".equalsIgnoreCase(policy.getRecipe()) || "Rebuild".equalsIgnoreCase(policy.getRecipe())
252                 || "Migrate".equalsIgnoreCase(policy.getRecipe())) {
253             appcRequest.setPayload(null);
254         }
255         
256         /* 
257          * Once the LCM request is constructed, add it into the 
258          * body of the dmaap wrapper.
259          */
260         dmaapRequest.setBody(appcRequest);
261         
262         /* Return the request to be sent through dmaap. */
263         return dmaapRequest;
264     }
265     
266     /**
267      * Parses the operation attempt using the subRequestId
268      * of APPC response.
269      * 
270      * @param subRequestId
271      *            the sub id used to send to APPC, Policy sets
272      *            this using the operation attempt
273      *            
274      * @return the current operation attempt
275      */
276     public static Integer parseOperationAttempt(String subRequestId) {
277         Integer operationAttempt;
278         try {
279             operationAttempt = Integer.parseInt(subRequestId);
280         } catch (NumberFormatException e) {
281             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
282             return null;
283         }
284         return operationAttempt;
285     }
286     
287     /**
288      * Processes the APPC LCM response sent from APPC. Determines
289      * if the APPC operation was successful/unsuccessful and maps
290      * this to the corresponding Policy result.
291      * 
292      * @param dmaapResponse
293      *            the dmaap wrapper message that contains the
294      *            actual APPC reponse inside the body field
295      *                       
296      * @return an key-value pair that contains the Policy result
297      * 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 noticiation 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 }