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