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