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