Containerization feature of SO
[so.git] / bpmn / so-bpmn-infrastructure-flows / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteE2EServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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.onap.so.bpmn.infrastructure.scripts
21
22 import static org.apache.commons.lang3.StringUtils.*;
23
24 import javax.xml.parsers.DocumentBuilder
25 import javax.xml.parsers.DocumentBuilderFactory
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.json.JSONArray
31 import org.json.JSONObject;
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
33 import org.onap.so.bpmn.common.scripts.ExceptionUtil
34 import org.onap.so.bpmn.common.scripts.MsoUtils
35 import org.onap.so.bpmn.core.WorkflowException
36 import org.onap.so.bpmn.core.domain.Resource
37 import org.onap.so.bpmn.core.domain.ServiceDecomposition;
38 import org.onap.so.bpmn.core.json.JsonUtils
39 import org.springframework.web.util.UriUtils;
40 import org.w3c.dom.Document
41 import org.w3c.dom.Element
42 import org.w3c.dom.Node
43 import org.w3c.dom.NodeList
44 import org.xml.sax.InputSource
45
46 import groovy.json.*
47
48 /**
49  * This groovy class supports the <class>DoDeleteE2EServiceInstance.bpmn</class> process.
50  *
51  * Inputs:
52  * @param - msoRequestId
53  * @param - globalSubscriberId - O
54  * @param - subscriptionServiceType - O
55  * @param - serviceInstanceId
56  * @param - serviceInstanceName - O
57  * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM)
58  * @param - sdncVersion
59  * @param - failNotFound - TODO
60  * @param - serviceInputParams - TODO
61  *
62  * @param - delResourceList
63  * @param - serviceRelationShip
64  *
65  * Outputs:
66  * @param - WorkflowException
67  *
68  * Rollback - Deferred
69  */
70 public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor {
71
72         String Prefix="DDEESI_"
73     ExceptionUtil exceptionUtil = new ExceptionUtil()
74     JsonUtils jsonUtil = new JsonUtils()
75
76     public void preProcessRequest (DelegateExecution execution) {
77         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
78         utils.log("INFO"," ***** preProcessRequest *****",  isDebugEnabled)
79         String msg = ""
80
81         try {
82             String requestId = execution.getVariable("msoRequestId")
83             execution.setVariable("prefix",Prefix)
84
85             //Inputs
86             //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
87             String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
88             if (globalSubscriberId == null)
89             {
90                 execution.setVariable("globalSubscriberId", "")
91             }
92
93             //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
94             String serviceType = execution.getVariable("serviceType")
95             if (serviceType == null)
96             {
97                 execution.setVariable("serviceType", "")
98             }
99
100             //Generated in parent for AAI PUT
101             String serviceInstanceId = execution.getVariable("serviceInstanceId")
102             if (isBlank(serviceInstanceId)){
103                 msg = "Input serviceInstanceId is null"
104                 utils.log("INFO", msg, isDebugEnabled)
105                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
106             }
107
108             String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback')
109             if (isBlank(sdncCallbackUrl)) {
110                 msg = "URN_mso_workflow_sdncadapter_callback is null"
111                 utils.log("INFO", msg, isDebugEnabled)
112                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
113             }
114             execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
115             utils.log("INFO","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled)
116
117             StringBuilder sbParams = new StringBuilder()
118             Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
119             if (paramsMap != null)
120             {
121                 sbParams.append("<service-input-parameters>")
122                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
123                     String paramsXml
124                     String paramName = entry.getKey()
125                     String paramValue = entry.getValue()
126                     paramsXml =
127                             """ <param>
128                                                         <name>${MsoUtils.xmlEscape(paramName)}</name>
129                                                         <value>${MsoUtils.xmlEscape(paramValue)}</value>
130                                                         </param>
131                                                         """
132                     sbParams.append(paramsXml)
133                 }
134                 sbParams.append("</service-input-parameters>")
135             }
136             String siParamsXml = sbParams.toString()
137             if (siParamsXml == null)
138                 siParamsXml = ""
139             execution.setVariable("siParamsXml", siParamsXml)
140
141         } catch (BpmnError e) {
142             throw e;
143         } catch (Exception ex){
144             msg = "Exception in preProcessRequest " + ex.getMessage()
145             utils.log("INFO", msg, isDebugEnabled)
146             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
147         }
148         utils.log("INFO"," ***** Exit preProcessRequest *****",  isDebugEnabled)
149     }
150
151     public void postProcessAAIGET(DelegateExecution execution) {
152         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
153         utils.log("INFO"," ***** postProcessAAIGET ***** ", isDebugEnabled)
154         String msg = ""
155
156         try {
157             String serviceInstanceId = execution.getVariable("serviceInstanceId")
158             boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator")
159             String serviceType = ""
160
161             if(foundInAAI){
162                 utils.log("INFO","Found Service-instance in AAI", isDebugEnabled)
163
164                 String siData = execution.getVariable("GENGS_service")
165                 utils.log("INFO", "SI Data", isDebugEnabled)
166                 if (isBlank(siData))
167                 {
168                     msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId
169                     utils.log("INFO", msg, isDebugEnabled)
170                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
171                 }
172                 else
173                 {
174                     InputSource source = new InputSource(new StringReader(siData));
175                     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
176                     DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
177                     Document serviceXml = docBuilder.parse(source)
178                     serviceXml.getDocumentElement().normalize()
179                     // get model invariant id
180                     // Get Template uuid and version
181                     if (utils.nodeExists(siData, "model-invariant-id") && utils.nodeExists(siData, "model-version-id") ) {
182                         utils.log("INFO", "SI Data model-invariant-id and model-version-id exist:", isDebugEnabled)
183                         def modelInvariantId  = serviceXml.getElementsByTagName("model-invariant-id").item(0).getTextContent()
184                         def modelVersionId  = serviceXml.getElementsByTagName("model-version-id").item(0).getTextContent()
185
186                         // Set Original Template info
187                         execution.setVariable("model-invariant-id-original", modelInvariantId)
188                         execution.setVariable("model-version-id-original", modelVersionId)
189                     }
190
191                     utils.log("INFO", "SI Data" + siData, isDebugEnabled)
192                     //Confirm there are no related service instances (vnf/network or volume)
193                     if (utils.nodeExists(siData, "relationship-list")) {
194                         utils.log("INFO", "SI Data relationship-list exists:", isDebugEnabled)
195                         //test(siData)
196                         NodeList nodeList = serviceXml.getElementsByTagName("relationship")
197                         JSONArray jArray = new JSONArray()
198                         for (int x = 0; x < nodeList.getLength(); x++) {
199                             Node node = nodeList.item(x)
200                             if (node.getNodeType() == Node.ELEMENT_NODE) {
201                                 Element eElement = (Element) node
202                                 def e = eElement.getElementsByTagName("related-to").item(0).getTextContent()                                                                    //for ns
203                                 if(e.equals("service-instance")){
204                                     def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent()
205                                     utils.log("INFO", "ServiceInstance Related NS :" + relatedObject, isDebugEnabled)
206                                     NodeList dataList = node.getChildNodes()
207                                     if(null != dataList) {
208                                         JSONObject jObj = new JSONObject()
209                                         for (int i = 0; i < dataList.getLength(); i++) {
210                                             Node dNode = dataList.item(i)
211                                             if(dNode.getNodeName() == "relationship-data") {
212                                                 Element rDataEle = (Element)dNode
213                                                 def eKey =  rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent()
214                                                 def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent()
215                                                 if(eKey.equals("service-instance.service-instance-id")){
216                                                     jObj.put("resourceInstanceId", eValue)
217                                                 }
218
219                                             }
220                                             else if(dNode.getNodeName() == "related-to-property"){
221                                                 Element rDataEle = (Element)dNode
222                                                 def eKey =  rDataEle.getElementsByTagName("property-key").item(0).getTextContent()
223                                                 def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent()
224                                                 if(eKey.equals("service-instance.service-instance-name")){
225                                                     jObj.put("resourceType", eValue)
226                                                 }
227                                             }
228                                         }
229                                         utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled)
230                                         jArray.put(jObj)
231                                     }
232                                     //for overlay/underlay
233                                 }else if (e.equals("configuration")){
234                                     def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent()
235                                     utils.log("INFO", "ServiceInstance Related Configuration :" + relatedObject, isDebugEnabled)
236                                     NodeList dataList = node.getChildNodes()
237                                     if(null != dataList) {
238                                         JSONObject jObj = new JSONObject()
239                                         for (int i = 0; i < dataList.getLength(); i++) {
240                                             Node dNode = dataList.item(i)
241                                             if(dNode.getNodeName() == "relationship-data") {
242                                                 Element rDataEle = (Element)dNode
243                                                 def eKey =  rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent()
244                                                 def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent()
245                                                 if(eKey.equals("configuration.configuration-id")){
246                                                     jObj.put("resourceInstanceId", eValue)
247                                                 }
248                                             }
249                                             else if(dNode.getNodeName() == "related-to-property"){
250                                                 Element rDataEle = (Element)dNode
251                                                 def eKey =  rDataEle.getElementsByTagName("property-key").item(0).getTextContent()
252                                                 def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent()
253                                                 if(eKey.equals("configuration.configuration-type")){
254                                                     jObj.put("resourceType", eValue)
255                                                 }
256                                             }
257                                         }
258                                         utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled)
259                                         jArray.put(jObj)
260                                     }
261                                 }
262                             }
263                         }
264                         execution.setVariable("serviceRelationShip", jArray.toString())
265                     }
266                 }
267             }else{
268                 boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
269                 if(!succInAAI){
270                     utils.log("INFO","Error getting Service-instance from AAI", + serviceInstanceId, isDebugEnabled)
271                     WorkflowException workflowException = execution.getVariable("WorkflowException")
272                     utils.logAudit("workflowException: " + workflowException)
273                     if(workflowException != null){
274                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
275                     }
276                     else
277                     {
278                         msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI
279                         utils.log("INFO", msg, isDebugEnabled)
280                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
281                     }
282                 }
283
284                 utils.log("INFO","Service-instance NOT found in AAI. Silent Success", isDebugEnabled)
285             }
286         }catch (BpmnError e) {
287             throw e;
288         } catch (Exception ex) {
289             msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage()
290             utils.log("INFO", msg, isDebugEnabled)
291             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
292         }
293         utils.log("INFO"," *** Exit postProcessAAIGET *** ", isDebugEnabled)
294     }
295
296    public void getCurrentNS(DelegateExecution execution){
297        def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
298        utils.log("INFO", "======== Start getCurrentNS Process ======== ", isDebugEnabled)
299
300        def currentIndex = execution.getVariable("currentNSIndex")
301        List<String> nsSequence = execution.getVariable("nsSequence")
302        String nsResourceType =  nsSequence.get(currentIndex)
303
304        // GET AAI by Name, not ID, for process convenient
305        execution.setVariable("GENGS_type", "service-instance")
306        execution.setVariable("GENGS_serviceInstanceId", "")
307        execution.setVariable("GENGS_serviceInstanceName", nsResourceType)
308
309        utils.log("INFO", "======== COMPLETED getCurrentNS Process ======== ", isDebugEnabled)
310    }
311
312     public void prepareDecomposeService(DelegateExecution execution) {
313         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
314
315         try {
316             utils.log("DEBUG", " ***** Inside prepareDecomposeService of create generic e2e service ***** ", isDebugEnabled)
317             String modelInvariantUuid = execution.getVariable("model-invariant-id-original")
318             String modelVersionId = execution.getVariable("model-version-id-original")
319
320             String serviceModelInfo = """{
321             "modelInvariantUuid":"${modelInvariantUuid}",
322             "modelUuid":"${modelVersionId}",
323             "modelVersion":""
324              }"""
325             execution.setVariable("serviceModelInfo", serviceModelInfo)
326
327             utils.log("DEBUG", " ***** Completed prepareDecomposeService of  create generic e2e service ***** ", isDebugEnabled)
328         } catch (Exception ex) {
329             // try error in method block
330             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
331             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
332         }
333     }
334
335     public void postDecomposeService(DelegateExecution execution) {
336         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
337
338         utils.log("DEBUG", " ***** Inside processDecomposition() of  delete generic e2e service flow ***** ", isDebugEnabled)
339         try {
340             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
341
342             // service model info
343             execution.setVariable("serviceModelInfo", serviceDecomposition.getModelInfo())
344
345             List<Resource> deleteResourceList = serviceDecomposition.getServiceResources()
346             String serviceRelationShip = execution.getVariable("serviceRelationShip")
347             def jsonSlurper = new JsonSlurper()
348             def jsonOutput = new JsonOutput()
349
350             List relationShipList = null
351             if (serviceRelationShip != null) {
352                 relationShipList = jsonSlurper.parseText(serviceRelationShip)
353             }
354
355             //Set the real resource instance id to the decomosed resource list
356             for (Resource resource: deleteResourceList) {
357                 //reset the resource instance id , because in the decompose flow ,its a random one.
358                 resource.setResourceId("");
359                 //match the resource-instance-name and the model name
360                 if (relationShipList != null) {
361                     relationShipList.each {
362                         if (StringUtils.containsIgnoreCase(it.resourceType, resource.getModelInfo().getModelName())) {
363                             resource.setResourceId(it.resourceInstanceId);
364                         }
365                     }
366                 }
367             }
368             execution.setVariable("deleteResourceList", deleteResourceList)
369             utils.log("DEBUG", "delete resource list : " + deleteResourceList, isDebugEnabled)
370         } catch (Exception ex) {
371             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. processDecomposition() - " + ex.getMessage()
372             utils.log("DEBUG", exceptionMessage, isDebugEnabled)
373             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
374         }
375         utils.log("DEBUG", " ***** exit processDecomposition() of  delete generic e2e service flow ***** ", isDebugEnabled)
376     }
377
378     public void preInitResourcesOperStatus(DelegateExecution execution){
379         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
380
381         utils.log("INFO", " ======== STARTED preInitResourcesOperStatus Process ======== ", isDebugEnabled)
382         try{
383             String serviceId = execution.getVariable("serviceInstanceId")
384             String operationId = execution.getVariable("operationId")
385             String operationType = execution.getVariable("operationType")
386             String resourceTemplateUUIDs = ""
387             String result = "processing"
388             String progress = "0"
389             String reason = ""
390             String operationContent = "Prepare service creation"
391             utils.log("INFO", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType, isDebugEnabled)
392             serviceId = UriUtils.encode(serviceId,"UTF-8")
393             execution.setVariable("serviceInstanceId", serviceId)
394             execution.setVariable("operationId", operationId)
395             execution.setVariable("operationType", operationType)
396             List<Resource> deleteResourceList = execution.getVariable("deleteResourceList")
397
398             String serviceRelationShip = execution.getVariable("serviceRelationShip")
399             for(Resource resource : deleteResourceList){
400                     resourceTemplateUUIDs  = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":"
401             }
402
403
404             execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter")
405
406             String payload =
407                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
408                         xmlns:ns="http://org.onap.so/requestsdb">
409                         <soapenv:Header/>
410                         <soapenv:Body>
411                             <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
412                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
413                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
414                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
415                             <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs>
416                         </ns:initResourceOperationStatus>
417                     </soapenv:Body>
418                 </soapenv:Envelope>"""
419
420             payload = utils.formatXml(payload)
421             execution.setVariable("CVFMI_initResOperStatusRequest", payload)
422             utils.log("INFO", "Outgoing initResourceOperationStatus: \n" + payload, isDebugEnabled)
423             utils.logAudit("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload)
424
425         }catch(Exception e){
426             utils.log("ERROR", "Exception Occured Processing preInitResourcesOperStatus. Exception is:\n" + e, isDebugEnabled)
427             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
428         }
429         utils.log("INFO", "======== COMPLETED preInitResourcesOperStatus Process ======== ", isDebugEnabled)
430     }
431
432      /**
433       * post config request.
434       */
435      public void postConfigRequest(execution){
436          //to do
437      }
438
439 }