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