76dba27890b26402dc19cbd0b16b4b495ab6b34a
[so.git] /
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                         JSONArray jArray = new JSONArray()
196
197                         XmlParser xmlParser = new XmlParser()
198                         Node root = xmlParser.parseText(siData)
199                         def relation_list = utils.getChildNode(root, 'relationship-list')
200                         def relationships = utils.getIdenticalChildren(relation_list, 'relationship')
201
202                         for (def relation: relationships) {
203                                 def jObj = getRelationShipData(relation, isDebugEnabled)
204                                 jArray.put(jObj)
205                         }
206
207                         execution.setVariable("serviceRelationShip", jArray.toString())
208                                                 
209 //                        //test(siData)
210 //                        NodeList nodeList = serviceXml.getElementsByTagName("relationship")
211 //                        JSONArray jArray = new JSONArray()
212 //                        for (int x = 0; x < nodeList.getLength(); x++) {
213 //                            Node node = nodeList.item(x)
214 //                            if (node.getNodeType() == Node.ELEMENT_NODE) {
215 //                                Element eElement = (Element) node
216 //                                def e = eElement.getElementsByTagName("related-to").item(0).getTextContent()                                                                  //for ns
217 //                                if(e.equals("service-instance")){
218 //                                    def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent()
219 //                                    utils.log("INFO", "ServiceInstance Related NS :" + relatedObject, isDebugEnabled)
220 //                                    NodeList dataList = node.getChildNodes()
221 //                                    if(null != dataList) {
222 //                                        JSONObject jObj = new JSONObject()
223 //                                        for (int i = 0; i < dataList.getLength(); i++) {
224 //                                            Node dNode = dataList.item(i)
225 //                                            if(dNode.getNodeName() == "relationship-data") {
226 //                                                Element rDataEle = (Element)dNode
227 //                                                def eKey =  rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent()
228 //                                                def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent()
229 //                                                if(eKey.equals("service-instance.service-instance-id")){
230 //                                                    jObj.put("resourceInstanceId", eValue)
231 //                                                }
232 //
233 //                                            }
234 //                                            else if(dNode.getNodeName() == "related-to-property"){
235 //                                                Element rDataEle = (Element)dNode
236 //                                                def eKey =  rDataEle.getElementsByTagName("property-key").item(0).getTextContent()
237 //                                                def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent()
238 //                                                if(eKey.equals("service-instance.service-instance-name")){
239 //                                                    jObj.put("resourceType", eValue)
240 //                                                }
241 //                                            }
242 //                                        }
243 //                                        utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled)
244 //                                        jArray.put(jObj)
245 //                                    }
246 //                                    //for overlay/underlay
247 //                                }else if (e.equals("configuration")){
248 //                                    def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent()
249 //                                    utils.log("INFO", "ServiceInstance Related Configuration :" + relatedObject, isDebugEnabled)
250 //                                    NodeList dataList = node.getChildNodes()
251 //                                    if(null != dataList) {
252 //                                        JSONObject jObj = new JSONObject()
253 //                                        for (int i = 0; i < dataList.getLength(); i++) {
254 //                                            Node dNode = dataList.item(i)
255 //                                            if(dNode.getNodeName() == "relationship-data") {
256 //                                                Element rDataEle = (Element)dNode
257 //                                                def eKey =  rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent()
258 //                                                def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent()
259 //                                                if(eKey.equals("configuration.configuration-id")){
260 //                                                    jObj.put("resourceInstanceId", eValue)
261 //                                                }
262 //                                            }
263 //                                            else if(dNode.getNodeName() == "related-to-property"){
264 //                                                Element rDataEle = (Element)dNode
265 //                                                def eKey =  rDataEle.getElementsByTagName("property-key").item(0).getTextContent()
266 //                                                def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent()
267 //                                                if(eKey.equals("configuration.configuration-type")){
268 //                                                    jObj.put("resourceType", eValue)
269 //                                                }
270 //                                            }
271 //                                        }
272 //                                        utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled)
273 //                                        jArray.put(jObj)
274 //                                    }
275 //                                // for SP-Partner
276 //                                }else if (e.equals("sp-partner")){
277 //                                                                      
278 //                                                              }                                                               
279 //                            }
280 //                        }
281 //                        execution.setVariable("serviceRelationShip", jArray.toString())
282                     }
283                 }
284             }else{
285                 boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator")
286                 if(!succInAAI){
287                     utils.log("INFO","Error getting Service-instance from AAI", + serviceInstanceId, isDebugEnabled)
288                     WorkflowException workflowException = execution.getVariable("WorkflowException")
289                     utils.logAudit("workflowException: " + workflowException)
290                     if(workflowException != null){
291                         exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage())
292                     }
293                     else
294                     {
295                         msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI
296                         utils.log("INFO", msg, isDebugEnabled)
297                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
298                     }
299                 }
300
301                 utils.log("INFO","Service-instance NOT found in AAI. Silent Success", isDebugEnabled)
302             }
303         }catch (BpmnError e) {
304             throw e;
305         } catch (Exception ex) {
306             msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage()
307             utils.log("INFO", msg, isDebugEnabled)
308             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
309         }
310         utils.log("INFO"," *** Exit postProcessAAIGET *** ", isDebugEnabled)
311     }
312         
313         private JSONObject getRelationShipData(node, isDebugEnabled){
314                 JSONObject jObj = new JSONObject()
315                 
316                 def relation  = utils.nodeToString(node)
317                 def rt  = utils.getNodeText1(relation, "related-to")
318                 
319                 def rl  = utils.getNodeText1(relation, "related-link")
320                 utils.log("INFO", "ServiceInstance Related NS/Configuration :" + rl, isDebugEnabled)
321                 
322                 def rl_datas = utils.getIdenticalChildren(node, "relationship-data")
323                 for(def rl_data : rl_datas) {
324                         def eKey =  utils.getChildNodeText(rl_data, "relationship-key")
325                         def eValue = utils.getChildNodeText(rl_data, "relationship-value")
326
327                         if ((rt == "service-instance" && eKey.equals("service-instance.service-instance-id"))
328                         //for overlay/underlay
329                         || (rt == "configuration" && eKey.equals("configuration.configuration-id")
330                         )){
331                                 jObj.put("resourceInstanceId", eValue)
332                         }
333                         // for sp-partner and others
334                         else if(eKey.equals(rt + ".id")){                               
335                                 jObj.put("resourceInstanceId", eValue)
336                                 String resourceName = rt + eValue;
337                                 jObj.put("resourceType", resourceName)
338                         }
339                         else if(eKey.equals(rt + ".id")){                               
340                                 jObj.put("resourceInstanceId", eValue)
341                                 String resourceName = rt + eValue;
342                                 jObj.put("resourceType", resourceName)
343                         }
344                 }
345
346                 def rl_props = utils.getIdenticalChildren(node, "related-to-property")
347                 for(def rl_prop : rl_props) {
348                         def eKey =  utils.getChildNodeText(rl_prop, "property-key")
349                         def eValue = utils.getChildNodeText(rl_prop, "property-value")
350                         if((rt == "service-instance" && eKey.equals("service-instance.service-instance-name"))
351                         //for overlay/underlay
352                         || (rt == "configuration" && eKey.equals("configuration.configuration-type"))){
353                                 jObj.put("resourceType", eValue)
354                         }
355                 }
356
357                 utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled)
358
359                 return jObj
360         }
361
362    public void getCurrentNS(DelegateExecution execution){
363        def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
364        utils.log("INFO", "======== Start getCurrentNS Process ======== ", isDebugEnabled)
365
366        def currentIndex = execution.getVariable("currentNSIndex")
367        List<String> nsSequence = execution.getVariable("nsSequence")
368        String nsResourceType =  nsSequence.get(currentIndex)
369
370        // GET AAI by Name, not ID, for process convenient
371        execution.setVariable("GENGS_type", "service-instance")
372        execution.setVariable("GENGS_serviceInstanceId", "")
373        execution.setVariable("GENGS_serviceInstanceName", nsResourceType)
374
375        utils.log("INFO", "======== COMPLETED getCurrentNS Process ======== ", isDebugEnabled)
376    }
377
378     public void prepareDecomposeService(DelegateExecution execution) {
379         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
380
381         try {
382             utils.log("DEBUG", " ***** Inside prepareDecomposeService of create generic e2e service ***** ", isDebugEnabled)
383             String modelInvariantUuid = execution.getVariable("model-invariant-id-original")
384             String modelVersionId = execution.getVariable("model-version-id-original")
385
386             String serviceModelInfo = """{
387             "modelInvariantUuid":"${modelInvariantUuid}",
388             "modelUuid":"${modelVersionId}",
389             "modelVersion":""
390              }"""
391             execution.setVariable("serviceModelInfo", serviceModelInfo)
392
393             utils.log("DEBUG", " ***** Completed prepareDecomposeService of  create generic e2e service ***** ", isDebugEnabled)
394         } catch (Exception ex) {
395             // try error in method block
396             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage()
397             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
398         }
399     }
400
401     public void postDecomposeService(DelegateExecution execution) {
402         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
403
404         utils.log("DEBUG", " ***** Inside processDecomposition() of  delete generic e2e service flow ***** ", isDebugEnabled)
405         try {
406             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
407
408             // service model info
409             execution.setVariable("serviceModelInfo", serviceDecomposition.getModelInfo())
410
411             List<Resource> deleteResourceList = serviceDecomposition.getServiceResources()
412             String serviceRelationShip = execution.getVariable("serviceRelationShip")
413             def jsonSlurper = new JsonSlurper()
414             def jsonOutput = new JsonOutput()
415
416             List relationShipList = null
417             if (serviceRelationShip != null) {
418                 relationShipList = jsonSlurper.parseText(serviceRelationShip)
419             }
420                         
421             List<Resource> deleteRealResourceList = new ArrayList<Resource>();
422
423             //Set the real resource instance id to the decomosed resource list
424             for (Resource resource: deleteResourceList) {
425                 //reset the resource instance id , because in the decompose flow ,its a random one.
426                 resource.setResourceId("");
427                 //match the resource-instance-name and the model name
428                 if (relationShipList != null) {
429                     relationShipList.each {
430                         if (StringUtils.containsIgnoreCase(it.resourceType, resource.getModelInfo().getModelName())) {
431                             resource.setResourceId(it.resourceInstanceId)
432                             deleteRealResourceList.add(resource)
433                         }
434                     }
435                 }
436             }
437                         
438             // only delete real existing resources
439             execution.setVariable("deleteResourceList", deleteRealResourceList)
440                         
441             utils.log("DEBUG", "delete resource list : " + deleteRealResourceList, isDebugEnabled)
442         } catch (Exception ex) {
443             String exceptionMessage = "Bpmn error encountered in  create generic e2e service flow. processDecomposition() - " + ex.getMessage()
444             utils.log("DEBUG", exceptionMessage, isDebugEnabled)
445             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
446         }
447         utils.log("DEBUG", " ***** exit processDecomposition() of  delete generic e2e service flow ***** ", isDebugEnabled)
448     }
449
450     public void preInitResourcesOperStatus(DelegateExecution execution){
451         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
452
453         utils.log("INFO", " ======== STARTED preInitResourcesOperStatus Process ======== ", isDebugEnabled)
454         try{
455             String serviceId = execution.getVariable("serviceInstanceId")
456             String operationId = execution.getVariable("operationId")
457             String operationType = execution.getVariable("operationType")
458             String resourceTemplateUUIDs = ""
459             String result = "processing"
460             String progress = "0"
461             String reason = ""
462             String operationContent = "Prepare service creation"
463             utils.log("INFO", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType, isDebugEnabled)
464             serviceId = UriUtils.encode(serviceId,"UTF-8")
465             execution.setVariable("serviceInstanceId", serviceId)
466             execution.setVariable("operationId", operationId)
467             execution.setVariable("operationType", operationType)
468             List<Resource> deleteResourceList = execution.getVariable("deleteResourceList")
469
470             String serviceRelationShip = execution.getVariable("serviceRelationShip")
471             for(Resource resource : deleteResourceList){
472                     resourceTemplateUUIDs  = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":"
473             }
474
475
476             execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter")
477
478             String payload =
479                     """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
480                         xmlns:ns="http://org.onap.so/requestsdb">
481                         <soapenv:Header/>
482                         <soapenv:Body>
483                             <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb">
484                             <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId>
485                             <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
486                             <operationType>${MsoUtils.xmlEscape(operationType)}</operationType>
487                             <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs>
488                         </ns:initResourceOperationStatus>
489                     </soapenv:Body>
490                 </soapenv:Envelope>"""
491
492             payload = utils.formatXml(payload)
493             execution.setVariable("CVFMI_initResOperStatusRequest", payload)
494             utils.log("INFO", "Outgoing initResourceOperationStatus: \n" + payload, isDebugEnabled)
495             utils.logAudit("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload)
496
497         }catch(Exception e){
498             utils.log("ERROR", "Exception Occured Processing preInitResourcesOperStatus. Exception is:\n" + e, isDebugEnabled)
499             execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage())
500         }
501         utils.log("INFO", "======== COMPLETED preInitResourcesOperStatus Process ======== ", isDebugEnabled)
502     }
503
504      /**
505       * post config request.
506       */
507      public void postConfigRequest(execution){
508          //to do
509      }
510
511 }