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