Merge of new rebased code
[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  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.dg.aai.impl;
23 import org.openecomp.appc.domainmodel.Vnf;
24 import org.openecomp.appc.domainmodel.Vnfc;
25 import org.openecomp.appc.domainmodel.Vserver;
26 import org.openecomp.appc.exceptions.APPCException;
27 import org.openecomp.appc.i18n.Msg;
28 import com.att.eelf.i18n.EELFResourceManager;
29
30 import org.openecomp.appc.dg.aai.AAIPlugin;
31 import org.openecomp.appc.dg.aai.exception.AAIQueryException;
32 import org.openecomp.appc.dg.aai.objects.AAIQueryResult;
33 import org.openecomp.appc.dg.aai.objects.Relationship;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36 import org.openecomp.sdnc.sli.SvcLogicContext;
37 import org.openecomp.sdnc.sli.SvcLogicException;
38 import org.openecomp.sdnc.sli.SvcLogicResource;
39 import org.openecomp.sdnc.sli.aai.AAIClient;
40 import org.openecomp.sdnc.sli.aai.AAIService;
41 import org.osgi.framework.BundleContext;
42 import org.osgi.framework.FrameworkUtil;
43 import org.osgi.framework.ServiceReference;
44
45 import java.util.*;
46
47
48 public class AAIPluginImpl implements AAIPlugin {
49     private AAIClient aaiClient;
50     private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIPluginImpl.class);
51
52     public AAIPluginImpl() {
53         BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
54         ServiceReference sref = bctx.getServiceReference(AAIService.class);
55         aaiClient = (AAIClient) bctx.getService(sref);
56     }
57
58     @Override
59     public void postGenericVnfData(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
60         String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME);
61         String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME);
62
63         String key = "vnf-id = '" + vnf_id + "'";
64
65         Map<String, String> data = new HashMap<>();
66         for (Map.Entry<String, String> entry : params.entrySet()) {
67             String paramKey = entry.getKey();
68             int pos = paramKey.indexOf(Constants.AAI_INPUT_DATA);
69             if (pos == 0) {
70                 data.put(paramKey.substring(Constants.AAI_INPUT_DATA.length()+1), entry.getValue());
71             }
72         }
73
74         try {
75             SvcLogicResource.QueryStatus response = aaiClient.update("generic-vnf", key, data, prefix, ctx);
76             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
77                 String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id);
78                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
79                 throw new APPCException(msg);
80             }
81             logger.info("AAIResponse: " + response.toString());
82             if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
83                 String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
84                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
85                 throw new APPCException(msg);
86             }
87             String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", "VNF ID " + vnf_id);
88             ctx.setAttribute(org.openecomp.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
89
90         } catch (SvcLogicException e) {
91             String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
92             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
93             logger.error(msg);
94             throw new APPCException(e);
95         }
96     }
97
98     @Override
99     public void getGenericVnfData(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
100         String vnf_id = ctx.getAttribute(Constants.VNF_ID_PARAM_NAME);
101         String prefix = ctx.getAttribute(Constants.AAI_PREFIX_PARAM_NAME);
102
103         String key = "vnf-id = '" + vnf_id + "'";
104         try {
105             SvcLogicResource.QueryStatus response = aaiClient.query("generic-vnf", false, null, key, prefix, null, ctx);
106             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
107                 String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnf_id);
108 //                String errorMessage = String.format("VNF not found for vnf_id = %s", vnf_id);
109                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
110                 throw new APPCException(msg);
111             } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
112                 String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
113                 ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
114                 throw new APPCException(msg);
115             }
116             String aaiEntitlementPoolUuid = ctx.getAttribute(Constants.AAI_ENTITLMENT_POOL_UUID_NAME);
117             if (null == aaiEntitlementPoolUuid) aaiEntitlementPoolUuid = "";
118             String aaiLicenseKeyGroupUuid = ctx.getAttribute(Constants.AAI_LICENSE_KEY_UUID_NAME);
119             if (null == aaiLicenseKeyGroupUuid) aaiLicenseKeyGroupUuid = "";
120
121             ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE, Boolean.toString(!aaiEntitlementPoolUuid.isEmpty()));
122             ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty()));
123             String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData","VNF ID " + vnf_id);
124             ctx.setAttribute(org.openecomp.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
125
126             logger.info("AAIResponse: " + response.toString());
127         } catch (SvcLogicException e) {
128             String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnf_id);
129             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
130             logger.error(msg);
131             throw new APPCException(e);
132         }
133     }
134
135     @Override
136     public void getVnfHierarchy(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
137
138         Map<Vnfc,Set<Vserver>> vnfcMap = new HashMap<>();
139         String vnfType,vnfVersion = null;
140         String vnfId = params.get("resourceKey");
141         AAIQueryResult vnfQueryResult = null;
142         int vmCount =0;
143         try {
144             vnfQueryResult = readVnf(vnfId);
145
146             vnfType = vnfQueryResult.getAdditionProperties().get("vnf-type");
147             vnfVersion = vnfQueryResult.getAdditionProperties().get("persona-model-version");
148
149             for(Relationship vnfRelationship:vnfQueryResult.getRelationshipList()){
150                 if("vserver".equalsIgnoreCase(vnfRelationship.getRelatedTo())){
151                     vmCount++;
152                     String tenantId = vnfRelationship.getRelationShipDataMap().get("tenant.tenant-id");
153                     String vmId = vnfRelationship.getRelationShipDataMap().get("vserver.vserver-id");
154                     String vmRelatedLink = vnfRelationship.getRelatedLink();
155                     String vmName = vnfRelationship.getRelatedProperties().get("vserver.vserver-name");
156                     String cloudOwner = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-owner");
157                     String cloudRegionId = vnfRelationship.getRelationShipDataMap().get("cloud-region.cloud-region-id");
158
159                     AAIQueryResult vmQueryResult = readVM(vmId,tenantId,cloudOwner,cloudRegionId);
160                     String vmURL = vmQueryResult.getAdditionProperties().get("vserver-selflink");
161
162                     Vserver vm = new Vserver(vmURL,tenantId,vmId,vmRelatedLink,vmName);
163                     for(Relationship vmRelation:vmQueryResult.getRelationshipList()){
164
165                         if("vnfc".equalsIgnoreCase(vmRelation.getRelatedTo())){
166                             String vnfcName = vmRelation.getRelationShipDataMap().get("vnfc.vnfc-name");
167                             AAIQueryResult vnfcQueryResult = readVnfc(vnfcName);
168                             String vnfcType = vnfcQueryResult.getAdditionProperties().get("vnfc-type");
169
170                             Vnfc vnfc = new Vnfc(vnfcType,null,vnfcName);
171                             Set<Vserver> vmSet = vnfcMap.get(vnfc);
172                             if(vmSet == null){
173                                 vmSet = new HashSet<>();
174                                 vnfcMap.put(vnfc,vmSet);
175                             }
176                             vmSet.add(vm);
177                         }
178                     }
179                 }
180             }
181             ctx.setAttribute("VNF.VMCount",String.valueOf(vmCount));
182         } catch (AAIQueryException e) {
183             ctx.setAttribute("getVnfHierarchy_result", "FAILURE");
184             String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId);
185             ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
186             logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx
187                     .getAttribute("getResource_result"));
188             logger.warn("Incorrect or Incomplete VNF Hierarchy");
189             throw new APPCException("Error Retrieving VNF hierarchy");
190         }
191
192         Vnf vnf = new Vnf(vnfId,vnfType,vnfVersion);
193         for(Vnfc vnfc:vnfcMap.keySet()){
194             for(Vserver vm:vnfcMap.get(vnfc)){
195                 vnfc.addVm(vm);
196             }
197             vnf.addVnfc(vnfc);
198         }
199
200         populateContext(vnf,ctx);
201         ctx.setAttribute("getVnfHierarchy_result", "SUCCESS");
202         String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetVNFHierarchy","VNF ID " + vnfId);
203         ctx.setAttribute(org.openecomp.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
204
205     }
206
207     private void populateContext(Vnf vnf ,SvcLogicContext ctx) {
208         ctx.setAttribute("vnf.type",vnf.getVnfType());
209         ctx.setAttribute("vnf.version",vnf.getVnfVersion());
210         ctx.setAttribute("vnf.vnfcCount",String.valueOf(vnf.getVnfcs().size()));
211         int vnfcCount =0;
212         for(Vnfc vnfc:vnf.getVnfcs()){
213             ctx.setAttribute("vnf.vnfc["+vnfcCount+"].name",vnfc.getVnfcName());
214             ctx.setAttribute("vnf.vnfc["+vnfcCount+"].type",vnfc.getVnfcType());
215             ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm_count",String.valueOf(vnfc.getVserverList().size()));
216             int vmCount =0;
217             for(Vserver vm:vnfc.getVserverList()){
218                 ctx.setAttribute("vnf.vnfc["+vnfcCount+"].vm["+ vmCount++ +"].url",vm.getUrl());
219             }
220             vnfcCount++;
221         }
222     }
223
224     private AAIQueryResult readVnfc(String vnfcName) throws AAIQueryException {
225         String query = "vnfc.vnfc-name = '" + vnfcName + "'";
226         String prefix = "VNFC";
227         String resourceType = "vnfc";
228         SvcLogicContext vnfContext = readResource(query,prefix,resourceType);
229         String[] additionalProperties = new String[]{"vnfc-type","vnfc-name",
230                 "vnfc-function-code","in-maint","prov-status",
231                 "is-closed-loop-disabled","orchestration-status","resource-version"};
232         AAIQueryResult result = readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
233         return result;
234     }
235
236     private AAIQueryResult readVM(String vmId,String tenantId,String cloudOwner,String cloudRegionId) throws AAIQueryException {
237         String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId + "' AND cloud-region.cloud-owner = '"
238                 + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'";
239         String prefix = "VM";
240         String resourceType = "vserver";
241         SvcLogicContext vnfContext = readResource(query,prefix,resourceType);
242         String[] additionalProperties = new String[]{"vserver-id","vserver-selflink",
243                                                 "vserver-name","in-maint","prov-status","is-closed-loop-disabled",
244                                                 "vserver-name2","resource-version",};
245         AAIQueryResult result = readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
246
247         return result;
248     }
249
250     private AAIQueryResult readVnf(String vnfId) throws AAIQueryException {
251         String query = "generic-vnf.vnf-id = '" + vnfId + "'";
252         String prefix = "VNF";
253         String resourceType = "generic-vnf";
254         SvcLogicContext vnfContext = readResource(query,prefix,resourceType);
255
256         String[] additionalProperties = new String[]{"vnf-type","vnf-name",
257                 "in-maint","prov-status","heat-stack-id",
258                 "is-closed-loop-disabled","orchestration-status","resource-version","persona-model-version"};
259
260         AAIQueryResult result = readRelationDataAndProperties(prefix, vnfContext,additionalProperties);
261
262         return result;
263     }
264
265     private AAIQueryResult readRelationDataAndProperties(String prefix, SvcLogicContext context,String[] additionalProperties) {
266         AAIQueryResult result = new AAIQueryResult();
267
268         Integer relationsCount = Integer.parseInt(context.getAttribute(prefix + ".relationship-list.relationship_length"));
269         for(int i=0;i<relationsCount;i++){
270             Relationship relationShip = new Relationship();
271             relationShip.setRelatedLink(context.getAttribute(prefix + ".relationship-list.relationship["+i+"].related-link"));
272             relationShip.setRelatedTo(context.getAttribute(prefix + ".relationship-list.relationship["+i+"].related-to"));
273             Integer relationDataCount = Integer.parseInt(context.getAttribute(prefix + ".relationship-list.relationship["+i+"].relationship-data_length"));
274             for(int j=0;j<relationDataCount;j++){
275                 String key = context.getAttribute(prefix+".relationship-list.relationship["+i+"].relationship-data["+j+"].relationship-key");
276                 String value = context.getAttribute(prefix+".relationship-list.relationship["+i+"].relationship-data["+j+"].relationship-value");
277                 relationShip.getRelationShipDataMap().put(key,value);
278             }
279             Integer relatedPropertyCount = 0;
280             String relatedPropertyCountStr = null;
281             try{
282                 relatedPropertyCountStr =context.getAttribute(prefix + ".relationship-list.relationship["+i+"].related-to-property_length");
283                 relatedPropertyCount = Integer.parseInt(relatedPropertyCountStr);
284             }
285             catch (NumberFormatException e){
286                 logger.debug("Invalid value in the context for Related Property Count " + relatedPropertyCountStr);
287             }
288
289             for(int j=0;j<relatedPropertyCount;j++){
290                 String key = context.getAttribute(prefix+".relationship-list.relationship["+i+"].related-to-property["+j+"].property-key");
291                 String value = context.getAttribute(prefix+".relationship-list.relationship["+i+"].related-to-property["+j+"].property-value");
292                 relationShip.getRelatedProperties().put(key,value);
293             }
294             result.getRelationshipList().add(relationShip);
295         }
296
297         for(String key:additionalProperties){
298             result.getAdditionProperties().put(key,context.getAttribute(prefix+"."+key));
299         }
300         return result;
301     }
302
303     private SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException {
304         SvcLogicContext resourceContext = new SvcLogicContext();
305         try {
306             SvcLogicResource.QueryStatus response = aaiClient.query(resourceType,false,null,query,prefix,null,resourceContext);
307             logger.info("AAIResponse: " + response.toString());
308             if(!SvcLogicResource.QueryStatus.SUCCESS.equals(response)){
309                 throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI");
310             }
311         } catch (SvcLogicException e) {
312             logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, query, "", e.getMessage()));
313             throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI");
314         }
315         return resourceContext;
316     }
317
318     @Override public void getResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
319         String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey =
320                 params.get("resourceKey");
321         if (logger.isDebugEnabled()) {
322             logger.debug("inside getResorce");
323             logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey);
324         }
325         try {
326             SvcLogicResource.QueryStatus response =
327                     aaiClient.query(resourceType, false, null, resourceKey, ctx_prefix, null, ctx);
328             logger.info("AAIResponse: " + response.toString());
329             ctx.setAttribute("getResource_result", response.toString());
330         } catch (SvcLogicException e) {
331             logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey, "", e.getMessage()));
332         }
333         if (logger.isDebugEnabled()) {
334             logger.debug("exiting getResource======");
335         }
336     }
337
338     @Override public void postResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
339         String resourceType = params.get("resourceType"), ctx_prefix = params.get("prefix"), resourceKey =
340                 params.get("resourceKey"), att_name = params.get("attributeName"), att_value =
341                 params.get("attributeValue");
342         if (logger.isDebugEnabled()) {
343             logger.debug("inside postResource");
344             logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey);
345             logger.debug("Updating " + att_name + " to : " + att_value);
346         }
347         Map<String, String> data = new HashMap<String, String>();
348         data.put(att_name, att_value);
349
350         try {
351             SvcLogicResource.QueryStatus response = aaiClient.update(resourceType, resourceKey, data, ctx_prefix, ctx);
352             logger.info("AAIResponse: " + response.toString());
353             ctx.setAttribute("postResource_result", response.toString());
354         } catch (SvcLogicException e) {
355             logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, att_value, e.getMessage()));
356         }
357         if (logger.isDebugEnabled()) {
358             logger.debug("exiting postResource======");
359         }
360     }
361
362     @Override public void deleteResource(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
363         String resourceType = params.get("resourceType"), resourceKey = params.get("resourceKey");
364
365         if (logger.isDebugEnabled()) {
366             logger.debug("inside deleteResource");
367             logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey);
368         }
369         try {
370             SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx);
371             logger.info("AAIResponse: " + response.toString());
372             ctx.setAttribute("deleteResource_result", response.toString());
373         } catch (SvcLogicException e) {
374             logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey, e.getMessage()));
375         }
376         if (logger.isDebugEnabled()) {
377             logger.debug("exiting deleteResource======");
378         }
379     }
380 }