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