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