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