Get Csar file bug fix
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteResourcesV1.groovy
1
2 /*-
3  * ============LICENSE_START=======================================================
4  * ONAP - SO
5  * ================================================================================
6  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import static org.apache.commons.lang3.StringUtils.isBlank
24
25 import org.apache.commons.lang3.StringUtils
26 import org.apache.http.HttpResponse
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.json.JSONObject
30 import org.onap.so.bpmn.common.recipe.BpmnRestClient
31 import org.onap.so.bpmn.common.recipe.ResourceInput
32 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
33 import org.onap.so.bpmn.common.scripts.CatalogDbUtils
34 import org.onap.so.bpmn.common.scripts.ExceptionUtil
35 import org.onap.so.bpmn.common.scripts.MsoUtils
36 import org.onap.so.bpmn.core.domain.AllottedResource
37 import org.onap.so.bpmn.core.domain.NetworkResource
38 import org.onap.so.bpmn.core.domain.Resource
39 import org.onap.so.bpmn.core.domain.ServiceDecomposition
40 import org.onap.so.bpmn.core.domain.VnfResource
41 import org.onap.so.bpmn.core.json.JsonUtils
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43 import org.onap.so.bpmn.infrastructure.properties.BPMNProperties
44 import org.onap.so.logger.MsoLogger
45
46 /**
47  * input for script :
48  * msoRequestId
49  * isDebugLogEnabled
50  * globalSubscriberId
51  * serviceType
52  * serviceInstanceId
53  * URN_mso_workflow_sdncadapter_callback
54  * serviceInputParams
55  * deleteResourceList
56  * resourceInstanceIDs
57  *
58  * output from script:
59  *
60  */
61
62 public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor {
63         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteResourcesV1.class);
64
65     String Prefix="DDR_"
66     ExceptionUtil exceptionUtil = new ExceptionUtil()
67     JsonUtils jsonUtil = new JsonUtils()
68     CatalogDbUtils cutils = new CatalogDbUtils()
69
70     public void preProcessRequest (DelegateExecution execution) {
71         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
72         utils.log("INFO"," ***** preProcessRequest *****",  isDebugEnabled)
73         String msg = ""
74
75         try {
76             String requestId = execution.getVariable("msoRequestId")
77             execution.setVariable("prefix",Prefix)
78
79             //Inputs
80             //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
81             String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
82             if (globalSubscriberId == null)
83             {
84                 execution.setVariable("globalSubscriberId", "")
85             }
86
87             //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
88             String serviceType = execution.getVariable("serviceType")
89             if (serviceType == null)
90             {
91                 execution.setVariable("serviceType", "")
92             }
93
94             //Generated in parent for AAI PUT
95             String serviceInstanceId = execution.getVariable("serviceInstanceId")
96             if (isBlank(serviceInstanceId)){
97                 msg = "Input serviceInstanceId is null"
98                 utils.log("INFO", msg, isDebugEnabled)
99                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
100             }
101
102             String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback')
103             if (isBlank(sdncCallbackUrl)) {
104                 msg = "URN_mso_workflow_sdncadapter_callback is null"
105                 utils.log("INFO", msg, isDebugEnabled)
106                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
107             }
108             execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
109             utils.log("INFO","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled)
110
111             StringBuilder sbParams = new StringBuilder()
112             Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
113             if (paramsMap != null)
114             {
115                 sbParams.append("<service-input-parameters>")
116                 for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
117                     String paramsXml
118                     String paramName = entry.getKey()
119                     String paramValue = entry.getValue()
120                     paramsXml =
121                             """ <param>
122                                                         <name>${MsoUtils.xmlEscape(paramName)}</name>
123                                                         <value>${MsoUtils.xmlEscape(paramValue)}</value>
124                                                         </param>
125                                                         """
126                     sbParams.append(paramsXml)
127                 }
128                 sbParams.append("</service-input-parameters>")
129             }
130             String siParamsXml = sbParams.toString()
131             if (siParamsXml == null)
132                 siParamsXml = ""
133             execution.setVariable("siParamsXml", siParamsXml)
134
135         } catch (BpmnError e) {
136             throw e;
137         } catch (Exception ex){
138             msg = "Exception in preProcessRequest " + ex.getMessage()
139             utils.log("INFO", msg, isDebugEnabled)
140             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
141         }
142         utils.log("INFO"," ***** Exit preProcessRequest *****",  isDebugEnabled)
143     }
144
145     public void sequenceResource(DelegateExecution execution){
146         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
147
148         utils.log("INFO", " ======== STARTED sequenceResource Process ======== ", isDebugEnabled)
149         List<Resource> sequencedResourceList = new ArrayList<Resource>()
150         List<Resource> wanResources = new ArrayList<Resource>()
151
152         // get delete resource list and order list
153         List<Resource> delResourceList = execution.getVariable("deleteResourceList")
154
155         ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
156         String serviceModelName = serviceDecomposition.getModelInfo().getModelName();
157         
158         def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName)
159
160         if(resourceSequence != null) {
161             for (resourceType in resourceSequence.reverse()) {
162                 for (resource in delResourceList) {
163                     if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) {
164                         sequencedResourceList.add(resource)
165
166                         if (resource instanceof NetworkResource) {
167                             wanResources.add(resource)
168                         }
169                     }
170                 }
171             }
172         }else {
173             //define sequenced resource list, we deploy vf first and then network and then ar
174             //this is defaule sequence
175             List<VnfResource> vnfResourceList = new ArrayList<VnfResource>()
176             List<AllottedResource> arResourceList = new ArrayList<AllottedResource>()
177             for (Resource rc : delResourceList) {
178                 if (rc instanceof VnfResource) {
179                     vnfResourceList.add(rc)
180                 } else if (rc instanceof NetworkResource) {
181                         wanResources.add(rc)
182                 } else if (rc instanceof AllottedResource) {
183                     arResourceList.add(rc)
184                 }
185             }
186
187             sequencedResourceList.addAll(arResourceList)
188             sequencedResourceList.addAll(wanResources)
189             sequencedResourceList.addAll(vnfResourceList)
190         }
191
192         String isContainsWanResource = wanResources.isEmpty() ? "false" : "true"
193         //if no networkResource, get SDNC config from properties file
194         if( "false".equals(isContainsWanResource)) {
195             String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need";
196             isContainsWanResource = BPMNProperties.getProperty(serviceNeedSDNC, isContainsWanResource)
197         }
198         execution.setVariable("isContainsWanResource", isContainsWanResource)
199         execution.setVariable("currentResourceIndex", 0)
200         execution.setVariable("sequencedResourceList", sequencedResourceList)
201         utils.log("INFO", "resourceSequence: " + resourceSequence, isDebugEnabled)
202         utils.log("INFO", " ======== END sequenceResource Process ======== ", isDebugEnabled)
203     }
204
205     /**
206      * prepare delete parameters
207      */
208     public void preResourceDelete(DelegateExecution execution){
209
210         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
211
212         utils.log("INFO", " ======== STARTED preResourceDelete Process ======== ", isDebugEnabled)
213
214         List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")
215
216         int currentIndex = execution.getVariable("currentResourceIndex")
217         if(sequencedResourceList != null && sequencedResourceList.size() > currentIndex){
218             Resource curResource = sequencedResourceList.get(currentIndex);
219
220             String resourceInstanceUUID = curResource.getResourceId()
221             String resourceTemplateUUID = curResource.getModelInfo().getModelUuid()
222             execution.setVariable("resourceInstanceId", resourceInstanceUUID)
223             execution.setVariable("currentResource", curResource)
224             utils.log("INFO", "Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + "  resourceInstanceId: "
225                     + resourceInstanceUUID + " resourceModelName: " + curResource.getModelInfo().getModelName(), isDebugEnabled)
226         }
227         else {
228             execution.setVariable("resourceInstanceId", "")
229         }
230
231         utils.log("INFO", " ======== END preResourceDelete Process ======== ", isDebugEnabled)
232     }
233
234
235     /**
236      * Execute delete workflow for resource
237      */
238     public void executeResourceDelete(DelegateExecution execution) {
239         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
240         utils.log("INFO", "======== Start executeResourceDelete Process ======== ", isDebugEnabled)
241                 try {
242                 String requestId = execution.getVariable("msoRequestId")
243                 String serviceInstanceId = execution.getVariable("serviceInstanceId")
244                 String serviceType = execution.getVariable("serviceType")
245         
246                 String resourceInstanceId = execution.getVariable("resourceInstanceId")
247         
248                 Resource currentResource = execution.getVariable("currentResource")
249                 String action = "deleteInstance"
250                 JSONObject resourceRecipe = cutils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action)
251                 String recipeUri = resourceRecipe.getString("orchestrationUri")
252                 int recipeTimeout = resourceRecipe.getInt("recipeTimeout")
253                 String recipeParamXsd = resourceRecipe.get("paramXSD")
254         
255         
256                 ResourceInput resourceInput = new ResourceInput();
257                 resourceInput.setServiceInstanceId(serviceInstanceId)
258                 resourceInput.setResourceInstanceName(currentResource.getResourceInstanceName())
259                 resourceInput.setResourceInstancenUuid(currentResource.getResourceId())
260                 resourceInput.setOperationId(execution.getVariable("operationId"))
261                 resourceInput.setOperationType(execution.getVariable("operationType"))
262                 String globalSubscriberId = execution.getVariable("globalSubscriberId") 
263                 resourceInput.setGlobalSubscriberId(globalSubscriberId)
264                 resourceInput.setResourceModelInfo(currentResource.getModelInfo());
265                     ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
266                         resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo());
267                 resourceInput.setServiceType(serviceType)
268         
269                 String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + recipeUri
270         
271                 HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd)
272                 utils.log("INFO", " ======== END executeResourceDelete Process ======== ", isDebugEnabled)
273                 }catch(BpmnError b){
274                          msoLogger.debug("Rethrowing MSOWorkflowException")
275                          throw b
276                  }catch(Exception e){
277                          msoLogger.debug("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e)
278                          exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog")
279                  }
280     }
281
282
283     public void parseNextResource(DelegateExecution execution){
284         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
285         utils.log("INFO", "======== Start parseNextResource Process ======== ", isDebugEnabled)
286         def currentIndex = execution.getVariable("currentResourceIndex")
287         def nextIndex =  currentIndex + 1
288         execution.setVariable("currentResourceIndex", nextIndex)
289         List<String> sequencedResourceList = execution.getVariable("sequencedResourceList")
290         if(nextIndex >= sequencedResourceList.size()){
291             execution.setVariable("allResourceFinished", "true")
292         }else{
293             execution.setVariable("allResourceFinished", "false")
294         }
295         utils.log("INFO", "======== COMPLETED parseNextResource Process ======== ", isDebugEnabled)
296     }
297     
298     public void prepareFinishedProgressForResource(DelegateExecution execution) {
299
300         String serviceInstanceId = execution.getVariable("serviceInstanceId")
301         String serviceType = execution.getVariable("serviceType")
302         String resourceInstanceId = execution.getVariable("resourceInstanceId")
303         Resource currentResource = execution.getVariable("currentResource")
304         String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid()
305         String resourceModelName = currentResource.getModelInfo().getModelName()
306         String operationType = execution.getVariable("operationType")
307         String progress = "100"
308         String status = "finished"
309         String statusDescription = "The resource instance does not exist for " + resourceModelName
310         String operationId = execution.getVariable("operationId")
311
312         String body = """
313                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
314                         xmlns:ns="http://org.onap.so/requestsdb">
315                         <soapenv:Header/>
316                 <soapenv:Body>
317                     <ns:updateResourceOperationStatus>
318                                <operType>${MsoUtils.xmlEscape(operationType)}</operType>
319                                <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
320                                <progress>${MsoUtils.xmlEscape(progress)}</progress>
321                                <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID>
322                                <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId>
323                                <status>${MsoUtils.xmlEscape(status)}</status>
324                                <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription>
325                     </ns:updateResourceOperationStatus>
326                 </soapenv:Body>
327                 </soapenv:Envelope>""";
328
329         def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
330         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
331         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
332     }
333
334     public void prepareSDNCServiceDeactivateRequest (DelegateExecution execution) {
335         prepareSDNCServiceRequest (execution, "deactivate")
336     }
337     
338     public void prepareSDNCServiceDeleteRequest (DelegateExecution execution) {
339         prepareSDNCServiceRequest (execution, "delete")
340     }
341     
342     public void prepareSDNCServiceRequest (DelegateExecution execution, String svcAction) {
343         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
344         utils.log("INFO"," ***** Started prepareSDNCServiceRequest for " + svcAction +  "*****",  isDebugEnabled)
345
346         try {
347             // get variables
348             String sdnc_svcAction = svcAction        
349             String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")            
350             String hdrRequestId = execution.getVariable("msoRequestId")
351             String serviceInstanceId = execution.getVariable("serviceInstanceId")
352             String source = execution.getVariable("source")
353             String sdnc_service_id = serviceInstanceId
354             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
355             String serviceType = execution.getVariable("serviceType")
356             String globalCustomerId = execution.getVariable("globalSubscriberId")
357             String serviceModelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
358             String serviceModelUuid = serviceDecomposition.getModelInfo().getModelUuid()
359             String serviceModelVersion = serviceDecomposition.getModelInfo().getModelVersion()
360             String serviceModelName = serviceDecomposition.getModelInfo().getModelName()
361
362             // 1. prepare assign topology via SDNC Adapter SUBFLOW call
363             String sndcTopologyDeleteRequest =
364                     """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
365                                                               xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" 
366                                                               xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
367                                  <sdncadapter:RequestHeader>
368                                     <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
369                                     <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
370                                     <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction>
371                                     <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
372                                     <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
373                                     <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
374                                  </sdncadapter:RequestHeader>
375                                  <sdncadapterworkflow:SDNCRequestData>
376                                      <request-information>
377                                         <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id>
378                                         <request-action>DeleteServiceInstance</request-action>
379                                         <source>${MsoUtils.xmlEscape(source)}</source>
380                                         <notification-url></notification-url>
381                                         <order-number></order-number>
382                                         <order-version></order-version>
383                                      </request-information>
384                                      <service-information>
385                                         <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id>
386                                         <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type>
387                                         <onap-model-information>
388                                              <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid>
389                                              <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid>
390                                              <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version>
391                                              <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name>
392                                         </onap-model-information>
393                                         <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
394                                         <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id>
395                                      </service-information>
396                                      <service-request-input>
397                                      </service-request-input>
398                                 </sdncadapterworkflow:SDNCRequestData>
399                              </aetgt:SDNCAdapterWorkflowRequest>""".trim()
400             
401             String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest)
402             utils.logAudit(sndcTopologyDeleteRequesAsString)
403             execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString)
404             utils.log("INFO","sdncAdapterWorkflowRequest - " + "\n" +  sndcTopologyDeleteRequesAsString, isDebugEnabled)
405
406         } catch (Exception ex) {
407             String exceptionMessage = " Bpmn error encountered in DoDeleteResourcesV1 flow. prepareSDNCServiceRequest() - " + ex.getMessage()
408             utils.log("DEBUG", exceptionMessage, isDebugEnabled)
409             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
410
411         }
412        utils.log("INFO","***** Exit prepareSDNCServiceRequest for " + svcAction +  "*****",  isDebugEnabled)
413         }
414 }