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