616c654a6ef980377c843a11b2baa39878016b21
[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('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             BpmnRestClient bpmnRestClient = new BpmnRestClient()
269
270             HttpResponse resp = bpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd)
271             logger.debug(" ======== END executeResourceDelete Process ======== ")
272         } catch (BpmnError b) {
273             logger.error("Rethrowing MSOWorkflowException")
274             throw b
275         } catch (Exception e) {
276             logger.error("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e)
277             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog")
278         }
279     }
280
281
282     public void parseNextResource(DelegateExecution execution){
283         logger.debug("======== Start parseNextResource Process ======== ")
284         def currentIndex = execution.getVariable("currentResourceIndex")
285         def nextIndex =  currentIndex + 1
286         execution.setVariable("currentResourceIndex", nextIndex)
287         List<String> sequencedResourceList = execution.getVariable("sequencedResourceList")
288         if(nextIndex >= sequencedResourceList.size()){
289             execution.setVariable("allResourceFinished", "true")
290         }else{
291             execution.setVariable("allResourceFinished", "false")
292         }
293         logger.debug("======== COMPLETED parseNextResource Process ======== ")
294     }
295     
296     public void prepareFinishedProgressForResource(DelegateExecution execution) {
297
298         String serviceInstanceId = execution.getVariable("serviceInstanceId")
299         String serviceType = execution.getVariable("serviceType")
300         String resourceInstanceId = execution.getVariable("resourceInstanceId")
301         Resource currentResource = execution.getVariable("currentResource")
302         String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid()
303         String resourceModelName = currentResource.getModelInfo().getModelName()
304         String operationType = execution.getVariable("operationType")
305         String progress = "100"
306         String status = "finished"
307         String statusDescription = "The resource instance does not exist for " + resourceModelName
308         String operationId = execution.getVariable("operationId")
309
310         String body = """
311                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
312                         xmlns:ns="http://org.onap.so/requestsdb">
313                         <soapenv:Header/>
314                 <soapenv:Body>
315                     <ns:updateResourceOperationStatus>
316                                <operType>${MsoUtils.xmlEscape(operationType)}</operType>
317                                <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
318                                <progress>${MsoUtils.xmlEscape(progress)}</progress>
319                                <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID>
320                                <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId>
321                                <status>${MsoUtils.xmlEscape(status)}</status>
322                                <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription>
323                     </ns:updateResourceOperationStatus>
324                 </soapenv:Body>
325                 </soapenv:Envelope>""";
326
327         def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
328         execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
329         execution.setVariable("CVFMI_updateResOperStatusRequest", body)
330     }
331
332     public void prepareSDNCServiceDeactivateRequest (DelegateExecution execution) {
333         prepareSDNCServiceRequest (execution, "deactivate")
334     }
335     
336     public void prepareSDNCServiceDeleteRequest (DelegateExecution execution) {
337         prepareSDNCServiceRequest (execution, "delete")
338     }
339     
340     public void prepareSDNCServiceRequest (DelegateExecution execution, String svcAction) {
341         logger.debug(" ***** Started prepareSDNCServiceRequest for " + svcAction +  "*****")
342
343         try {
344             // get variables
345             String sdnc_svcAction = svcAction        
346             String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")            
347             String hdrRequestId = execution.getVariable("msoRequestId")
348             String serviceInstanceId = execution.getVariable("serviceInstanceId")
349             String source = execution.getVariable("source")
350             String sdnc_service_id = serviceInstanceId
351             ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
352             String serviceType = execution.getVariable("serviceType")
353             String globalCustomerId = execution.getVariable("globalSubscriberId")
354             String serviceModelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
355             String serviceModelUuid = serviceDecomposition.getModelInfo().getModelUuid()
356             String serviceModelVersion = serviceDecomposition.getModelInfo().getModelVersion()
357             String serviceModelName = serviceDecomposition.getModelInfo().getModelName()
358
359             // 1. prepare assign topology via SDNC Adapter SUBFLOW call
360             String sndcTopologyDeleteRequest =
361                     """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
362                                                               xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" 
363                                                               xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
364                                  <sdncadapter:RequestHeader>
365                                     <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
366                                     <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
367                                     <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction>
368                                     <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
369                                     <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
370                                     <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
371                                  </sdncadapter:RequestHeader>
372                                  <sdncadapterworkflow:SDNCRequestData>
373                                      <request-information>
374                                         <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id>
375                                         <request-action>DeleteServiceInstance</request-action>
376                                         <source>${MsoUtils.xmlEscape(source)}</source>
377                                         <notification-url></notification-url>
378                                         <order-number></order-number>
379                                         <order-version></order-version>
380                                      </request-information>
381                                      <service-information>
382                                         <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id>
383                                         <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type>
384                                         <onap-model-information>
385                                              <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid>
386                                              <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid>
387                                              <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version>
388                                              <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name>
389                                         </onap-model-information>
390                                         <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
391                                         <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id>
392                                      </service-information>
393                                      <service-request-input>
394                                      </service-request-input>
395                                 </sdncadapterworkflow:SDNCRequestData>
396                              </aetgt:SDNCAdapterWorkflowRequest>""".trim()
397             
398             String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest)
399             logger.debug(sndcTopologyDeleteRequesAsString)
400             execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString)
401             logger.debug("sdncAdapterWorkflowRequest - " + "\n" +  sndcTopologyDeleteRequesAsString)
402
403         } catch (Exception ex) {
404             String exceptionMessage = " Bpmn error encountered in DoDeleteResourcesV1 flow. prepareSDNCServiceRequest() - " + ex.getMessage()
405             logger.debug(exceptionMessage)
406             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
407
408         }
409        logger.debug("***** Exit prepareSDNCServiceRequest for " + svcAction +  "*****")
410         }
411 }