aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy
blob: 6a31095920333c3b20a3469417c3e0b2b8bf4317 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.onap.so.bpmn.infrastructure.scripts

import org.onap.so.bpmn.common.scripts.CatalogDbUtilsFactory

import static org.apache.commons.lang3.StringUtils.isBlank

import org.apache.commons.lang3.StringUtils
import org.apache.http.HttpResponse
import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.delegate.DelegateExecution
import org.json.JSONObject
import org.onap.so.bpmn.common.recipe.BpmnRestClient
import org.onap.so.bpmn.common.recipe.ResourceInput
import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
import org.onap.so.bpmn.common.scripts.CatalogDbUtils
import org.onap.so.bpmn.common.scripts.ExceptionUtil
import org.onap.so.bpmn.common.scripts.MsoUtils
import org.onap.so.bpmn.core.domain.AllottedResource
import org.onap.so.bpmn.core.domain.NetworkResource
import org.onap.so.bpmn.core.domain.Resource
import org.onap.so.bpmn.core.domain.ServiceDecomposition
import org.onap.so.bpmn.core.domain.VnfResource
import org.onap.so.bpmn.core.json.JsonUtils
import org.onap.so.bpmn.core.UrnPropertiesReader
import org.onap.so.bpmn.infrastructure.properties.BPMNProperties
import org.onap.so.logger.MsoLogger

/**
 * input for script :
 * msoRequestId
 * isDebugLogEnabled
 * globalSubscriberId
 * serviceType
 * serviceInstanceId
 * URN_mso_workflow_sdncadapter_callback
 * serviceInputParams
 * deleteResourceList
 * resourceInstanceIDs
 *
 * output from script:
 *
 */

public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor {
	private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteResourcesV1.class);

    String Prefix="DDR_"
    ExceptionUtil exceptionUtil = new ExceptionUtil()
    JsonUtils jsonUtil = new JsonUtils()
    CatalogDbUtils catalogDbUtils = new CatalogDbUtilsFactory().create()

    public void preProcessRequest (DelegateExecution execution) {
        msoLogger.debug(" ***** preProcessRequest *****")
        String msg = ""

        try {
            String requestId = execution.getVariable("msoRequestId")
            execution.setVariable("prefix",Prefix)

            //Inputs
            //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology
            String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId
            if (globalSubscriberId == null) {
                execution.setVariable("globalSubscriberId", "")
            }

            //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology
            String serviceType = execution.getVariable("serviceType")
            if (serviceType == null)
            {
                execution.setVariable("serviceType", "")
            }

            //Generated in parent for AAI PUT
            String serviceInstanceId = execution.getVariable("serviceInstanceId")
            if (isBlank(serviceInstanceId)){
                msg = "Input serviceInstanceId is null"
                msoLogger.error(msg)
                exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
            }

            String sdncCallbackUrl = UrnPropertiesReader.getVariable('URN_mso_workflow_sdncadapter_callback', execution)
            if (isBlank(sdncCallbackUrl)) {
                msg = "URN_mso_workflow_sdncadapter_callback is null"
                msoLogger.error(msg)
                exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
            }
            execution.setVariable("sdncCallbackUrl", sdncCallbackUrl)
            msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl)

            StringBuilder sbParams = new StringBuilder()
            Map<String, String> paramsMap = execution.getVariable("serviceInputParams")
            if (paramsMap != null)
            {
                sbParams.append("<service-input-parameters>")
                for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                    String paramsXml
                    String paramName = entry.getKey()
                    String paramValue = entry.getValue()
                    paramsXml =
                            """	<param>
							<name>${MsoUtils.xmlEscape(paramName)}</name>
							<value>${MsoUtils.xmlEscape(paramValue)}</value>
							</param>
							"""
                    sbParams.append(paramsXml)
                }
                sbParams.append("</service-input-parameters>")
            }
            String siParamsXml = sbParams.toString()
            if (siParamsXml == null)
                siParamsXml = ""
            execution.setVariable("siParamsXml", siParamsXml)

        } catch (BpmnError e) {
            throw e;
        } catch (Exception ex){
            msg = "Exception in preProcessRequest " + ex.getMessage()
            msoLogger.error(msg)
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
        }
        msoLogger.debug(" ***** Exit preProcessRequest *****",)
    }

    public void sequenceResource(DelegateExecution execution){
        msoLogger.debug(" ======== STARTED sequenceResource Process ======== ")
        List<Resource> sequencedResourceList = new ArrayList<Resource>()
        List<Resource> wanResources = new ArrayList<Resource>()

        // get delete resource list and order list
        List<Resource> delResourceList = execution.getVariable("deleteResourceList")

        ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
        String serviceModelName = serviceDecomposition.getModelInfo().getModelName();
        
        def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName)

        if(resourceSequence != null) {
            for (resourceType in resourceSequence.reverse()) {
                for (resource in delResourceList) {
                    if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) {
                        sequencedResourceList.add(resource)

                        if (resource instanceof NetworkResource) {
                            wanResources.add(resource)
                        }
                    }
                }
            }
        }else {
            //define sequenced resource list, we deploy vf first and then network and then ar
            //this is defaule sequence
            List<VnfResource> vnfResourceList = new ArrayList<VnfResource>()
            List<AllottedResource> arResourceList = new ArrayList<AllottedResource>()
            for (Resource rc : delResourceList) {
                if (rc instanceof VnfResource) {
                    vnfResourceList.add(rc)
                } else if (rc instanceof NetworkResource) {
                	wanResources.add(rc)
                } else if (rc instanceof AllottedResource) {
                    arResourceList.add(rc)
                }
            }

            sequencedResourceList.addAll(arResourceList)
            sequencedResourceList.addAll(wanResources)
            sequencedResourceList.addAll(vnfResourceList)
        }

        String isContainsWanResource = wanResources.isEmpty() ? "false" : "true"
        //if no networkResource, get SDNC config from properties file
        if( "false".equals(isContainsWanResource)) {
            String serviceNeedSDNC = "mso.workflow.custom." + serviceModelName + ".sdnc.need";
            isContainsWanResource = BPMNProperties.getProperty(serviceNeedSDNC, isContainsWanResource)
        }
        execution.setVariable("isContainsWanResource", isContainsWanResource)
        execution.setVariable("currentResourceIndex", 0)
        execution.setVariable("sequencedResourceList", sequencedResourceList)
        msoLogger.debug("resourceSequence: " + resourceSequence)
        msoLogger.debug(" ======== END sequenceResource Process ======== ")
    }

    /**
     * prepare delete parameters
     */
    public void preResourceDelete(DelegateExecution execution){
        msoLogger.debug(" ======== STARTED preResourceDelete Process ======== ")

        List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList")

        int currentIndex = execution.getVariable("currentResourceIndex")
        if(sequencedResourceList != null && sequencedResourceList.size() > currentIndex){
            Resource curResource = sequencedResourceList.get(currentIndex);

            String resourceInstanceUUID = curResource.getResourceId()
            String resourceTemplateUUID = curResource.getModelInfo().getModelUuid()
            execution.setVariable("resourceInstanceId", resourceInstanceUUID)
            execution.setVariable("currentResource", curResource)
            msoLogger.debug("Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + "  resourceInstanceId: "
                    + resourceInstanceUUID + " resourceModelName: " + curResource.getModelInfo().getModelName())
        }
        else {
            execution.setVariable("resourceInstanceId", "")
        }

        msoLogger.debug(" ======== END preResourceDelete Process ======== ")
    }


    /**
     * Execute delete workflow for resource
     */
    public void executeResourceDelete(DelegateExecution execution) {
        msoLogger.debug("======== Start executeResourceDelete Process ======== ")
		try {
	        String requestId = execution.getVariable("msoRequestId")
	        String serviceInstanceId = execution.getVariable("serviceInstanceId")
	        String serviceType = execution.getVariable("serviceType")
	
	        String resourceInstanceId = execution.getVariable("resourceInstanceId")
	
	        Resource currentResource = execution.getVariable("currentResource")
	        String action = "deleteInstance"
	        JSONObject resourceRecipe = catalogDbUtils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action)
	        String recipeUri = resourceRecipe.getString("orchestrationUri")
	        int recipeTimeout = resourceRecipe.getInt("recipeTimeout")
	        String recipeParamXsd = resourceRecipe.get("paramXSD")
	
	
	        ResourceInput resourceInput = new ResourceInput();
	        resourceInput.setServiceInstanceId(serviceInstanceId)
	        resourceInput.setResourceInstanceName(currentResource.getResourceInstanceName())
	        resourceInput.setResourceInstancenUuid(currentResource.getResourceId())
	        resourceInput.setOperationId(execution.getVariable("operationId"))
	        resourceInput.setOperationType(execution.getVariable("operationType"))
	        String globalSubscriberId = execution.getVariable("globalSubscriberId") 
	        resourceInput.setGlobalSubscriberId(globalSubscriberId)
	        resourceInput.setResourceModelInfo(currentResource.getModelInfo());
	   	    ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
	   		resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo());
	        resourceInput.setServiceType(serviceType)
	
	        String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + recipeUri
	
	        HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd)
	        msoLogger.debug(" ======== END executeResourceDelete Process ======== ")
		}catch(BpmnError b){
			 msoLogger.error("Rethrowing MSOWorkflowException")
			 throw b
		 }catch(Exception e){
			 msoLogger.error("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e)
			 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog")
		 }
    }


    public void parseNextResource(DelegateExecution execution){
        msoLogger.debug("======== Start parseNextResource Process ======== ")
        def currentIndex = execution.getVariable("currentResourceIndex")
        def nextIndex =  currentIndex + 1
        execution.setVariable("currentResourceIndex", nextIndex)
        List<String> sequencedResourceList = execution.getVariable("sequencedResourceList")
        if(nextIndex >= sequencedResourceList.size()){
            execution.setVariable("allResourceFinished", "true")
        }else{
            execution.setVariable("allResourceFinished", "false")
        }
        msoLogger.debug("======== COMPLETED parseNextResource Process ======== ")
    }
    
    public void prepareFinishedProgressForResource(DelegateExecution execution) {

        String serviceInstanceId = execution.getVariable("serviceInstanceId")
        String serviceType = execution.getVariable("serviceType")
        String resourceInstanceId = execution.getVariable("resourceInstanceId")
        Resource currentResource = execution.getVariable("currentResource")
        String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid()
        String resourceModelName = currentResource.getModelInfo().getModelName()
        String operationType = execution.getVariable("operationType")
        String progress = "100"
        String status = "finished"
        String statusDescription = "The resource instance does not exist for " + resourceModelName
        String operationId = execution.getVariable("operationId")

        String body = """
                <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                        xmlns:ns="http://org.onap.so/requestsdb">
                        <soapenv:Header/>
                <soapenv:Body>
                    <ns:updateResourceOperationStatus>
                               <operType>${MsoUtils.xmlEscape(operationType)}</operType>
                               <operationId>${MsoUtils.xmlEscape(operationId)}</operationId>
                               <progress>${MsoUtils.xmlEscape(progress)}</progress>
                               <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID>
                               <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId>
                               <status>${MsoUtils.xmlEscape(status)}</status>
                               <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription>
                    </ns:updateResourceOperationStatus>
                </soapenv:Body>
                </soapenv:Envelope>""";

        def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
        execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
        execution.setVariable("CVFMI_updateResOperStatusRequest", body)
    }

    public void prepareSDNCServiceDeactivateRequest (DelegateExecution execution) {
    	prepareSDNCServiceRequest (execution, "deactivate")
    }
    
    public void prepareSDNCServiceDeleteRequest (DelegateExecution execution) {
    	prepareSDNCServiceRequest (execution, "delete")
    }
    
    public void prepareSDNCServiceRequest (DelegateExecution execution, String svcAction) {
        msoLogger.debug(" ***** Started prepareSDNCServiceRequest for " + svcAction +  "*****")

        try {
            // get variables
            String sdnc_svcAction = svcAction        
            String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback")            
            String hdrRequestId = execution.getVariable("msoRequestId")
            String serviceInstanceId = execution.getVariable("serviceInstanceId")
            String source = execution.getVariable("source")
            String sdnc_service_id = serviceInstanceId
            ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition")
            String serviceType = execution.getVariable("serviceType")
            String globalCustomerId = execution.getVariable("globalSubscriberId")
            String serviceModelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid()
            String serviceModelUuid = serviceDecomposition.getModelInfo().getModelUuid()
            String serviceModelVersion = serviceDecomposition.getModelInfo().getModelVersion()
            String serviceModelName = serviceDecomposition.getModelInfo().getModelName()

            // 1. prepare assign topology via SDNC Adapter SUBFLOW call
            String sndcTopologyDeleteRequest =
                    """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
                                                              xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" 
                                                              xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1">
                                 <sdncadapter:RequestHeader>
                                    <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId>
                                    <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId>
                                    <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction>
                                    <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation>
                                    <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl>
                                    <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction>
                                 </sdncadapter:RequestHeader>
                                 <sdncadapterworkflow:SDNCRequestData>
                                     <request-information>
                                        <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id>
                                        <request-action>DeleteServiceInstance</request-action>
                                        <source>${MsoUtils.xmlEscape(source)}</source>
                                        <notification-url></notification-url>
                                        <order-number></order-number>
                                        <order-version></order-version>
                                     </request-information>
                                     <service-information>
                                        <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id>
                                        <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type>
                                        <onap-model-information>
                                             <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid>
                                             <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid>
                                             <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version>
                                             <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name>
                                        </onap-model-information>
                                        <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id>
                                        <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id>
                                     </service-information>
                                     <service-request-input>
                                     </service-request-input>
                                </sdncadapterworkflow:SDNCRequestData>
                             </aetgt:SDNCAdapterWorkflowRequest>""".trim()
            
            String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest)
            msoLogger.debug(sndcTopologyDeleteRequesAsString)
            execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString)
            msoLogger.debug("sdncAdapterWorkflowRequest - " + "\n" +  sndcTopologyDeleteRequesAsString)

        } catch (Exception ex) {
            String exceptionMessage = " Bpmn error encountered in DoDeleteResourcesV1 flow. prepareSDNCServiceRequest() - " + ex.getMessage()
            msoLogger.debug(exceptionMessage)
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)

        }
       msoLogger.debug("***** Exit prepareSDNCServiceRequest for " + svcAction +  "*****")
	}
}