Containerization feature of SO
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / AllottedResourceUtils.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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.onap.so.bpmn.common.scripts
22
23 import static org.apache.commons.lang3.StringUtils.*;
24
25 import org.apache.commons.lang3.*
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution;
28 import org.onap.so.bpmn.core.UrnPropertiesReader
29 import org.onap.so.bpmn.core.WorkflowException
30 import org.onap.so.logger.MessageEnum
31 import org.onap.so.logger.MsoLogger
32 import org.onap.so.rest.APIResponse;
33
34
35
36 class AllottedResourceUtils {
37         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, AllottedResourceUtils.class);
38
39
40         private AbstractServiceTaskProcessor taskProcessor
41         ExceptionUtil exceptionUtil = new ExceptionUtil()
42         MsoUtils utils;
43
44         public AllottedResourceUtils(AbstractServiceTaskProcessor taskProcessor) {
45                 this.taskProcessor = taskProcessor
46                 this.utils = taskProcessor.utils
47         }
48
49         /*Used on Create - called from DoCreate
50         * Using Consuming ServiceInstanceId get related Allotted Resources Orchestration status from AAI
51         * 1) get related AR links for CSI 2) get AR from AR links
52         * return: null -> AR Not found
53         * return: " " -> AR found with empty orchStatus
54         * return: orchStatus - > AR found with this orchStatus
55         * setsVariable aaiARGetResponse
56         */
57         public String getAROrchStatus (DelegateExecution execution) {
58
59                 msoLogger.trace("getAROrchStatus ")
60                 String msg = ""
61                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
62                 String arType = execution.getVariable("allottedResourceType")
63                 String arRole = execution.getVariable("allottedResourceRole")
64                 String siXml = execution.getVariable("CSI_service")
65                 String ar = null
66                 String orchStatus = null
67                 XmlParser xmlParser = new XmlParser()
68                 msoLogger.debug("getAROrchStatus siXml:" + siXml)
69                 try {
70                         if (!isBlank(siXml)) {
71                                 def groovy.util.Node siNode = xmlParser.parseText(siXml)
72                                 def groovy.util.Node relationshipList = utils.getChildNode(siNode, 'relationship-list')
73                                 if (relationshipList != null) {
74                                         def groovy.util.NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship')
75                                         for (groovy.util.Node relationship in relationships) {
76                                                 def groovy.util.Node relatedTo = utils.getChildNode(relationship, 'related-to')
77                                                 if ((relatedTo != null) && (relatedTo.text().equals('allotted-resource'))) {
78                                                         msoLogger.debug("getARORchStatus AR found")
79                                                         def groovy.util.Node relatedLink = utils.getChildNode(relationship, 'related-link')
80                                                         if (relatedLink != null){
81                                                                 ar = getARbyLink(execution, relatedLink.text(), arRole)
82                                                                 if (!isBlank(ar))
83                                                                 {
84                                                                         orchStatus = execution.getVariable("aaiAROrchStatus")
85                                                                         break
86                                                                 }
87                                                         }
88                                                 }
89                                         }
90                                 }
91                         }
92                 }catch(Exception e){
93                         msoLogger.debug(" Error encountered in getAROrchStatus" + e.getMessage())
94                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in getAROrchStatus" + e.getMessage())
95                 }
96                 msoLogger.trace(" Exit getAROrchStatus - OrchStatus:" + orchStatus)
97                 return orchStatus
98         }
99
100         // get Allotted Resource by AllottedResourceId
101         // used on Delete - called from doDeleteAR
102         // setsVariable aaiARGetResponse
103         public String getARbyId (DelegateExecution execution, String allottedResourceId) {
104                 msoLogger.trace("getARbyId ")
105                 String arLink = getARLinkbyId(execution, allottedResourceId)
106                 String ar = null
107                 if (!isBlank(arLink))
108                 {
109                         ar = getARbyLink(execution, arLink, "")
110                 }
111                 msoLogger.trace(" Exit GetARbyId - AR:" + ar)
112                 return ar;
113         }
114         
115         public String getPSIFmARLink(DelegateExecution execution, String arLink)
116         {
117                 // Path: /aai/{version}/business/customers/customer/{cust}/service-subscriptions/service-subscription/{subs}/service-instances/service-instance/{psiid}/allotted-resources/allotted-resource/{arid}
118                 msoLogger.trace(" getPSIFmARLink - path:" + arLink)
119                 String[] split = arLink.split("/service-instance/")
120                 String[] splitB =  split[1].split("/allotted-resources/")
121                 String siId = splitB[0]
122                 msoLogger.trace(" Exit getARLinkbyId - parentServiceInstanceId:" + siId )
123                 return siId
124         }
125
126         // get Allotted Resource Link by AllottedResourceId using Nodes Query
127         // used on Delete - called from getARbyId
128         public String getARLinkbyId (DelegateExecution execution, String allottedResourceId) {
129                 msoLogger.trace("getARLinkbyId ")
130                 String arLink = null
131                 try {
132                         AaiUtil aaiUriUtil = new AaiUtil(taskProcessor)
133                         String aaiNQUri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
134                         String aaiEndpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
135                         String aaiUrl = "${aaiNQUri}?search-node-type=allotted-resource&filter=id:EQUALS:${allottedResourceId}"
136
137                         msoLogger.debug("getARLinkbyId url: \n" + aaiUrl)
138
139                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, aaiUrl)
140                         int responseCode = response.getStatusCode()
141                         msoLogger.debug("  GET AR response code is: " + responseCode)
142
143                         String aaiResponse = response.getResponseBodyAsString()
144                         msoLogger.debug("GET AR:" + aaiResponse)
145                         if(responseCode == 200 || responseCode == 202){
146                                 msoLogger.debug("GET AR Received a Good Response Code")
147                                 if(utils.nodeExists(aaiResponse, "result-data")){
148                                         msoLogger.debug("Query for AllottedResource Url Response Does Contain Data" )
149                                         arLink = utils.getNodeText(aaiResponse, "resource-link")
150                                 }else{
151                                         msoLogger.debug("GET AR Response Does NOT Contain Data" )
152                                 }
153                         }else if(responseCode == 404){
154                                 msoLogger.debug("GET AR received a Not Found (404) Response")
155                         }
156                         else{
157                                 msoLogger.debug("  GET AR received a Bad Response: \n" + aaiResponse)
158                                 buildAAIErrorResponse(execution, aaiResponse, "Error retrieving AR from AAI")
159                         }
160                 }catch(Exception e){
161                         msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage())
162                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetARbyId" + e.getMessage())
163                 }
164                 msoLogger.trace(" Exit GetARLinkbyId - Link:" + arLink)
165                 return arLink
166         }
167
168         // get Allotted resource using Link
169         // used on Create called from getARORchStatus
170         // used on Delete called from getARbyId
171         // setsVariable aaiARPath - used for Patch in create
172         public String getARbyLink (DelegateExecution execution, String link, String role) {
173                 msoLogger.trace("getARbyLink ")
174                 String ar = null
175                 String arUrl = null
176                 try {
177                         AaiUtil aaiUriUtil = new AaiUtil(taskProcessor)
178                         String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution)
179                         String arEndpoint = ""
180
181                         if(!isBlank(link)) {
182                                 msoLogger.debug("Incoming AR Resource Link is: " + link)
183                                 String[] split = link.split("/aai/")
184                                 arEndpoint = "/aai/" + split[1]
185                         }
186
187                         arUrl = "${aai_endpoint}" + arEndpoint
188                 
189                         msoLogger.debug("GET AR Aai Path is: \n" + arUrl)
190
191                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, arUrl)
192                         int responseCode = response.getStatusCode()
193                         msoLogger.debug("  GET AR response code is: " + responseCode)
194
195                         String aaiResponse = response.getResponseBodyAsString()
196                         msoLogger.debug("GET AR:" + aaiResponse)
197                         if(responseCode == 200 || responseCode == 202){
198                                 msoLogger.debug("GET AR Received a Good Response Code")
199                                 if(utils.nodeExists(aaiResponse, "allotted-resource")){
200                                         if (!isBlank(role))
201                                         {
202                                                 if (utils.nodeExists(aaiResponse, "role") && role.equals(utils.getNodeText(aaiResponse, "role"))) {
203                                                         ar = aaiResponse
204                                                 }else{
205                                                         msoLogger.debug("AAI AR does not match input role:" + role)
206                                                 }
207                                         }
208                                         else
209                                         {
210                                                 ar = aaiResponse
211                                         }
212                                 }
213                                 else
214                                 {
215                                         msoLogger.debug("GET AR Does NOT Contain Data" )
216                                 }
217                         }else if(responseCode == 404){
218                                 msoLogger.debug("GET AR received a Not Found (404) Response")
219                         }
220                         else{
221                                 msoLogger.debug("  GET AR received a Bad Response: \n" + aaiResponse)
222                                 buildAAIErrorResponse(execution, aaiResponse, "Error retrieving AR from AAI")
223                         }
224                 }catch(Exception e){
225                         msoLogger.debug(" Error encountered within GetAaiAR" + e.getMessage())
226                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error in GetAaiAR" + e.getMessage())
227                 }
228                 if (!isBlank(ar))
229                 {
230                         execution.setVariable("aaiARGetResponse", ar)
231                         execution.setVariable("aaiARPath", arUrl)
232                         
233                         String resourceVersion = null
234                         if (utils.nodeExists(ar, "resource-version")) {
235                                 resourceVersion = utils.getNodeText(ar, "resource-version")
236                                 execution.setVariable("aaiARResourceVersion", resourceVersion)
237                         }
238                         
239                         String orchStatus = null
240                         if (utils.nodeExists(ar, "orchestration-status")) {
241                                 orchStatus= utils.getNodeText(ar, "orchestration-status")
242                         }
243                         else
244                         {
245                                 orchStatus = " "
246                         }
247                         execution.setVariable("aaiAROrchStatus", orchStatus)
248                 }
249                 msoLogger.trace(" Exit GetARbyLink - AR:" + ar)
250                 return ar
251         }
252
253         public void updateAROrchStatus(DelegateExecution execution, String status, String aaiARPath){
254                 msoLogger.trace("updaAROrchStatus ")
255                 try{
256
257                         String updateReq =      """
258                                         {
259                                         "orchestration-status": "${status}"
260                                         }
261                                         """
262
263                         msoLogger.debug('AAI AR URI: ' + aaiARPath)
264
265                         AaiUtil aaiUriUtil = new AaiUtil(taskProcessor)
266                         APIResponse apiResponse = aaiUriUtil.executeAAIPatchCall(execution, aaiARPath, updateReq)
267                         def aaiResponse = apiResponse.getResponseBodyAsString()
268                         def responseCode = apiResponse.getStatusCode()
269
270                         msoLogger.debug("AAI Response Code: " + responseCode)
271                         msoLogger.debug("AAI Response: " + aaiResponse)
272                         if(responseCode == 200){
273                                 msoLogger.debug("UpdateAR Good REST Response is: " + "\n" + aaiResponse)
274                         }else{
275                                 msoLogger.debug("UpdateAROrchStatus Bad REST Response!")
276                                 buildAAIErrorResponse(execution, aaiResponse, "Error updating AR OrchStatus in AAI")
277                         }
278
279                 }catch(BpmnError b){
280                         msoLogger.debug("Rethrowing MSOWorkflowException ")
281                         throw b
282                 }catch(Exception e){
283                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception in updateAR.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage());
284                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, 'Internal Error in updateAROrchStatus.' + e.getMessage())
285                 }
286                 msoLogger.trace("Exit updateAROrchStatus ")
287         }
288         
289         //Sets Variable "wasDeleted"
290         public void deleteAR(DelegateExecution execution, String aaiARPath){
291                 msoLogger.trace(" deleteAR - aaiARPath:" + aaiARPath)
292                 try {
293                         AaiUtil aaiUriUtil = new AaiUtil(taskProcessor)
294                         APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, aaiARPath)
295                         int responseCode = response.getStatusCode()
296                         execution.setVariable("deleteARResponseCode", responseCode)
297                         
298                         msoLogger.debug("  Delete AR response code:" + responseCode)
299
300                         String aaiResponse = response.getResponseBodyAsString()
301                         execution.setVariable("aaiARDeleteResponse", aaiResponse)
302
303                         msoLogger.debug("Delete AR Response:" + aaiResponse)
304                         
305                         //Process Response
306                         if(responseCode == 204){
307                                 msoLogger.debug("  Delete AR Received a Good Response")
308                                 execution.setVariable("wasDeleted", "true")
309                         }else if(responseCode == 404){
310                                 msoLogger.debug("  Delete AR Received a Not Found (404) Response")
311                         }else if(responseCode == 412){
312                                 msoLogger.debug("Delete AR Received a Resource Version Mismatch Error: \n" + aaiResponse)
313                                 exceptionUtil.buildAndThrowWorkflowException(execution, 412, "DeleteAR Received a resource-version Mismatch Error Response from AAI")
314                         }else{
315                                 msoLogger.debug("Delete AR Received a BAD REST Response: \n" + aaiResponse)
316                                 buildAAIErrorResponse(execution, aaiResponse, "Error deleting AR in AAI")
317                                 exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
318                         }
319                 }catch(BpmnError b){
320                         msoLogger.debug("Rethrowing MSOWorkflowException")
321                         throw b
322                 }catch(Exception e){
323                         msoLogger.debug(" Error encountered in deleteAR!" + e)
324                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During Delete AR")
325                 }
326                 msoLogger.trace("Exit deleteAR ")
327         }
328
329         public void buildAAIErrorResponse(DelegateExecution execution, String response, String errorMessage){
330                 msoLogger.trace("BuildAAIErrorResponse")
331
332                 if((response != null) && (response.contains("Fault") || response.contains("RESTFault"))){
333                         WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(response, execution)
334                         execution.setVariable("WorkflowException", workflowException)
335                 }else{
336                         exceptionUtil.buildWorkflowException(execution, 500, errorMessage)
337                 }
338
339                 msoLogger.trace("Exit BuildAAIErrorResponse Process")
340                 throw new BpmnError("MSOWorkflowException")
341         }
342
343 }