Merge of new rebased code
[appc.git] / appc-dg-util / appc-dg-util-bundle / src / main / java / org / openecomp / appc / dg / util / impl / ExecuteNodeActionImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.dg.util.impl;
23
24 import org.openecomp.appc.dg.util.ExecuteNodeAction;
25 import org.openecomp.appc.exceptions.APPCException;
26 import org.openecomp.appc.i18n.Msg;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.eelf.i18n.EELFResourceManager;
30 import org.openecomp.sdnc.sli.SvcLogicContext;
31 import org.openecomp.sdnc.sli.SvcLogicException;
32 import org.openecomp.sdnc.sli.SvcLogicResource;
33 import org.openecomp.sdnc.sli.aai.AAIClient;
34 import org.openecomp.sdnc.sli.aai.AAIService;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.FrameworkUtil;
37 import org.osgi.framework.ServiceReference;
38
39 import java.util.*;
40 import java.util.concurrent.ConcurrentHashMap;
41
42
43 public class ExecuteNodeActionImpl implements ExecuteNodeAction {
44
45     private AAIService aaiService;
46     protected static AAIClient client;
47     private static final EELFLogger logger = EELFManager.getInstance().getLogger(ExecuteNodeActionImpl.class);
48
49     public static final String DG_OUTPUT_STATUS_MESSAGE = "output.status.message";
50     public ExecuteNodeActionImpl() {
51     }
52
53     /**
54      * initialize the SDNC adapter (AAIService) by building the context.
55      */
56     private void initialize() {
57         getAAIservice();
58     }
59
60     private void getAAIservice() {
61         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
62         // Get AAIadapter reference
63         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
64         if (sref != null) {
65             logger.info("AAIService from bundlecontext");
66             aaiService = (AAIService) bctx.getService(sref);
67
68         } else {
69             logger.info("AAIService error from bundlecontext");
70             logger.error(EELFResourceManager.format(Msg.AAI_CONNECTION_FAILED, "AAIService"));
71         }
72     }
73
74     /**
75      * Method called in TestDG to test timeout scenario
76      *
77      * @param params waitTime time in millisecond DG is going to sleep
78      * @param ctx
79      * @throws APPCException
80      */
81     @Override public void waitMethod(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
82         try {
83             String waitTime = params.get("waitTime");
84
85             logger.info("DG will waits for " + Long.parseLong(waitTime) + "milliseconds");
86             Thread.sleep(Long.parseLong(waitTime));
87             logger.info("DG waits for " + Long.parseLong(waitTime) + " milliseconds completed");
88         } catch (InterruptedException e) {
89             e.printStackTrace();
90         }
91     }
92
93     @Override public void getResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
94         initialize();
95         String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey =
96                 params.get("resourceKey");
97         if (logger.isDebugEnabled()) {
98             logger.debug("inside getResorce");
99             logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey);
100         }
101         client = aaiService;
102         try {
103             SvcLogicResource.QueryStatus response =
104                     client.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx);
105             logger.info("AAIResponse: " + response.toString());
106             ctx.setAttribute("getResource_result", response.toString());
107         } catch (SvcLogicException e) {
108             logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage()));
109         }
110         if (logger.isDebugEnabled()) {
111             logger.debug("exiting getResource======");
112         }
113     }
114
115     @Override public void postResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
116         initialize();
117         String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey =
118                 params.get("resourceKey"), att_name = params.get("attributeName"), att_value =
119                 params.get("attributeValue");
120         if (logger.isDebugEnabled()) {
121             logger.debug("inside postResource");
122             logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey);
123             logger.debug("Updating " + att_name + " to : " + att_value);
124         }
125         Map<String, String> data = new HashMap<String, String>();
126         data.put(att_name, att_value);
127         client = aaiService;
128
129         try {
130             SvcLogicResource.QueryStatus response = client.update(resourceType, resourceKey, data, ctx_prefix, ctx);
131             logger.info("AAIResponse: " + response.toString());
132             ctx.setAttribute("postResource_result", response.toString());
133         } catch (SvcLogicException e) {
134             logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage()));
135         }
136         if (logger.isDebugEnabled()) {
137             logger.debug("exiting postResource======");
138         }
139     }
140
141     @Override public void deleteResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
142         initialize();
143         String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey");
144
145         if (logger.isDebugEnabled()) {
146             logger.debug("inside deleteResource");
147             logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey);
148         }
149         client = aaiService;
150         try {
151             SvcLogicResource.QueryStatus response = client.delete(resourceType, resourceKey, ctx);
152             logger.info("AAIResponse: " + response.toString());
153             ctx.setAttribute("deleteResource_result", response.toString());
154         } catch (SvcLogicException e) {
155             logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage()));
156         }
157         if (logger.isDebugEnabled()) {
158             logger.debug("exiting deleteResource======");
159         }
160     }
161
162     @Override public void getVnfHierarchy(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
163         if (logger.isDebugEnabled()) {
164             logger.debug("Inside getVnfHierarchy======");
165         }
166         //String ctx_prefix = params.get("prefix");
167         String resourceKey = params.get("resourceKey");
168        // String retrivalVnfKey = "vnf-id = '" + resourceKey + "' AND relationship-key = 'vserver.vserver-id'";
169         String retrivalVnfKey = "generic-vnf.vnf-id = '" + resourceKey + "'";
170         Map<String, String> paramsVnf = new HashMap<String, String>();
171         paramsVnf.put("resourceType", "generic-vnf");
172         paramsVnf.put("prefix", "vnfRetrived");
173         paramsVnf.put("resourceKey", retrivalVnfKey);
174         logger.debug("Retrieving VNF details from A&AI");
175         //Retrive all the relations of VNF
176         SvcLogicContext vnfCtx = new SvcLogicContext();
177         getResource(paramsVnf, vnfCtx);
178         if (vnfCtx.getAttribute("getResource_result").equals("SUCCESS")) {
179             if (vnfCtx.getAttribute("vnfRetrived.heat-stack-id") != null) {
180                 ctx.setAttribute("VNF.heat-stack-id", vnfCtx.getAttribute("vnfRetrived.heat-stack-id"));
181             }
182             ctx.setAttribute("vnf.type",vnfCtx.getAttribute("vnfRetrived.vnf-type"));
183             Map<String, String> vnfHierarchyMap = new ConcurrentHashMap<String, String>();
184
185             Map<String, Set<String>> vnfcHierarchyMap = new HashMap<String, Set<String>>();
186             int vmCount = 0;
187             int vnfcCount = 0;
188             Set<String> vmSet = null;
189             String vmURL = "";
190             logger.debug("Parsing Vserver details from VNF relations");
191             for (String ctxKeySet : vnfCtx
192                     .getAttributeKeySet()) {     //loop through relationship-list data, to get vserver relations
193                 if (ctxKeySet.startsWith("vnfRetrived.") && vnfCtx.getAttribute(ctxKeySet).equalsIgnoreCase("vserver")) {
194                     String vmKey = ctxKeySet.substring(0, ctxKeySet.length() - "related-to".length());
195                     String vserverID = null;
196                     String tenantID = null;
197                     String cloudOwner = null;
198                     String cloudRegionId = null;
199                     int relationshipLength = 0;
200                     if (vnfCtx.getAttributeKeySet().contains(vmKey + "relationship-data_length")) {
201                         relationshipLength = Integer.parseInt(vnfCtx.getAttribute(vmKey + "relationship-data_length"));
202                     }
203
204                     for (int j = 0; j
205                             < relationshipLength; j++) {      //loop inside relationship data, to get vserver-id and tenant-id
206                         String key = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-key");
207                         String value = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-value");
208                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value);
209                         if ("vserver.vserver-id".equals(key)) {
210                             vserverID = value;
211                         }
212                         if ("tenant.tenant-id".equals(key)) {
213                             tenantID = value;
214                         }
215                         if ("cloud-region.cloud-owner".equals(key)) {
216                             cloudOwner = value;
217                         }
218                         if ("cloud-region.cloud-region-id".equals(key)) {
219                             cloudRegionId = value;
220                         }
221                     }
222                     int relatedPropertyLength = 0;
223                     if (vnfCtx.getAttributeKeySet().contains(vmKey + "related-to-property_length")) {
224                         relatedPropertyLength =
225                                 Integer.parseInt(vnfCtx.getAttribute(vmKey + "related-to-property_length"));
226                     }
227                     for (int j = 0;
228                          j < relatedPropertyLength; j++) {   //loop inside related-to-property data, to get vserver-name
229                         String key = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-key");
230                         String value = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-value");
231                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value);
232                     }
233                     //Retrive VM relations to find vnfc's
234                     //VM to VNFC is 1 to 1 relation
235                     String vmRetrivalKey = "vserver.vserver-id = '" + vserverID + "' AND tenant.tenant_id = '" + tenantID + "'" + "' AND cloud-region.cloud-owner = '" + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'";   
236                     Map<String, String> paramsVm = new HashMap<String, String>();
237                     paramsVm.put("resourceType", "vserver");
238                     paramsVm.put("prefix", "vmRetrived");
239                     paramsVm.put("resourceKey", vmRetrivalKey);
240                     SvcLogicContext vmCtx = new SvcLogicContext();
241
242                     logger.debug("Retrieving VM details from A&AI");
243                     getResource(paramsVm, vmCtx);
244                     if (vmCtx.getAttribute("getResource_result").equals("SUCCESS")) {
245                         if (logger.isDebugEnabled()) {
246                             logger.debug("Parsing VNFC details from VM relations");
247                         }
248                         vmURL = vmCtx.getAttribute("vmRetrived.vserver-selflink");
249                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "].URL",vmURL);
250                         for (String ctxVnfcKeySet : vmCtx
251                                 .getAttributeKeySet()) {    //loop through relationship-list data, to get vnfc relations
252                             if (ctxVnfcKeySet.startsWith("vmRetrived.") && vmCtx.getAttribute(ctxVnfcKeySet)
253                                     .equalsIgnoreCase("vnfc")) {
254                                 String vnfcKey = ctxVnfcKeySet.substring(0,
255                                         ctxVnfcKeySet.length() - "related-to".length());
256                                 relationshipLength = 0;
257                                 if (vmCtx.getAttributeKeySet().contains(vnfcKey + "relationship-data_length")) {
258                                     relationshipLength = Integer.parseInt(
259                                             vmCtx.getAttribute(vnfcKey + "relationship-data_length"));
260                                 }
261                                 for (int j = 0; j
262                                         < relationshipLength; j++) {          //loop through relationship data, to get vnfc name
263                                     String key = vmCtx.getAttribute(
264                                             vnfcKey + "relationship-data[" + j + "].relationship-key");
265                                     String value = vmCtx.getAttribute(
266                                             vnfcKey + "relationship-data[" + j + "].relationship-value");
267                                     if (key.equalsIgnoreCase("vnfc.vnfc-name")) {
268                                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "].VNFC", value);
269                                         vmSet = vnfcHierarchyMap.get(value);
270                                         if(vmSet == null){
271                                             vmSet = new HashSet<>();
272                                         }
273                                         vmSet.add(vmURL);
274                                         vnfcHierarchyMap.put(value,vmSet);
275                                         break; //VM to VNFC is 1 to 1 relation, once we got the VNFC name we can break the loop
276                                     }
277                                 }
278                             }
279                         }
280                     } else {
281                         ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy");
282                         vnfHierarchyMap.put("getVnfHierarchy_result", "FAILURE");
283                         logger.error("Failed in getVnfHierarchy, Error retrieving Vserver details. Error message: "
284                                 + vmCtx.getAttribute("getResource_result"));
285                         logger.warn("Incorrect or Incomplete VNF Hierarchy");
286                         throw new APPCException("Error Retrieving VNFC hierarchy");
287                     }
288                     vmCount++;
289                 }
290             }
291             vnfHierarchyMap.put("VNF.VMCount", vmCount + "");
292             if (vmCount == 0) {
293                 ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "VM count is 0");
294             }
295             //code changes for getting vnfcs hirearchy
296             populateVnfcsDetailsinContext(vnfcHierarchyMap,ctx);
297             //vnf,vnfcCount
298             ctx.setAttribute("VNF.VNFCCount",
299                     Integer.toString(vnfcHierarchyMap.size()));
300             //code changes for getting vnfcs hirearchy
301             ctx.setAttribute("getVnfHierarchy_result", "SUCCESS");
302             //Finally set all attributes to ctx
303             for (String attribute : vnfHierarchyMap.keySet()) {
304                 ctx.setAttribute(attribute, vnfHierarchyMap.get(attribute));
305             }
306         } else {
307             ctx.setAttribute("getVnfHierarchy_result", "FAILURE");
308             ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy");
309             logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx
310                     .getAttribute("getResource_result"));
311             logger.warn("Incorrect or Incomplete VNF Hierarchy");
312             throw new APPCException("Error Retrieving VNFC hierarchy");
313         }
314         if (logger.isDebugEnabled()) {
315             logger.debug("exiting getVnfHierarchy======");
316         }
317     }
318
319     private void populateVnfcsDetailsinContext(Map<String, Set<String>> vnfcHierarchyMap, SvcLogicContext ctx) throws APPCException {
320 //        int vnfcCount = vnfcHierarchyMap.size();
321         SvcLogicContext vnfcCtx = new SvcLogicContext();
322         int vnfcCounter = 0;
323         for (String vnfcName : vnfcHierarchyMap.keySet()) {
324             String vnfcRetrivalKey = "vnfc-name = '" + vnfcName + "'";
325             Map<String, String> paramsVnfc = new HashMap<String, String>();
326             paramsVnfc.put("resourceType", "vnfc");
327             paramsVnfc.put("prefix", "vnfcRetrived");
328             paramsVnfc.put("resourceKey", vnfcRetrivalKey);
329
330             logger.debug("Retrieving VM details from A&AI");
331             getResource(paramsVnfc, vnfcCtx);
332             if (vnfcCtx.getAttribute("getResource_result").equals("SUCCESS")) {
333                 if (logger.isDebugEnabled()) {
334                     logger.debug("Parsing VNFC details from VM relations");
335                 }
336                 //putting required values in the map
337                 //vnf.vnfc[vnfcIndex].type
338                 ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].TYPE",
339                         vnfcCtx.getAttribute("vnfcRetrived.vnfc-type"));
340
341                 // vnf.vnfc[vnfcIndex].name
342                 ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].NAME",
343                         vnfcCtx.getAttribute("vnfcRetrived.vnfc-name"));
344
345                 //vnf.vnfc[vnfcIndex].vmCount
346                 Set<String> vmSet = vnfcHierarchyMap.get(vnfcName);
347                 String vmCountinVnfcs = Integer.toString(vmSet.size());
348                 ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM_COUNT",
349                         vmCountinVnfcs);
350                 int vmCount =0;
351                 for(String vmURL:vmSet){
352                     ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM[" + vmCount++ + "].URL",vmURL);
353                 }
354
355             }
356             vnfcCounter++;
357         }
358     }
359 }