[MSO-8] Update the maven dependency
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / openecomp / mso / bpmn / common / scripts / AaiUtil.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.bpmn.common.scripts
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.runtime.Execution
24 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor;
25 import org.openecomp.mso.rest.APIResponse;
26 import org.openecomp.mso.rest.RESTClient
27 import org.openecomp.mso.rest.RESTConfig
28
29 class AaiUtil {
30         
31         public MsoUtils utils = new MsoUtils()
32         public static final String AAI_NAMESPACE_STRING = 'http://org.openecomp.aai.inventory/'
33         public static final String DEFAULT_VERSION_KEY = 'URN_mso_workflow_global_default_aai_version'
34         
35         private AbstractServiceTaskProcessor taskProcessor
36
37         public AaiUtil(AbstractServiceTaskProcessor taskProcessor) {
38                 this.taskProcessor = taskProcessor
39         }
40         
41         public String getNetworkGenericVnfEndpoint(Execution execution) {
42                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
43                 String endpoint = execution.getVariable("URN_aai_endpoint")
44                 def uri = getNetworkGenericVnfUri(execution)
45                 taskProcessor.logDebug('AaiUtil.getNetworkGenericVnfEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled)
46                 return endpoint + uri
47         }
48
49         public String getNetworkGenericVnfUri(Execution execution) {
50                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
51                 def uri = getUri(execution, 'generic_vnf')
52                 taskProcessor.logDebug('AaiUtil.getNetworkGenericVnfUri() - AAI URI: ' + uri, isDebugLogEnabled)
53                 return uri
54         }
55                 
56         public String getNetworkVpnBindingUri(Execution execution) {
57                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
58                 def uri = getUri(execution, 'vpn_binding')
59                 taskProcessor.logDebug('AaiUtil.getNetworkVpnBindingUri() - AAI URI: ' + uri, isDebugLogEnabled)
60                 return uri
61         }
62
63         public String getNetworkPolicyUri(Execution execution) {
64                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
65                 def uri = getUri(execution, 'network_policy')
66                 taskProcessor.logDebug('AaiUtil.getNetworkPolicyUri() - AAI URI: ' + uri, isDebugLogEnabled)
67                 return uri
68         }
69
70         public String getNetworkTableReferencesUri(Execution execution) {
71                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
72                 def uri = getUri(execution, 'route_table_reference')
73                 taskProcessor.logDebug('AaiUtil.getNetworkTableReferencesUri() - AAI URI: ' + uri, isDebugLogEnabled)
74                 return uri
75         }
76         
77         public String getNetworkVceUri(Execution execution) {
78                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
79                 def uri = getUri(execution, 'vce')
80                 taskProcessor.logDebug('AaiUtil.getNetworkVceUri() - AAI URI: ' + uri, isDebugLogEnabled)
81                 return uri
82         }
83
84         public String getNetworkL3NetworkUri(Execution execution) {
85                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
86                 def uri = getUri(execution, 'l3_network')
87                 taskProcessor.logDebug('AaiUtil.getNetworkL3NetworkUri() - AAI URI: ' + uri, isDebugLogEnabled)
88                 return uri
89         }
90
91         public String getBusinessCustomerUri(Execution execution) {
92                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
93                 def uri = getUri(execution, 'customer')
94                 taskProcessor.logDebug('AaiUtil.getBusinessCustomerUri() - AAI URI: ' + uri, isDebugLogEnabled)
95                 return uri
96         }
97
98         //public String getBusinessCustomerUriv7(Execution execution) {
99         //      def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
100         //      //def uri = getUri(execution, BUSINESS_CUSTOMERV7)
101         //      def uri = getUri(execution, 'Customer')
102         //      taskProcessor.logDebug('AaiUtil.getBusinessCustomerUriv7() - AAI URI: ' + uri, isDebugLogEnabled)
103         //      return uri
104         //}
105
106         public String getCloudInfrastructureCloudRegionEndpoint(Execution execution) {
107                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
108                 String endpoint = execution.getVariable("URN_aai_endpoint")
109                 def uri = getCloudInfrastructureCloudRegionUri(execution)
110                 taskProcessor.logDebug('AaiUtil.getCloudInfrastructureCloudRegionEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled)
111                 return endpoint + uri
112         }
113         
114         public String getCloudInfrastructureCloudRegionUri(Execution execution) {
115                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
116                 def uri = getUri(execution, 'cloud_region')
117                 taskProcessor.logDebug('AaiUtil.getCloudInfrastructureCloudRegionUri() - AAI URI: ' + uri, isDebugLogEnabled)
118                 return uri
119         }
120
121         public String getCloudInfrastructureVolumeGroupUri(Execution execution) {
122                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
123                 def uri = getUri(execution, 'volume_group')
124                 taskProcessor.logDebug('AaiUtil.getCloudInfrastructureVolumeGroupUri() - AAI URI: ' + uri, isDebugLogEnabled)
125                 return uri
126         }
127
128         public String getCloudInfrastructureTenantUri(Execution execution) {
129                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
130                 def uri = getUri(execution, 'tenant')
131                 taskProcessor.logDebug('AaiUtil.getCloudInfrastructureTenantUri() - AAI URI: ' + uri, isDebugLogEnabled)
132                 return uri
133         }
134
135         public String getSearchNodesQueryUri(Execution execution) {
136                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
137                 def uri = getUri(execution, 'nodes_query')
138                 taskProcessor.logDebug('AaiUtil.getSearchNodesQueryUri() - AAI URI: ' + uri, isDebugLogEnabled)
139                 return uri
140         }
141         
142         public String getSearchNodesQueryEndpoint(Execution execution) {
143                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
144                 String endpoint = execution.getVariable("URN_aai_endpoint")
145                 def uri = getSearchNodesQueryUri(execution)
146                 taskProcessor.logDebug('AaiUtil.getSearchNodesQueryEndpoint() - AAI endpoint: ' + endpoint + uri, isDebugLogEnabled)
147                 return endpoint + uri
148         }
149         
150         public String getSearchGenericQueryUri(Execution execution) {
151                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
152                 def uri = getUri(execution, 'generic_query')
153                 taskProcessor.logDebug('AaiUtil.getSearchGenericQueryUri() - AAI URI: ' + uri, isDebugLogEnabled)
154                 return uri
155         }
156
157         public String getVersion(Execution execution, resourceName, processKey) {
158                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
159
160                 resourceName = resourceName.replaceAll('-', '_')
161                 
162                 def versionWithResourceKey = "URN_mso_workflow_default_aai_${resourceName}_version"
163                 def versionWithProcessKey = "URN_mso_workflow_custom_${processKey}_aai_version"
164
165                 def version = execution.getVariable(versionWithProcessKey)
166                 if (version) {
167                         taskProcessor.logDebug("AaiUtil.getVersion() - using flow specific ${versionWithProcessKey}=${version}", isDebugLogEnabled)
168                         return version 
169                 }
170                 
171                 version = execution.getVariable(versionWithResourceKey)
172                 if (version) {
173                         taskProcessor.logDebug("AaiUtil.getVersion() - using resource specific ${versionWithResourceKey}=${version}", isDebugLogEnabled)
174                         return version
175                 }
176                 
177                 version = execution.getVariable(DEFAULT_VERSION_KEY)
178                 if (version) {
179                         taskProcessor.logDebug("AaiUtil.getVersion() - using default version ${DEFAULT_VERSION_KEY}=${version}", isDebugLogEnabled)
180                         return version
181                 }
182                 
183                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, "Internal Error: One of the following should be defined in MSO URN properties file: ${versionWithResourceKey}, ${versionWithProcessKey}, ${DEFAULT_VERSION_KEY}")
184         }
185         
186         public String getUri(Execution execution, resourceName) {
187
188                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
189                 def processKey = taskProcessor.getMainProcessKey(execution)
190                 
191                 resourceName = resourceName.replaceAll('-', '_')
192                 
193                 // Check for flow+resource specific first
194                 def key = "URN_mso_workflow_${processKey}_aai_${resourceName}_uri"
195                 def uri = execution.getVariable(key)
196                 if(uri) {
197                         taskProcessor.logDebug("AaiUtil.getUri() - using flow+resource specific key: ${key}=${uri}", isDebugLogEnabled)
198                         return uri
199                 }
200                 
201                 // Check for versioned key
202                 def version = getVersion(execution, resourceName, processKey)
203                 key = "URN_mso_workflow_default_aai_v${version}_${resourceName}_uri"
204                 uri = execution.getVariable(key)
205
206                 if(uri) {
207                         taskProcessor.logDebug("AaiUtil.getUri() - using versioned URI key: ${key}=${uri}", isDebugLogEnabled)
208                         return uri
209                 }
210
211                 (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 9999, 'Internal Error: AAI URI entry for ' + key + ' not defined in the MSO URN properties file')
212         }
213
214         public String getNamespaceFromUri(String uri) {
215                 String namespace = AAI_NAMESPACE_STRING
216                 if(uri!=null){
217                         return namespace + uri.substring(uri.indexOf("v"),  uri.indexOf("v")+2)
218                 }else{
219                         return namespace
220                 }
221         }
222
223
224         
225         /**
226          * This reusable method can be used for making AAI Get Calls. The url should
227          * be passed as a parameter along with the execution.  The method will
228          * return an APIResponse.
229          *
230          * @param execution
231          * @param url
232          *
233          * @return APIResponse
234          */
235         public APIResponse executeAAIGetCall(Execution execution, String url){
236                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
237                 taskProcessor.logDebug(" ======== STARTED Execute AAI Get Process ======== ", isDebugEnabled)
238                 try{
239                         String uuid = UUID.randomUUID()
240                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
241                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
242                                         
243                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
244
245                         RESTConfig config = new RESTConfig(url);
246                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
247
248                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
249                                 client.addAuthorizationHeader(basicAuthCred)
250                         }
251
252                         APIResponse apiResponse = client.get()
253                         return apiResponse
254
255                 }catch(Exception e){
256                         taskProcessor.logDebug("Exception occured while executing AAI Get Call. Exception is: \n" + e, isDebugEnabled)
257                         return e
258                 }
259                 taskProcessor.logDebug( "======== COMPLETED Execute AAI Get Process ======== ", isDebugEnabled)
260         }
261
262         /**
263          * This reusable method can be used for making AAI httpPut Calls. The url should
264          * be passed as a parameter along with the execution and payload.  The method will
265          * return an APIResponse.
266          *
267          * @param execution
268          * @param url
269          * @param payload
270          *
271          * @return APIResponse
272          */
273         public APIResponse executeAAIPutCall(Execution execution, String url, String payload){
274                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
275                 taskProcessor.logDebug( " ======== Started Execute AAI Put Process ======== ", isDebugEnabled)
276                 try{
277                         String uuid = UUID.randomUUID()
278                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
279                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
280                         
281                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
282
283                         RESTConfig config = new RESTConfig(url);
284                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");
285                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
286                                 client.addAuthorizationHeader(basicAuthCred)
287                         }
288                         APIResponse apiResponse = client.httpPut(payload)
289
290                         return apiResponse
291                 }catch(Exception e){
292                         taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Put Call. Exception is: \n" + e, isDebugEnabled)
293                         return e
294                 }
295                 taskProcessor.logDebug( "======== Completed Execute AAI Put Process ======== ", isDebugEnabled)
296         }
297
298
299         /**
300          * This reusable method can be used for making AAI Delete Calls. The url should
301          * be passed as a parameter along with the execution.  The method will
302          * return an APIResponse.
303          *
304          * @param execution
305          * @param url
306          *
307          * @return APIResponse
308          */
309         public APIResponse executeAAIDeleteCall(Execution execution, String url){
310                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
311                 taskProcessor.logDebug( " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled)
312                 try{
313                         String uuid = UUID.randomUUID()
314                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
315                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
316
317                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
318                         
319                         RESTConfig config = new RESTConfig(url);
320                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
321                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
322                                 client.addAuthorizationHeader(basicAuthCred)
323                         }
324                         APIResponse apiResponse = client.delete()
325
326                         return apiResponse
327
328                 }catch(Exception e){
329                         taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Delete Call. Exception is: \n" + e, isDebugEnabled)
330                         return e
331                 }
332                 taskProcessor.logDebug( "======== Completed Execute AAI Delete Process ======== ", isDebugEnabled)
333         }
334
335         /**
336          * This reusable method can be used for making AAI Delete Calls. The url should
337          * be passed as a parameter along with the execution.  The method will
338          * return an APIResponse.
339          *
340          * @param execution
341          * @param url
342          * @param payload
343          *
344          * @return APIResponse
345          */
346         public APIResponse executeAAIDeleteCall(Execution execution, String url, String payload, String authHeader){
347                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
348                 taskProcessor.logDebug( " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled)
349                 try{
350                         String uuid = UUID.randomUUID()
351                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
352                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
353                         
354                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
355                         RESTConfig config = new RESTConfig(url);
356                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml").addAuthorizationHeader(authHeader);
357                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
358                                 client.addAuthorizationHeader(basicAuthCred)
359                         }
360                         
361                         APIResponse apiResponse = client.httpDelete(payload)
362
363                         return apiResponse
364
365                 }catch(Exception e){
366                         taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Delete Call. Exception is: \n" + e, isDebugEnabled)
367                         return e
368                 }
369                 taskProcessor.logDebug( "======== Completed Execute AAI Delete Process ======== ", isDebugEnabled)
370         }
371         
372         /**
373          * This reusable method can be used for making AAI Post Calls. The url should
374          * be passed as a parameter along with the execution.  The method will
375          * return an APIResponse.
376          *
377          * @param execution
378          * @param url
379          * @param payload
380          *
381          * @return APIResponse
382          */
383         public APIResponse executeAAIPostCall(Execution execution, String url, String payload){
384                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
385                 taskProcessor.logDebug( " ======== Started Execute AAI Post Process ======== ", isDebugEnabled)
386                 try{
387                         String uuid = UUID.randomUUID()
388                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
389                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
390
391                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_aai_auth"),execution.getVariable("URN_mso_msoKey"))
392                         RESTConfig config = new RESTConfig(url);
393                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/xml");
394                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
395                                 client.addAuthorizationHeader(basicAuthCred)
396                         }
397                         APIResponse apiResponse = client.httpPost(payload)
398
399                         return apiResponse
400
401                 }catch(Exception e){
402                         taskProcessor.utils.log("ERROR", "Exception occured while executing AAI Post Call. Exception is: \n" + e, isDebugEnabled)
403                         return e
404                 }
405                 taskProcessor.logDebug( "======== Completed Execute AAI Post Process ======== ", isDebugEnabled)
406         }
407
408         /** Utilitty to get the Cloud Region from AAI
409          * Returns String cloud region id, (ie, cloud-region-id)
410          * @param execution
411          * @param url  - url for AAI get cloud region
412          * @param backend - "PO" - real region, or "SDNC" - v2.5 (fake region).
413          */
414
415         //TODO: We should refactor this method to return WorkflowException instead of Error. Also to throw MSOWorkflowException which the calling flow will then catch.
416
417         public String getAAICloudReqion(Execution execution, String url, String backend, inputCloudRegion){
418                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
419
420                 try {
421                   APIResponse apiResponse = executeAAIGetCall(execution, url)
422                   String returnCode = apiResponse.getStatusCode()
423                   String aaiResponseAsString = apiResponse.getResponseBodyAsString()
424                   taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region Return code: " + returnCode, isDebugEnabled)
425                   execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionReturnCode", returnCode)
426                   //taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region Response: " + aaiResponseAsString, isDebugEnabled)
427                   //execution.setVariable(execution.getVariable("prefix")+"queryCloudRegionResponse", aaiResponseAsString)
428                   String regionId = ""
429                   if (returnCode == "200") {
430                          taskProcessor.utils.log("DEBUG", "Call AAI Cloud Region is Successful.", isDebugEnabled)
431                            try {
432                            String regionVersion = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-version")
433                            taskProcessor.utils.log("DEBUG", "Cloud Region Version from AAI for " + backend + " is: " + regionVersion, isDebugEnabled)
434                            if (backend == "PO") {
435                                   regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
436                            } else { // backend not "PO"
437                                   if (regionVersion == "2.5" ) {
438                                           regionId = "AAIAIC25"
439                                   } else {
440                                           regionId = taskProcessor.utils.getNodeText(aaiResponseAsString, "cloud-region-id")
441                                   }
442                            }
443
444                            taskProcessor.utils.log("DEBUG", "Cloud Region Id from AAI " + backend + " is: " + regionId, isDebugEnabled)
445                            return regionId
446
447                          } catch (Exception e) {
448                                   taskProcessor.utils.log("ERROR", "Exception occured while getting the Cloud Reqion. Exception is: \n" + e, isDebugEnabled)
449                                   return "ERROR"
450                          }
451                   } else { // not 200
452                       if (returnCode == "404") {
453                                  if (backend == "PO") {
454                                           regionId = inputCloudRegion
455                                  } else  {  // backend not "PO"
456                                           regionId = "AAIAIC25"
457                                  }
458                                  taskProcessor.utils.log("DEBUG", "Cloud Region value for code='404' of " + backend + " is: " + regionId, isDebugEnabled)
459                                   return regionId
460                       } else {
461                               taskProcessor.utils.log("ERROR", "Call AAI Cloud Region is NOT Successful.", isDebugEnabled)
462                               return "ERROR"
463                       }
464                   }
465                 }catch(Exception e) {
466                    taskProcessor.utils.log("ERROR", "Exception occured while getting the Cloud Reqion. Exception is: \n" + e, isDebugEnabled)
467                    return "ERROR"
468                 }
469         }
470
471         /* returns xml Node with service-type of searchValue */
472         def searchServiceType(xmlInput, searchValue){
473                 def fxml= new XmlSlurper().parseText(xmlInput)
474                 def ret = fxml.'**'.find {it.'service-type' == searchValue}
475                 return ret
476         }
477
478         /* returns xml Node with service-instance-id of searchValue */
479         def searchServiceInstanceId(xmlInput, searchValue){
480                 def ret = xmlInput.'**'.find {it.'service-instance-id' == searchValue}
481                 return ret
482         }
483 }