Updated SDC listener and dependent bundles
[appc.git] / appc-dg / appc-dg-shared / appc-dg-aai / src / main / java / org / onap / appc / dg / aai / impl / AAIPluginImpl.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.aai.impl;
26 import org.onap.appc.domainmodel.Vnf;
27 import org.onap.appc.domainmodel.Vnfc;
28 import org.onap.appc.domainmodel.Vserver;
29 import org.onap.appc.exceptions.APPCException;
30 import org.onap.appc.i18n.Msg;
31 import com.att.eelf.i18n.EELFResourceManager;
32
33 import org.onap.appc.dg.aai.AAIPlugin;
34 import org.onap.appc.dg.aai.exception.AAIQueryException;
35 import org.onap.appc.dg.aai.objects.AAIQueryResult;
36 import org.onap.appc.dg.aai.objects.Relationship;
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
42 import org.onap.ccsdk.sli.adaptors.aai.AAIClient;
43 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
44 import org.osgi.framework.BundleContext;
45 import org.osgi.framework.FrameworkUtil;
46 import org.osgi.framework.ServiceReference;
47
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.Map;
51 import java.util.Set;
52 import java.util.stream.Collectors;
53
54
55 public class AAIPluginImpl implements AAIPlugin {
56
57     protected AAIClient aaiClient;
58
59     private final EELFLogger logger = EELFManager.getInstance().getLogger(AAIPluginImpl.class);
60
61     public void initialize(){
62         BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
63         ServiceReference sref = bctx.getServiceReference(AAIService.class);
64         aaiClient = (AAIClient) bctx.getService(sref);
65     }
66
67     @Override
68     public void postGenericVnfData(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
69         String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME);
70         String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME);
71
72         String key = "vnf-id = '" + vnf_id + "'";
73
74         Map<String, String> data = new HashMap<>();
75         for (Map.Entry<String, String> entry : params.entrySet()) {
76             String paramKey = entry.getKey();
77             int pos = paramKey.indexOf(Constants.AAI_INPUT_DATA);
78             if (pos == 0) {
79                 data.put(paramKey.substring(Constants.AAI_INPUT_DATA.length()+1), entry.getValue());
80             }
81         }
82
83         try {
84             SvcLogicResource.QueryStatus response = aaiClient.update("generic-vnf", key, data, prefix, ctx);
85             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
86                 String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id);
87                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
88                 throw new APPCException(msg);
89             }
90             logger.info("AAIResponse: " + response.toString());
91             if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
92                 String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
93                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
94                 throw new APPCException(msg);
95             }
96             String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", "VNF ID " + vnf_id);
97             ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
98
99         } catch (SvcLogicException e) {
100             String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
101             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
102             logger.error(msg);
103             throw new APPCException(e);
104         }
105     }
106
107     @Override
108     public void getGenericVnfData(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
109         String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME);
110         String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME);
111
112         String key = "vnf-id = '" + vnf_id + "'";
113         try {
114             SvcLogicResource.QueryStatus response = aaiClient.query("generic-vnf", false, null, key, prefix, null, ctx);
115             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
116                 String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id);
117 //                String errorMessage = String.format("VNF not found for vnf_id = %s", vnf_id);
118                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
119                 throw new APPCException(msg);
120             } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
121                 String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
122                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
123                 throw new APPCException(msg);
124             }
125             String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME);
126             if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = "";
127             String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME);
128             if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = "";
129
130             ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(!aaiEntitlementPoolUuid.isEmpty()));
131             ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty()));
132             String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData","VNF ID " + vnf_id);
133             ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
134
135             logger.info("AAIResponse: " + response.toString());
136         } catch (SvcLogicException e) {
137             String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
138             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
139             logger.error(msg);
140             throw new APPCException(e);
141         }
142     }
143
144     @Override
145     public void getVnfHierarchy(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
146
147         Set<Vnfc> vnfcSet = new HashSet<>();
148         String vnfType,vnfVersion;
149         String vnfId = params.get("resourceKey");
150         AAIQueryResult vnfQueryResult;
151         int vmCount =0;
152         try {
153             vnfQueryResult = readVnf(vnfId);
154
155             vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type");
156             vnfVersion = vnfQueryResult.getAdditionProperties().get(Constants.AAI_VNF_MODEL_VERSION_ID);
157
158             Vnf vnf = createVnf(vnfType, vnfVersion, vnfId);
159
160             for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){
161                 if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){
162                     vmCount++;
163                     String tenantId = vnfRelationship.getRelationShipDataMap().get("tenant.tenant-id");
164                     String vmId = vnfRelationship.getRelationShipDataMap().get("vserver.vserver-id");
165                     String vmRelatedLink = vnfRelationship.getRelatedLink();
166                     String vmName = vnfRelationship.getRelatedProperties().get("vserver.vserver-name");
167                     String cloudOwner = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-owner");
168                     String cloudRegionId = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-region-id");
169
170                     AAIQueryResult vmQueryResult = readVM(vmId,tenantId,cloudOwner,cloudRegionId);
171                     String vmURL = vmQueryResult.getAdditionProperties().get("vserver-selflink");
172
173                     Vserver vm = createVserver(tenantId, vmId, vmRelatedLink, vmName, vmURL);
174                     vnf.addVserver(vm);
175                     for(Relationship vmRelation:vmQueryResult.getRelationshipList()){
176
177                         if("vnfc".equalsIgnoreCase(vmRelation.getRelatedTo())){
178                             String vnfcName = vmRelation.getRelationShipDataMap().get("vnfc.vnfc-name");
179                             AAIQueryResult vnfcQueryResult = readVnfc(vnfcName);
180                             String vnfcType = vnfcQueryResult.getAdditionProperties().get("vnfc-type");
181
182                             Vnfc newVnfc = createVnfc(vnfcName, vnfcType);
183                             if(vnfcSet.contains(newVnfc)){
184                                 Vnfc vnfcFromSet = vnfcSet.stream().filter(vnfc -> vnfc.equals(newVnfc)).collect(Collectors.toList()).get(0);
185                                 vnfcFromSet.addVserver(vm);
186                                 vm.setVnfc(vnfcFromSet);
187                             }
188                             else{
189                                 vm.setVnfc(newVnfc);
190                                 newVnfc.addVserver(vm);
191                                 vnfcSet.add(newVnfc);
192                             }
193                         }
194                     }
195                 }
196             }
197             ctx.setAttribute("VNF.VMCount",String.valueOf(vmCount));
198             populateContext(vnf,ctx);
199         } catch (AAIQueryException e) {
200             ctx.setAttribute("getVnfHierarchy_result", "FAILURE");
201             String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId);
202             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
203             logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx
204                     .getAttribute("getResource_result"));
205             logger.warn("Incorrect or Incomplete VNF Hierarchy");
206             throw new APPCException("Error Retrieving VNF hierarchy");
207         }
208         ctx.setAttribute("getVnfHierarchy_result", "SUCCESS");
209         String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVNFHierarchy","VNF ID " + vnfId);
210         ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
211
212     }
213
214     private Vnf createVnf(String vnfType, String vnfVersion, String vnfId) {
215         Vnf vnf = new Vnf();
216         vnf.setVnfId(vnfId);
217         vnf.setVnfType(vnfType);
218         vnf.setVnfVersion(vnfVersion);
219         return vnf;
220     }
221
222     private Vnfc createVnfc(String vnfcName, String vnfcType) {
223         Vnfc vnfc = new Vnfc();
224         vnfc.setVnfcName(vnfcName);
225         vnfc.setVnfcType(vnfcType);
226         return vnfc;
227     }
228
229     private Vserver createVserver(String tenantId, String vmId, String vmRelatedLink, String vmName, String vmURL) {
230         Vserver vserver = new Vserver();
231         vserver.setTenantId(tenantId);
232         vserver.setId(vmId);
233         vserver.setRelatedLink(vmRelatedLink);
234         vserver.setName(vmName);
235         vserver.setUrl(vmURL);
236         return vserver;
237     }
238
239     private void populateContext(Vnf vnf ,SvcLogicContext ctx) {
240         ctx.setAttribute("vnf.type",vnf.getVnfType());
241         ctx.setAttribute("vnf.version",vnf.getVnfVersion());
242         ctx.setAttribute("vnf.vnfcCount",String.valueOf(vnf.getVnfcs().size()));
243         int vnfcCount =0;
244         for(Vnfc vnfc:vnf.getVnfcs()){
245             ctx.setAttribute("vnf.vnfc["+vnfcCount+"].name",vnfc.getVnfcName());
246             ctx.setAttribute("vnf.vnfc["+vnfcCount+"].type",vnfc.getVnfcType());
247             ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm_count",String.valueOf(vnfc.getVserverList().size()));
248             int vmCount =0;
249             for(Vserver vm:vnfc.getVserverList()){
250                 ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm["+ vmCount++ +"].url",vm.getUrl());
251             }
252             vnfcCount++;
253         }
254     }
255
256     private AAIQueryResult readVnfc(String vnfcName) throws AAIQueryException {
257         String query = "vnfc.vnfc-name = '" + vnfcName + "'";
258         String prefix = "VNFC";
259         String resourceType = "vnfc";
260         SvcLogicContext vnfContext = readResource(query,prefix,resourceType);
261         String[] additionalProperties = new String[]{"vnfc-type","vnfc-name",
262                 "vnfc-function-code","in-maint","prov-status",
263                 "is-closed-loop-disabled","orchestration-status","resource-version"};
264         return readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
265     }
266
267     private AAIQueryResult readVM(String vmId,String tenantId,String cloudOwner,String cloudRegionId) throws AAIQueryException {
268         String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId + "' AND cloud-region.cloud-owner = '"
269                 + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'";
270         String prefix = "VM";
271         String resourceType = "vserver";
272         SvcLogicContext vnfContext = readResource(query,prefix,resourceType);
273         String[] additionalProperties = new String[]{"vserver-id","vserver-selflink",
274                                                 "vserver-name","in-maint","prov-status","is-closed-loop-disabled",
275                                                 "vserver-name2","resource-version",};
276
277         return readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
278     }
279
280     private AAIQueryResult readVnf(String vnfId) throws AAIQueryException {
281         String query = "generic-vnf.vnf-id = '" + vnfId + "'";
282         String prefix = "VNF";
283         String resourceType = "generic-vnf";
284         SvcLogicContext vnfContext = readResource(query,prefix,resourceType);
285
286         String[] additionalProperties = new String[]{"vnf-type","vnf-name",
287                 "in-maint","prov-status","heat-stack-id",
288                 "is-closed-loop-disabled","orchestration-status","resource-version",Constants.AAI_VNF_MODEL_VERSION_ID};
289
290         return readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
291     }
292
293     private AAIQueryResult readRelationDataAndProperties(String prefix, SvcLogicContext context,String[] additionalProperties) {
294         AAIQueryResult result = new AAIQueryResult();
295
296         if (context != null && context.getAttribute(prefix + ".relationship-list.relationship_length") != null) {
297             Integer relationsCount = Integer.parseInt(context.getAttribute(
298                 prefix + ".relationship-list.relationship_length"));
299             for (int i = 0; i < relationsCount; i++) {
300                 String rsKey = prefix + ".relationship-list.relationship[" + i + "]";
301                 Relationship relationShip = new Relationship();
302                 relationShip.setRelatedLink(context.getAttribute(rsKey + ".related-link"));
303                 relationShip.setRelatedTo(context.getAttribute(rsKey + ".related-to"));
304                 Integer relationDataCount = Integer.parseInt(context.getAttribute(rsKey + ".relationship-data_length"));
305                 for (int j = 0; j < relationDataCount; j++) {
306                     String rsDataKey = rsKey + ".relationship-data[" + j + "]";
307                     String key = context.getAttribute(rsDataKey + ".relationship-key");
308                     String value = context.getAttribute(rsDataKey + ".relationship-value");
309                     relationShip.getRelationShipDataMap().put(key, value);
310                 }
311                 Integer relatedPropertyCount = 0;
312                 String relatedPropertyCountStr = null;
313                 try {
314                     relatedPropertyCountStr = context.getAttribute(rsKey + ".related-to-property_length");
315                     relatedPropertyCount = Integer.parseInt(relatedPropertyCountStr);
316                 } catch (NumberFormatException e) {
317                     logger.debug("Invalid value in the context for Related Property Count " + relatedPropertyCountStr);
318                 }
319
320                 for (int j = 0; j < relatedPropertyCount; j++) {
321                     String rsPropKey = rsKey + ".related-to-property[" + j + "]";
322                     String key = context.getAttribute(rsPropKey + ".property-key");
323                     String value = context.getAttribute(rsPropKey + ".property-value");
324                     relationShip.getRelatedProperties().put(key, value);
325                 }
326                 result.getRelationshipList().add(relationShip);
327             }
328         } else {
329             logger.error("Relationship-list not present in the SvcLogicContext attributes set."
330                 + (context == null ? "" : "Attribute KeySet = "+ context.getAttributeKeySet()));
331         }
332
333         if (context != null) {
334             for (String key : additionalProperties) {
335                 result.getAdditionProperties().put(key, context.getAttribute(prefix + "." + key));
336             }
337         }
338         return result;
339     }
340
341     private SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException {
342         SvcLogicContext resourceContext = new SvcLogicContext();
343         try {
344             SvcLogicResource.QueryStatus response = aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext);
345             logger.info("AAIResponse: " + response.toString());
346             if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){
347                 throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI");
348             }
349         } catch (SvcLogicException e) {
350             logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, query, "", e.getMessage()));
351             throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI");
352         }
353         return resourceContext;
354     }
355
356     @Override public void getResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
357         String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey =
358                 params.get("resourceKey");
359         if (logger.isDebugEnabled()) {
360             logger.debug("inside getResorce");
361             logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey);
362         }
363         try {
364             SvcLogicResource.QueryStatus response =
365                     aaiClient.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx);
366             logger.info("AAIResponse: " + response.toString());
367             ctx.setAttribute("getResource_result", response.toString());
368         } catch (SvcLogicException e) {
369             logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage()));
370         }
371         if (logger.isDebugEnabled()) {
372             logger.debug("exiting getResource======");
373         }
374     }
375
376     @Override public void postResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
377         String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey =
378                 params.get("resourceKey"), att_name = params.get("attributeName"), att_value =
379                 params.get("attributeValue");
380         if (logger.isDebugEnabled()) {
381             logger.debug("inside postResource");
382             logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey);
383             logger.debug("Updating " + att_name + " to : " + att_value);
384         }
385         Map<String, String> data = new HashMap<>();
386         data.put(att_name, att_value);
387
388         try {
389             SvcLogicResource.QueryStatus response = aaiClient.update(resourceType, resourceKey, data, ctx_prefix, ctx);
390             logger.info("AAIResponse: " + response.toString());
391             ctx.setAttribute("postResource_result", response.toString());
392         } catch (SvcLogicException e) {
393             logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage()));
394         }
395         if (logger.isDebugEnabled()) {
396             logger.debug("exiting postResource======");
397         }
398     }
399
400     @Override public void deleteResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
401         String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey");
402
403         if (logger.isDebugEnabled()) {
404             logger.debug("inside deleteResource");
405             logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey);
406         }
407         try {
408             SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx);
409             logger.info("AAIResponse: " + response.toString());
410             ctx.setAttribute("deleteResource_result", response.toString());
411         } catch (SvcLogicException e) {
412             logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage()));
413         }
414         if (logger.isDebugEnabled()) {
415             logger.debug("exiting deleteResource======");
416         }
417     }
418 }