c52a7f08e6a9fa9772032887f3f2a0f5134153fc
[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.AAINQF199.AAINQF199InventoryResponseItem;
35 import org.onap.policy.aai.AAINQF199.AAINQF199Manager;
36 import org.onap.policy.aai.AAINQF199.AAINQF199Request;
37 import org.onap.policy.aai.AAINQF199.AAINQF199Response;
38 import org.onap.policy.appclcm.LCMCommonHeader;
39 import org.onap.policy.appclcm.LCMRequest;
40 import org.onap.policy.appclcm.LCMRequestWrapper;
41 import org.onap.policy.appclcm.LCMResponse;
42 import org.onap.policy.appclcm.LCMResponseCode;
43 import org.onap.policy.appclcm.LCMResponseWrapper;
44 import org.onap.policy.controlloop.ControlLoopOperation;
45 import org.onap.policy.controlloop.VirtualControlLoopEvent;
46 import org.onap.policy.controlloop.actorServiceProvider.spi.Actor;
47 import org.onap.policy.controlloop.policy.Policy;
48 import org.onap.policy.controlloop.policy.PolicyResult;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class AppcLcmActorServiceProvider implements Actor {
53     
54     private static final Logger logger = LoggerFactory.getLogger(AppcLcmActorServiceProvider.class);
55     
56     /* The source vnf-id provided from the DCAE onset */
57     private static final String DCAE_VNF_ID = "generic-vnf.vnf-id";
58
59     /* To be used in future releases to restart a single vm */
60     private static final String APPC_VM_ID = "vm-id";
61     
62     /* To be used in future releases when LCM ConfigModify is used */
63     private static final String APPC_REQUEST_PARAMS = "request-parameters";
64     private static final String APPC_CONFIG_PARAMS = "configuration-parameters";
65
66     private static final ImmutableList<String> recipes = ImmutableList.of("Restart", "Rebuild", "Migrate",
67             "ConfigModify");
68     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
69             .put("Restart", ImmutableList.of("VM")).put("Rebuild", ImmutableList.of("VM"))
70             .put("Migrate", ImmutableList.of("VM")).put("ConfigModify", ImmutableList.of("VNF")).build();
71     private static final ImmutableMap<String, List<String>> payloads = new ImmutableMap.Builder<String, List<String>>()
72             .put("Restart", ImmutableList.of(APPC_VM_ID))
73             .put("ConfigModify", ImmutableList.of(APPC_REQUEST_PARAMS, APPC_CONFIG_PARAMS)).build();
74
75     @Override
76     public String actor() {
77         return "APPC";
78     }
79
80     @Override
81     public List<String> recipes() {
82         return ImmutableList.copyOf(recipes);
83     }
84
85     @Override
86     public List<String> recipeTargets(String recipe) {
87         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
88     }
89
90     @Override
91     public List<String> recipePayloads(String recipe) {
92         return ImmutableList.copyOf(payloads.getOrDefault(recipe, Collections.emptyList()));
93     }
94         
95     /**
96      * Constructs an A&AI Named Query using a source vnf-id to determine 
97      * the vnf-id of the target entity specified in the policy to act upon.
98      * 
99      * @param resourceId
100      *            the id of the target from the sdc catalog
101      *            
102      * @param sourceVnfId
103      *            the vnf id of the source entity reporting the alert
104      *            
105      * @return the target entities vnf id to act upon
106      */
107     public static String vnfNamedQuery(String resourceId, String sourceVnfId) {
108         String targetVnfId = "";
109         AAINQF199Request aaiRequest = new AAINQF199Request();
110         UUID requestId = UUID.randomUUID();
111         
112         aaiRequest.queryParameters.namedQuery.namedQueryUUID = requestId;
113         
114         Map<String, Map<String, String>> filter = new HashMap<String, Map<String, String>>();
115         
116         Map<String, String> filterItem = new HashMap<String, String>();
117         filterItem.put("vnf-id", sourceVnfId);
118         
119         filter.put("generic-vnf", filterItem);
120         
121         aaiRequest.instanceFilters.instanceFilter.add(filter);
122         
123         //TODO: What is the url to use?
124         AAINQF199Response aaiResponse = AAINQF199Manager.postQuery("http://localhost:6666", "policy", "policy", aaiRequest, requestId);
125         
126         //TODO: What if the resourceId never matches?
127         for (AAINQF199InventoryResponseItem item: aaiResponse.inventoryResponseItems) {
128             if (item.genericVNF.modelInvariantId.equals(resourceId)) {
129                 targetVnfId = item.genericVNF.vnfID;
130             }
131         }
132         
133         return targetVnfId;
134     }
135     
136     /**
137      * Constructs an APPC request conforming to the lcm API.
138      * The actual request is constructed and then placed in a 
139      * wrapper object used to send through DMAAP.
140      * 
141      * @param onset
142      *            the event that is reporting the alert for policy
143      *            to perform an action        
144      * @param operation
145      *            the control loop operation specifying the actor,
146      *            operation, target, etc.  
147      * @param policy
148      *            the policy the was specified from the yaml generated
149      *            by CLAMP or through the Policy GUI/API                        
150      * @return an APPC request conforming to the lcm API using the DMAAP wrapper
151      */
152     public static LCMRequestWrapper constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation,
153             Policy policy) {
154         
155         /* Construct an APPC request using LCM Model */
156         
157         /*
158          * The actual LCM request is placed in a wrapper used to send
159          * through dmaap. The current version is 2.0 as of R1.
160          */
161         LCMRequestWrapper dmaapRequest = new LCMRequestWrapper();
162         dmaapRequest.setVersion("2.0");
163         dmaapRequest.setCorrelationId(onset.requestID + "-" + operation.subRequestId);
164         dmaapRequest.setRpcName(policy.getRecipe().toLowerCase());
165         dmaapRequest.setType("request");
166         
167         /* This is the actual request that is placed in the dmaap wrapper. */
168         LCMRequest appcRequest = new LCMRequest();
169         
170         /* The common header is a required field for all APPC requests. */
171         LCMCommonHeader requestCommonHeader = new LCMCommonHeader();
172         requestCommonHeader.setOriginatorId(onset.requestID.toString());
173         requestCommonHeader.setRequestId(onset.requestID);
174         requestCommonHeader.setSubRequestId(operation.subRequestId);
175         
176         appcRequest.setCommonHeader(requestCommonHeader);
177
178         /* 
179          * Action Identifiers are required for APPC LCM requests.
180          * For R1, the recipes supported by Policy only require
181          * a vnf-id.
182          */
183         HashMap<String, String> requestActionIdentifiers = new HashMap<>();
184         requestActionIdentifiers.put("vnf-id", onset.AAI.get(DCAE_VNF_ID));
185         appcRequest.setActionIdentifiers(requestActionIdentifiers);
186         
187         /* 
188          * An action is required for all APPC requests, this will 
189          * be the recipe specified in the policy.
190          */
191         appcRequest.setAction(policy.getRecipe().toLowerCase());
192
193         /*
194          * For R1, the payloads will not be required for the Restart, 
195          * Rebuild, or Migrate recipes. APPC will populate the payload
196          * based on A&AI look up of the vnd-id provided in the action
197          * identifiers.
198          */
199         if ("Restart".equalsIgnoreCase(policy.getRecipe()) || "Rebuild".equalsIgnoreCase(policy.getRecipe())
200                 || "Migrate".equalsIgnoreCase(policy.getRecipe())) {
201             appcRequest.setPayload(null);
202         }
203         
204         /* 
205          * Once the LCM request is constructed, add it into the 
206          * body of the dmaap wrapper.
207          */
208         dmaapRequest.setBody(appcRequest);
209         
210         /* Return the request to be sent through dmaap. */
211         return dmaapRequest;
212     }
213     
214     /**
215      * Parses the operation attempt using the subRequestId
216      * of APPC response.
217      * 
218      * @param subRequestId
219      *            the sub id used to send to APPC, Policy sets
220      *            this using the operation attempt
221      *            
222      * @return the current operation attempt
223      */
224     public static Integer parseOperationAttempt(String subRequestId) {
225         Integer operationAttempt;
226         try {
227             operationAttempt = Integer.parseInt(subRequestId);
228         } catch (NumberFormatException e) {
229             logger.debug("A NumberFormatException was thrown due to error in parsing the operation attempt");
230             return null;
231         }
232         return operationAttempt;
233     }
234     
235     /**
236      * Processes the APPC LCM response sent from APPC. Determines
237      * if the APPC operation was successful/unsuccessful and maps
238      * this to the corresponding Policy result.
239      * 
240      * @param dmaapResponse
241      *            the dmaap wrapper message that contains the
242      *            actual APPC reponse inside the body field
243      *                       
244      * @return an key-value pair that contains the Policy result
245      * and APPC response message
246      */
247     public static SimpleEntry<PolicyResult, String> processResponse(LCMResponseWrapper dmaapResponse) {
248         /* The actual APPC response is inside the wrapper's body field. */
249         LCMResponse appcResponse = dmaapResponse.getBody();
250         
251         /* The message returned in the APPC response. */
252         String message;
253         
254         /* The Policy result determined from the APPC Response. */
255         PolicyResult result;
256         
257         /* If there is no status, Policy cannot determine if the request was successful. */
258         if (appcResponse.getStatus() == null) {
259             message = "Policy was unable to parse APP-C response status field (it was null).";
260             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
261         }
262         
263         /* If there is no code, Policy cannot determine if the request was successful. */
264         String responseValue = LCMResponseCode.toResponseValue(appcResponse.getStatus().getCode());
265         if (responseValue == null) {
266             message = "Policy was unable to parse APP-C response status code field.";
267             return new AbstractMap.SimpleEntry<>(PolicyResult.FAILURE_EXCEPTION, message);
268         }
269         
270         /* Save the APPC response's message for Policy noticiation message. */
271         message = appcResponse.getStatus().getMessage();
272         
273         /* Maps the APPC response result to a Policy result. */
274         switch (responseValue) {
275             case LCMResponseCode.ACCEPTED:
276                 /* Nothing to do if code is accept, continue processing */
277                 result = null;
278                 break;
279             case LCMResponseCode.SUCCESS:
280                 result = PolicyResult.SUCCESS;
281                 break;
282             case LCMResponseCode.FAILURE:
283                 result = PolicyResult.FAILURE;
284                 break;
285             case LCMResponseCode.REJECT:
286             case LCMResponseCode.ERROR:
287             default:
288                 result = PolicyResult.FAILURE_EXCEPTION;
289         }
290         return new AbstractMap.SimpleEntry<>(result, message);
291     }
292
293 }