Groovy scripts header correction
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoDeleteServiceInstance.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 package org.openecomp.mso.bpmn.infrastructure.scripts;
21
22 import static org.apache.commons.lang3.StringUtils.*;
23 import groovy.xml.XmlUtil
24 import groovy.json.*
25
26 import org.openecomp.mso.bpmn.core.json.JsonUtils
27 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
29 import org.openecomp.mso.bpmn.common.scripts.SDNCAdapterUtils
30 import org.openecomp.mso.bpmn.core.WorkflowException
31 import org.openecomp.mso.rest.APIResponse;
32 import org.openecomp.mso.rest.RESTClient
33 import org.openecomp.mso.rest.RESTConfig
34
35 import java.util.UUID;
36 import javax.xml.parsers.DocumentBuilder
37 import javax.xml.parsers.DocumentBuilderFactory
38
39 import org.camunda.bpm.engine.delegate.BpmnError
40 import org.camunda.bpm.engine.runtime.Execution
41 import org.json.JSONObject;
42 import org.apache.commons.lang3.*
43 import org.apache.commons.codec.binary.Base64;
44 import org.springframework.web.util.UriUtils;
45 import org.w3c.dom.Document
46 import org.w3c.dom.Element
47 import org.w3c.dom.Node
48 import org.w3c.dom.NodeList
49 import org.xml.sax.InputSource
50
51 /**
52  * This groovy class supports the <class>DoDeleteServiceInstance.bpmn</class> process.
53  * 
54  * Inputs:
55  * @param - msoRequestId
56  * @param - globalSubscriberId - O
57  * @param - subscriptionServiceType - O
58  * @param - serviceInstanceId
59  * @param - serviceInstanceName - O
60  * @param - serviceModelInfo - O
61  * @param - productFamilyId
62  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
63  * @param - sdncVersion 
64  * @param - failNotFound - TODO
65  * @param - serviceInputParams - TODO
66  *
67  * Outputs:
68  * @param - WorkflowException
69  * 
70  * Rollback - Deferred
71  */
72 public class DoDeleteServiceInstance extends AbstractServiceTaskProcessor {
73
74         String Prefix="DDELSI_"
75         ExceptionUtil exceptionUtil = new ExceptionUtil()
76         JsonUtils jsonUtil = new JsonUtils()
77
78         public void preProcessRequest (Execution execution) {
79                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
80                 utils.log("DEBUG"," ***** preProcessRequest *****",  isDebugEnabled)
81                 String msg = ""
82
83                 try {
84                         String requestId = execution.getVariable("msoRequestId")
85                         execution.setVariable("prefix",Prefix)
86
87                         //Inputs
88                         //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
89                         String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
90                         if (globalSubscriberId == null)
91                         {
92                                 execution.setVariable("globalSubscriberId", "")
93                         }
94
95                         //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
96                         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
97                         if (subscriptionServiceType == null)
98                         {
99                                 execution.setVariable("subscriptionServiceType", "")
100                         }
101
102                         //Generated in parent for AAI PUT
103                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
104                         if (isBlank(serviceInstanceId)){
105                                 msg = "Input serviceInstanceId is null"
106                                 utils.log("DEBUG", msg, isDebugEnabled)
107                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
108                         }
109
110                         String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback')
111                         if (isBlank(sdncCallbackUrl)) {
112                                 msg = "URN_mso_workflow_sdncadapter_callback is null"
113                                 utils.log("DEBUG", msg, isDebugEnabled)
114                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
115                         }
116                         execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
117                         utils.log("DEBUG","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled)
118
119                         StringBuilder sbParams = new StringBuilder()
120                         Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
121                         if (paramsMap != null)
122                         {
123                                 sbParams.append("<service-input-parameters>")
124                                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
125                                         String paramsXml
126                                         String paramName = entry.getKey()
127                                         String paramValue = entry.getValue()
128                                         paramsXml =
129                                                         """     <param>
130                                                         <name>${paramName}</name>
131                                                         <value>${paramValue}</value>
132                                                         </param>
133                                                         """
134                                         sbParams.append(paramsXml)
135                                 }
136                                 sbParams.append("</service-input-parameters>")
137                         }
138                         String siParamsXml = sbParams.toString()
139                         if (siParamsXml == null)
140                                 siParamsXml = ""
141                         execution.setVariable("siParamsXml", siParamsXml)
142
143                 } catch (BpmnError e) {
144                         throw e;
145                 } catch (Exception ex){
146                         msg = "Exception in preProcessRequest " + ex.getMessage()
147                         utils.log("DEBUG", msg, isDebugEnabled)
148                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
149                 }
150                 utils.log("DEBUG"," ***** Exit preProcessRequest *****",  isDebugEnabled)
151         }
152
153         public void preProcessSDNCDelete (Execution execution) {
154                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
155                 utils.log("DEBUG"," ***** preProcessSDNCDelete *****", isDebugEnabled)
156                 String msg = ""
157
158                 try {
159                         def serviceInstanceId = execution.getVariable("serviceInstanceId")
160                         def serviceInstanceName = execution.getVariable("serviceInstanceName")
161                         def callbackURL = execution.getVariable("sdncCallbackUrl")
162                         def requestId = execution.getVariable("msoRequestId")
163                         def serviceId = execution.getVariable("productFamilyId")
164                         def subscriptionServiceType = execution.getVariable("subscriptionServiceType")
165                         def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
166
167                         String serviceModelInfo = execution.getVariable("serviceModelInfo")
168                         def modelInvariantUuid = ""
169                         def modelVersion = ""
170                         def modelUuid = ""
171                         def modelName = ""
172                         if (!isBlank(serviceModelInfo))
173                         {
174                                 modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid")
175                                 modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion")
176                                 modelUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelUuid")
177                                 modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName")
178
179                                 if (modelInvariantUuid == null) {
180                                         modelInvariantUuid = ""
181                                 }
182                                 if (modelVersion == null) {
183                                         modelVersion = ""
184                                 }
185                                 if (modelUuid == null) {
186                                         modelUuid = ""
187                                 }
188                                 if (modelName == null) {
189                                         modelName = ""
190                                 }
191                         }
192                         if (serviceInstanceName == null) {
193                                 serviceInstanceName = ""
194                         }
195                         if (serviceId == null) {
196                                 serviceId = ""
197                         }
198
199                         def siParamsXml = execution.getVariable("siParamsXml")
200                         def serviceType = execution.getVariable("serviceType")
201                         if (serviceType == null)
202                         {
203                                 serviceType = ""
204                         }
205
206                         def sdncRequestId = UUID.randomUUID().toString()
207
208                         String sdncDelete =
209                                         """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.openecomp/mso/request/types/v1"
210                                                                                                         xmlns:sdncadapterworkflow="http://org.openecomp/mso/workflow/schema/v1"
211                                                                                                         xmlns:sdncadapter="http://org.openecomp/workflow/sdnc/adapter/schema/v1">
212                                    <sdncadapter:RequestHeader>
213                                                         <sdncadapter:RequestId>${sdncRequestId}</sdncadapter:RequestId>
214                                                         <sdncadapter:SvcInstanceId>${serviceInstanceId}</sdncadapter:SvcInstanceId>
215                                                         <sdncadapter:SvcAction>delete</sdncadapter:SvcAction>
216                                                         <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
217                                                         <sdncadapter:CallbackUrl>${callbackURL}</sdncadapter:CallbackUrl>
218                                                         <sdncadapter:MsoAction>${serviceType}</sdncadapter:MsoAction>
219                                         </sdncadapter:RequestHeader>
220                                 <sdncadapterworkflow:SDNCRequestData>
221                                         <request-information>
222                                                 <request-id>${requestId}</request-id>
223                                                 <source>MSO</source>
224                                                 <notification-url/>
225                                                 <order-number/>
226                                                 <order-version/>
227                                                 <request-action>DeleteServiceInstance</request-action>
228                                         </request-information>
229                                         <service-information>
230                                                 <service-id>${serviceId}</service-id>
231                                                 <subscription-service-type>${subscriptionServiceType}</subscription-service-type>
232                                                 <ecomp-model-information>
233                                                  <model-invariant-uuid>${modelInvariantUuid}</model-invariant-uuid>
234                                                  <model-uuid>${modelUuid}</model-uuid>
235                                                  <model-version>${modelVersion}</model-version>
236                                                  <model-name>${modelName}</model-name>
237                                             </ecomp-model-information>
238                                                 <service-instance-id>${serviceInstanceId}</service-instance-id>
239                                                 <subscriber-name/>
240                                                 <global-customer-id>${globalSubscriberId}</global-customer-id>
241                                         </service-information>
242                                         <service-request-input>
243                                                 <service-instance-name>${serviceInstanceName}</service-instance-name>
244                                                 ${siParamsXml}
245                                         </service-request-input>
246                                 </sdncadapterworkflow:SDNCRequestData>
247                                 </sdncadapterworkflow:SDNCAdapterWorkflowRequest>"""
248
249                         sdncDelete = utils.formatXml(sdncDelete)
250                         def sdncRequestId2 = UUID.randomUUID().toString()
251                         String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<")
252                         execution.setVariable("sdncDelete", sdncDelete)
253                         execution.setVariable("sdncDeactivate", sdncDeactivate)
254                         utils.log("DEBUG","sdncDeactivate:\n" + sdncDeactivate, isDebugEnabled)
255                         utils.log("DEBUG","sdncDelete:\n" + sdncDelete, isDebugEnabled)
256
257                 } catch (BpmnError e) {
258                         throw e;
259                 } catch(Exception ex) {
260                         msg = "Exception in preProcessSDNCDelete. " + ex.getMessage()
261                         utils.log("DEBUG", msg, isDebugEnabled)
262                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage())
263                 }
264                 utils.log("DEBUG"," *****Exit preProcessSDNCDelete *****", isDebugEnabled)
265         }
266
267         public void postProcessSDNCDelete(Execution execution, String response, String method) {
268
269                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
270                 utils.log("DEBUG"," ***** postProcessSDNC " + method + " *****", isDebugEnabled)
271                 String msg = ""
272
273                 try {
274                         WorkflowException workflowException = execution.getVariable("WorkflowException")
275                         boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator")
276                         utils.log("DEBUG", "SDNCResponse: " + response, isDebugEnabled)
277                         utils.log("DEBUG", "workflowException: " + workflowException, isDebugEnabled)
278
279                         SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this)
280                         sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator)
281
282                         if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){
283                                 utils.log("DEBUG","Good response from SDNC Adapter for service-instance " + method + "response:\n" + response, isDebugEnabled)
284
285                         }else{
286                                 msg = "Bad Response from SDNC Adapter for service-instance " + method
287                                 utils.log("DEBUG", msg, isDebugEnabled)
288                                 exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg)
289                         }
290                 } catch (BpmnError e) {
291                         throw e;
292                 } catch(Exception ex) {
293                         msg = "Exception in postProcessSDNC " + method + " Exception:" + ex.getMessage()
294                         utils.log("DEBUG", msg, isDebugEnabled)
295                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
296                 }
297                 utils.log("DEBUG"," *** Exit postProcessSDNC " + method + " ***", isDebugEnabled)
298         }
299
300         public void postProcessAAIGET(Execution execution) {
301                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
302                 utils.log("DEBUG"," ***** postProcessAAIGET ***** ", isDebugEnabled)
303                 String msg = ""
304
305                 try {
306
307                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
308                         boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
309                         String serviceType = ""
310
311                         if(foundInAAI == true){
312                                 utils.log("DEBUG","Found Service-instance in AAI", isDebugEnabled)
313
314                                 //Extract GlobalSubscriberId
315                                 String siRelatedLink = execution.getVariable("GENGS_siResourceLink")
316                                 if (isBlank(siRelatedLink))
317                                 {
318                                         msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId
319                                         utils.log("DEBUG", msg, isDebugEnabled)
320                                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
321                                 }
322                                 else
323                                 {
324                                         utils.log("DEBUG","Found Service-instance in AAI. link: " + siRelatedLink, isDebugEnabled)
325                                         String  globalSubscriberId = execution.getVariable("globalSubscriberId")
326                                         if(isBlank(globalSubscriberId)){
327                                                 int custStart = siRelatedLink.indexOf("customer/")
328                                                 int custEnd = siRelatedLink.indexOf("/service-subscriptions")
329                                                 globalSubscriberId = siRelatedLink.substring(custStart + 9, custEnd)
330                                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
331                                         }
332
333                                         //Extract Service Type if not provided on request
334                                         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
335                                         if(isBlank(subscriptionServiceType)){
336                                                 int serviceStart = siRelatedLink.indexOf("service-subscription/")
337                                                 int serviceEnd = siRelatedLink.indexOf("/service-instances/")
338                                                 String serviceTypeEncoded = siRelatedLink.substring(serviceStart + 21, serviceEnd)
339                                                 subscriptionServiceType = UriUtils.decode(serviceTypeEncoded, "UTF-8")
340                                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
341                                         }
342
343                                         if (isBlank(globalSubscriberId) || isBlank(subscriptionServiceType))
344                                         {
345                                                 msg = "Could not retrive global-customer-id & subscription-service-type from AAI to delete id:" + serviceInstanceId
346                                                 utils.log("DEBUG", msg, isDebugEnabled)
347                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
348                                         }
349                                 }
350
351                                 String siData = execution.getVariable("GENGS_service")
352                                 utils.log("DEBUG", "SI Data", isDebugEnabled)
353                                 if (isBlank(siData))
354                                 {
355                                         msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId
356                                         utils.log("DEBUG", msg, isDebugEnabled)
357                                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
358                                 }
359                                 else
360                                 {
361                                         utils.log("DEBUG", "SI Data" + siData, isDebugEnabled)
362                                         serviceType = utils.getNodeText1(siData,"service-type")
363                                         execution.setVariable("serviceType", serviceType)
364                                         execution.setVariable("serviceRole", utils.getNodeText1(siData,"service-role"))
365                                         String orchestrationStatus =  utils.getNodeText1(siData,"orchestration-status")
366
367                                         //Confirm there are no related service instances (vnf/network or volume)
368                                         if (utils.nodeExists(siData, "relationship-list")) {
369                                                 utils.log("DEBUG", "SI Data relationship-list exists:", isDebugEnabled)
370                                                 InputSource source = new InputSource(new StringReader(siData));
371                                                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
372                                                 DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
373                                                 Document serviceXml = docBuilder.parse(source)
374
375                                                 NodeList nodeList = serviceXml.getElementsByTagName("relationship")
376                                                 for (int x = 0; x < nodeList.getLength(); x++) {
377                                                         Node node = nodeList.item(x)
378                                                         if (node.getNodeType() == Node.ELEMENT_NODE) {
379                                                                 Element eElement = (Element) node
380                                                                 def e = eElement.getElementsByTagName("related-to").item(0).getTextContent()
381                                                                 if(e.equals("generic-vnf") || e.equals("l3-network") || e.equals("allotted-resource") ){
382                                                                         utils.log("DEBUG", "ServiceInstance still has relationship(s) to generic-vnfs, l3-networks or allotted-resources", isDebugEnabled)
383                                                                         execution.setVariable("siInUse", true)
384                                                                         //there are relationship dependencies to this Service Instance
385                                                                         msg = " Stopped deleting Service Instance, it has dependencies. Service instance id: " + serviceInstanceId
386                                                                         utils.log("DEBUG", msg, isDebugEnabled)
387                                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
388                                                                 }else{
389                                                                         utils.log("DEBUG", "Relationship NOT related to OpenStack", isDebugEnabled)
390                                                                 }
391                                                         }
392                                                 }
393                                         }
394
395                                         if ("TRANSPORT".equalsIgnoreCase(serviceType))
396                                         {
397                                                 if ("PendingDelete".equals(orchestrationStatus))
398                                                 {
399                                                         execution.setVariable("skipDeactivate", true)
400                                                 }
401                                                 else
402                                                 {
403                                                         msg = "ServiceInstance of type TRANSPORT must in PendingDelete status to allow Delete. Orchestration-status:" + orchestrationStatus
404                                                         utils.log("DEBUG", msg, isDebugEnabled)
405                                                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
406                                                 }
407
408                                         }
409                                 }
410                         }else{
411                                 boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
412                                 if(succInAAI != true){
413                                         utils.log("DEBUG","Error getting Service-instance from AAI", + serviceInstanceId, isDebugEnabled)
414                                         WorkflowException workflowException = execution.getVariable("WorkflowException")
415                                         utils.logAudit("workflowException: " + workflowException)
416                                         if(workflowException != null){
417                                                 exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
418                                         }
419                                         else
420                                         {
421                                                 msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI
422                                                 utils.log("DEBUG", msg, isDebugEnabled)
423                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
424                                         }
425                                 }
426
427                                 utils.log("DEBUG","Service-instance NOT found in AAI. Silent Success", isDebugEnabled)
428                         }
429                 } catch (BpmnError e) {
430                         throw e;
431                 } catch (Exception ex) {
432                         msg = "Exception in DoDeleteServiceInstance.postProcessAAIGET. " + ex.getMessage()
433                         utils.log("DEBUG", msg, isDebugEnabled)
434                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
435                 }
436                 utils.log("DEBUG"," *** Exit postProcessAAIGET *** ", isDebugEnabled)
437         }
438
439         public void postProcessAAIDEL(Execution execution) {
440                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
441                 utils.log("DEBUG"," ***** postProcessAAIDEL ***** ", isDebugEnabled)
442                 String msg = ""
443                 try {
444                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
445                         boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator")
446                         if(succInAAI != true){
447                                 msg = "Error deleting Service-instance in AAI" + serviceInstanceId
448                                 utils.log("DEBUG", msg, isDebugEnabled)
449                                 WorkflowException workflowException = execution.getVariable("WorkflowException")
450                                 utils.logAudit("workflowException: " + workflowException)
451                                 if(workflowException != null){
452                                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
453                                 }
454                                 else
455                                 {
456                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
457                                 }
458                         }
459                 } catch (BpmnError e) {
460                         throw e;
461                 } catch (Exception ex) {
462                         msg = "Exception in DoDeleteServiceInstance.postProcessAAIDEL. " + ex.getMessage()
463                         utils.log("DEBUG", msg, isDebugEnabled)
464                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
465                 }
466                 utils.log("DEBUG"," *** Exit postProcessAAIDEL *** ", isDebugEnabled)
467         }
468 }