faf9df220f11a3c5bd04a4ca8f2d025d8dd30c8e
[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  * 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.openecomp.appc.dg.util.impl;
26
27 import org.openecomp.appc.dg.util.ExecuteNodeAction;
28 import org.openecomp.appc.exceptions.APPCException;
29 import org.openecomp.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             e.printStackTrace();
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 ctx_prefix = params.get("prefix");
170         String resourceKey = params.get("resourceKey");
171        // String retrivalVnfKey = "vnf-id = '" + resourceKey + "' AND relationship-key = 'vserver.vserver-id'";
172         String retrivalVnfKey = "generic-vnf.vnf-id = '" + resourceKey + "'";
173         Map<String, String> paramsVnf = new HashMap<String, String>();
174         paramsVnf.put("resourceType", "generic-vnf");
175         paramsVnf.put("prefix", "vnfRetrived");
176         paramsVnf.put("resourceKey", retrivalVnfKey);
177         logger.debug("Retrieving VNF details from A&AI");
178         //Retrive all the relations of VNF
179         SvcLogicContext vnfCtx = new SvcLogicContext();
180         getResource(paramsVnf, vnfCtx);
181         if (vnfCtx.getAttribute("getResource_result").equals("SUCCESS")) {
182             if (vnfCtx.getAttribute("vnfRetrived.heat-stack-id") != null) {
183                 ctx.setAttribute("VNF.heat-stack-id", vnfCtx.getAttribute("vnfRetrived.heat-stack-id"));
184             }
185             ctx.setAttribute("vnf.type",vnfCtx.getAttribute("vnfRetrived.vnf-type"));
186             Map<String, String> vnfHierarchyMap = new ConcurrentHashMap<String, String>();
187
188             Map<String, Set<String>> vnfcHierarchyMap = new HashMap<String, Set<String>>();
189             int vmCount = 0;
190             int vnfcCount = 0;
191             Set<String> vmSet = null;
192             String vmURL = "";
193             logger.debug("Parsing Vserver details from VNF relations");
194             for (String ctxKeySet : vnfCtx
195                     .getAttributeKeySet()) {     //loop through relationship-list data, to get vserver relations
196                 if (ctxKeySet.startsWith("vnfRetrived.") && vnfCtx.getAttribute(ctxKeySet).equalsIgnoreCase("vserver")) {
197                     String vmKey = ctxKeySet.substring(0, ctxKeySet.length() - "related-to".length());
198                     String vserverID = null;
199                     String tenantID = null;
200                     String cloudOwner = null;
201                     String cloudRegionId = null;
202                     int relationshipLength = 0;
203                     if (vnfCtx.getAttributeKeySet().contains(vmKey + "relationship-data_length")) {
204                         relationshipLength = Integer.parseInt(vnfCtx.getAttribute(vmKey + "relationship-data_length"));
205                     }
206
207                     for (int j = 0; j
208                             < relationshipLength; j++) {      //loop inside relationship data, to get vserver-id and tenant-id
209                         String key = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-key");
210                         String value = vnfCtx.getAttribute(vmKey + "relationship-data[" + j + "].relationship-value");
211                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value);
212                         if ("vserver.vserver-id".equals(key)) {
213                             vserverID = value;
214                         }
215                         if ("tenant.tenant-id".equals(key)) {
216                             tenantID = value;
217                         }
218                         if ("cloud-region.cloud-owner".equals(key)) {
219                             cloudOwner = value;
220                         }
221                         if ("cloud-region.cloud-region-id".equals(key)) {
222                             cloudRegionId = value;
223                         }
224                     }
225                     int relatedPropertyLength = 0;
226                     if (vnfCtx.getAttributeKeySet().contains(vmKey + "related-to-property_length")) {
227                         relatedPropertyLength =
228                                 Integer.parseInt(vnfCtx.getAttribute(vmKey + "related-to-property_length"));
229                     }
230                     for (int j = 0;
231                          j < relatedPropertyLength; j++) {   //loop inside related-to-property data, to get vserver-name
232                         String key = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-key");
233                         String value = vnfCtx.getAttribute(vmKey + "related-to-property[" + j + "].property-value");
234                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "]." + key, value);
235                     }
236                     //Retrive VM relations to find vnfc's
237                     //VM to VNFC is 1 to 1 relation
238                     String vmRetrivalKey = "vserver.vserver-id = '" + vserverID + "' AND tenant.tenant_id = '" + tenantID + "'" + "' AND cloud-region.cloud-owner = '" + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'";   
239                     Map<String, String> paramsVm = new HashMap<String, String>();
240                     paramsVm.put("resourceType", "vserver");
241                     paramsVm.put("prefix", "vmRetrived");
242                     paramsVm.put("resourceKey", vmRetrivalKey);
243                     SvcLogicContext vmCtx = new SvcLogicContext();
244
245                     logger.debug("Retrieving VM details from A&AI");
246                     getResource(paramsVm, vmCtx);
247                     if (vmCtx.getAttribute("getResource_result").equals("SUCCESS")) {
248                         if (logger.isDebugEnabled()) {
249                             logger.debug("Parsing VNFC details from VM relations");
250                         }
251                         vmURL = vmCtx.getAttribute("vmRetrived.vserver-selflink");
252                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "].URL",vmURL);
253                         for (String ctxVnfcKeySet : vmCtx
254                                 .getAttributeKeySet()) {    //loop through relationship-list data, to get vnfc relations
255                             if (ctxVnfcKeySet.startsWith("vmRetrived.") && vmCtx.getAttribute(ctxVnfcKeySet)
256                                     .equalsIgnoreCase("vnfc")) {
257                                 String vnfcKey = ctxVnfcKeySet.substring(0,
258                                         ctxVnfcKeySet.length() - "related-to".length());
259                                 relationshipLength = 0;
260                                 if (vmCtx.getAttributeKeySet().contains(vnfcKey + "relationship-data_length")) {
261                                     relationshipLength = Integer.parseInt(
262                                             vmCtx.getAttribute(vnfcKey + "relationship-data_length"));
263                                 }
264                                 for (int j = 0; j
265                                         < relationshipLength; j++) {          //loop through relationship data, to get vnfc name
266                                     String key = vmCtx.getAttribute(
267                                             vnfcKey + "relationship-data[" + j + "].relationship-key");
268                                     String value = vmCtx.getAttribute(
269                                             vnfcKey + "relationship-data[" + j + "].relationship-value");
270                                     if (key.equalsIgnoreCase("vnfc.vnfc-name")) {
271                                         vnfHierarchyMap.put("VNF.VM[" + vmCount + "].VNFC", value);
272                                         vmSet = vnfcHierarchyMap.get(value);
273                                         if(vmSet == null){
274                                             vmSet = new HashSet<>();
275                                         }
276                                         vmSet.add(vmURL);
277                                         vnfcHierarchyMap.put(value,vmSet);
278                                         break; //VM to VNFC is 1 to 1 relation, once we got the VNFC name we can break the loop
279                                     }
280                                 }
281                             }
282                         }
283                     } else {
284                         ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy");
285                         vnfHierarchyMap.put("getVnfHierarchy_result", "FAILURE");
286                         logger.error("Failed in getVnfHierarchy, Error retrieving Vserver details. Error message: "
287                                 + vmCtx.getAttribute("getResource_result"));
288                         logger.warn("Incorrect or Incomplete VNF Hierarchy");
289                         throw new APPCException("Error Retrieving VNFC hierarchy");
290                     }
291                     vmCount++;
292                 }
293             }
294             vnfHierarchyMap.put("VNF.VMCount", vmCount + "");
295             if (vmCount == 0) {
296                 ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "VM count is 0");
297             }
298             //code changes for getting vnfcs hirearchy
299             populateVnfcsDetailsinContext(vnfcHierarchyMap,ctx);
300             //vnf,vnfcCount
301             ctx.setAttribute("VNF.VNFCCount",
302                     Integer.toString(vnfcHierarchyMap.size()));
303             //code changes for getting vnfcs hirearchy
304             ctx.setAttribute("getVnfHierarchy_result", "SUCCESS");
305             //Finally set all attributes to ctx
306             for (String attribute : vnfHierarchyMap.keySet()) {
307                 ctx.setAttribute(attribute, vnfHierarchyMap.get(attribute));
308             }
309         } else {
310             ctx.setAttribute("getVnfHierarchy_result", "FAILURE");
311             ctx.setAttribute(DG_OUTPUT_STATUS_MESSAGE, "Error Retrieving VNFC hierarchy");
312             logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx
313                     .getAttribute("getResource_result"));
314             logger.warn("Incorrect or Incomplete VNF Hierarchy");
315             throw new APPCException("Error Retrieving VNFC hierarchy");
316         }
317         if (logger.isDebugEnabled()) {
318             logger.debug("exiting getVnfHierarchy======");
319         }
320     }
321
322     private void populateVnfcsDetailsinContext(Map<String, Set<String>> vnfcHierarchyMap, SvcLogicContext ctx) throws APPCException {
323 //        int vnfcCount = vnfcHierarchyMap.size();
324         SvcLogicContext vnfcCtx = new SvcLogicContext();
325         int vnfcCounter = 0;
326         for (String vnfcName : vnfcHierarchyMap.keySet()) {
327             String vnfcRetrivalKey = "vnfc-name = '" + vnfcName + "'";
328             Map<String, String> paramsVnfc = new HashMap<String, String>();
329             paramsVnfc.put("resourceType", "vnfc");
330             paramsVnfc.put("prefix", "vnfcRetrived");
331             paramsVnfc.put("resourceKey", vnfcRetrivalKey);
332
333             logger.debug("Retrieving VM details from A&AI");
334             getResource(paramsVnfc, vnfcCtx);
335             if (vnfcCtx.getAttribute("getResource_result").equals("SUCCESS")) {
336                 if (logger.isDebugEnabled()) {
337                     logger.debug("Parsing VNFC details from VM relations");
338                 }
339                 //putting required values in the map
340                 //vnf.vnfc[vnfcIndex].type
341                 ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].TYPE",
342                         vnfcCtx.getAttribute("vnfcRetrived.vnfc-type"));
343
344                 // vnf.vnfc[vnfcIndex].name
345                 ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].NAME",
346                         vnfcCtx.getAttribute("vnfcRetrived.vnfc-name"));
347
348                 //vnf.vnfc[vnfcIndex].vmCount
349                 Set<String> vmSet = vnfcHierarchyMap.get(vnfcName);
350                 String vmCountinVnfcs = Integer.toString(vmSet.size());
351                 ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM_COUNT",
352                         vmCountinVnfcs);
353                 int vmCount =0;
354                 for(String vmURL:vmSet){
355                     ctx.setAttribute("VNF.VNFC[" + vnfcCounter + "].VM[" + vmCount++ + "].URL",vmURL);
356                 }
357
358             }
359             vnfcCounter++;
360         }
361     }
362 }