aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteSliceService.groovy
blob: 5fd06fd8d42db94a2a6009572718dcf7f07aa80a (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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 # Copyright (c) 2019, CMCC Technologies Co., Ltd.
 #
 # 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.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.delegate.DelegateExecution
import org.onap.aai.domain.yang.AllottedResource
import org.onap.aai.domain.yang.AllottedResources
import org.onap.aai.domain.yang.Relationship
import org.onap.aai.domain.yang.ServiceInstance
import org.onap.aaiclient.client.aai.AAIObjectName
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
import org.onap.logging.filter.base.ONAPComponents
import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
import org.onap.so.bpmn.common.scripts.ExceptionUtil
import org.onap.so.bpmn.common.scripts.OofUtils
import org.onap.so.bpmn.core.UrnPropertiesReader
import org.onap.so.client.HttpClient
import org.onap.so.client.HttpClientFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.ws.rs.NotFoundException
import javax.ws.rs.core.Response

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

/**
 * This groovy class supports the <class>DoDeleteSliceService.bpmn</class> process.
 *
 * Inputs:
 * @param - msoRequestId
 * @param - globalSubscriberId - O
 * @param - subscriptionServiceType - O
 * @param - serviceInstanceId
 *
 */
class DoDeleteSliceService extends AbstractServiceTaskProcessor {
    private final String PREFIX ="DoDeleteSliceService"
    ExceptionUtil exceptionUtil = new ExceptionUtil()
    OofUtils oofUtils = new OofUtils()
    private static final Logger LOGGER = LoggerFactory.getLogger( DoDeleteSliceService.class)

    @Override
    void preProcessRequest(DelegateExecution execution) {
        LOGGER.debug(" *****${PREFIX} preProcessRequest *****")
        String msg = ""

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

            //Inputs
            //requestDetails.subscriberInfo. for AAI GET & PUT
             execution.getVariable("globalSubscriberId") ?: execution.setVariable("globalSubscriberId", "")

            //requestDetails.requestParameters. for AAI PUT
            execution.getVariable("serviceType") ?: execution.setVariable("serviceType", "")

            //Generated in parent for AAI PUT
            String serviceInstanceId = execution.getVariable("serviceInstanceId")
            if (isBlank(serviceInstanceId)){
                msg = "Input serviceInstanceId is null"
                LOGGER.info(msg)
                exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
            }
        } catch (BpmnError e) {
            throw e
        } catch (Exception ex){
            msg = "Exception in preProcessRequest " + ex.getMessage()
            LOGGER.error(msg)
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
        }
        LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
    }

    /**
     * query E2ESliceService from AAI
     * save snssai
     * @param execution
     */
    void queryServiceProfileFromAAI(DelegateExecution execution)
    {
        LOGGER.trace(" *****${PREFIX} Start queryE2ESliceSeriveFromAAI *****")
        String serviceInstanceId = execution.getVariable("serviceInstanceId")
        try
        {
        String errorMsg = "query e2e slice service from aai failed"
        AAIResultWrapper wrapper = queryAAI(execution, Types.SERVICE_INSTANCE, serviceInstanceId, errorMsg)
        Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
        if(si.isPresent())
        {
            String snssai = si.get()?.getEnvironmentContext()
            execution.setVariable("snssai", snssai ?: "")
//            ServiceProfiles serviceProfiles = si.get()?.getServiceProfiles()
//            ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
//            String serviceProfileId = serviceProfile ? serviceProfile.getProfileId() : ""
//            execution.setVariable("serviceProfileId", serviceProfileId)
            List<ServiceInstance> sliceProfileList = []
            List<Relationship> relationshipList = si.get().getRelationshipList().getRelationship()
            for (Relationship relationship : relationshipList) {
                String relatedTo = relationship.getRelatedTo()
                if (relatedTo.toLowerCase() == "service-instance") {
                    String relatioshipurl = relationship.getRelatedLink()
                    String instanceId = relatioshipurl.substring(relatioshipurl.lastIndexOf("/") + 1, relatioshipurl.length())
                    AAIResultWrapper wrapper1 = queryAAI(execution, Types.SERVICE_INSTANCE, instanceId, errorMsg)
                    Optional<ServiceInstance> serviceInstance = wrapper1.asBean(ServiceInstance.class)
                    if (serviceInstance.isPresent()) {
                        ServiceInstance instance = serviceInstance.get()
                        if ("slice-profile".equalsIgnoreCase(instance.getServiceRole())) {
                            sliceProfileList.add(instance)
                        }
                    }
                }
            }
            execution.setVariable("sliceProfileList",sliceProfileList)
            LOGGER.info("serviceInstanceId: ${serviceInstanceId}, snssai: ${snssai}, sliceProfileList: ${sliceProfileList}")
        }
        LOGGER.trace(" *****${PREFIX} Exit queryE2ESliceSeriveFromAAI *****")
        }
        catch (any)
        {
            String msg = "query E2E slice service from aai failed! cause-"+any.getCause()
            LOGGER.error(any.printStackTrace())
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
        }
    }

    /**
     * get allotted resource from AAI
     * save nsi id
     * @param execution
     */
    void getAllottedResFromAAI(DelegateExecution execution)
    {
        LOGGER.trace(" *****${PREFIX} Start getAllottedResFromAAI *****")
        String serviceInstanceId = execution.getVariable("serviceInstanceId")
        try
        {
            String errorMsg = "query allotted resource from aai failed."
            AAIResultWrapper wrapper = queryAAI(execution, Types.ALLOTTED_RESOURCE, serviceInstanceId, errorMsg)
            Optional<AllottedResources> ars = wrapper?.asBean(AllottedResources.class)
            if(ars.isPresent() && ars.get().getAllottedResource())
            {
                List<AllottedResource> allottedResourceList = ars.get().getAllottedResource()
                AllottedResource ar = allottedResourceList.first()
                String relatedLink = ar?.getRelationshipList()?.getRelationship()?.first()?.getRelatedLink()
                String nsiId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
                execution.setVariable("nsiId", nsiId)
                LOGGER.info("serviceInstanceId: ${serviceInstanceId}, nsiId:${nsiId}")
            }
        }
        catch(BpmnError e){
            throw e
        }
        catch (Exception ex){
            String msg = "Exception in getAllottedResFromAAI " + ex.getMessage()
            LOGGER.error(msg)
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
        }
        LOGGER.trace(" *****${PREFIX} Exit getAllottedResFromAAI *****")
    }

    /**
     * get nsi service instance from aai
     * save nssi id
     * @param execution
     */
    void getNSIFromAAI(DelegateExecution execution)
    {
        LOGGER.trace(" *****${PREFIX} Start getNSIFromAAI *****")
        String nsiId = execution.getVariable("nsiId")
        List<String> nssiIdList = getNSSIIdList(execution, nsiId)
        String msg = "nsiId: ${nsiId}, nssiIdList:"
        msg+= nssiIdList.join(",")
        LOGGER.info(msg)
        execution.setVariable("nssiIdList", nssiIdList)
        LOGGER.trace(" *****${PREFIX} Exit getNSIFromAAI *****")
    }
    /**
     * Get NSSI Id from AAI
     * @param execution
     * @param nsiId
     * @return
     */
    private List<String> getNSSIIdList(DelegateExecution execution, String nsiId){
        List<String> nssiIdList = []

        try
        {
            String errorMsg = "query nssi from aai failed."
            AAIResultWrapper wrapper = queryAAI(execution, Types.SERVICE_INSTANCE, nsiId, errorMsg)
            Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
            if(si.isPresent())
            {
                List<Relationship> relationshipList = si.get().getRelationshipList()?.getRelationship()
                for (Relationship relationship : relationshipList)
                {
                    String relatedTo = relationship.getRelatedTo()
                    if (relatedTo == "service-instance")
                    {
                        String relatedLink = relationship.getRelatedLink()?:""
                        String instanceId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
                        AAIResultWrapper wrapper1 = queryAAI(execution, Types.SERVICE_INSTANCE, instanceId, errorMsg)
                        Optional<ServiceInstance> serviceInstance = wrapper1.asBean(ServiceInstance.class)
                        def nssiId
                        if (serviceInstance.isPresent()) {
                            ServiceInstance instance = serviceInstance.get()
                            if ("nssi".equalsIgnoreCase(instance.getServiceRole())) {
                                nssiId = instance.getServiceInstanceId()
                                nssiIdList.add(nssiId)
                            }
                        }
                    }
                }
            }
        }
        catch(BpmnError e){
            throw e
        }
        catch (Exception ex){
            String msg = "Exception in getNSIFromAAI " + ex.getMessage()
            LOGGER.error(msg)
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
        }
        return nssiIdList
    }

    /**
     * get nssi service from AAI
     * prepare list
     * @param execution
     */
    void getNSSIListFromAAI(DelegateExecution execution)
    {
        LOGGER.trace("*****${PREFIX} Start getNSSIListFromAAI *****")
        List<String> nssiIdList = execution.getVariable("nssiIdList")
        List<ServiceInstance> nssiInstanceList = []
        String errorMsg = "query nssi list from aai failed"
        for(String nssiId : nssiIdList)
        {
            AAIResultWrapper wrapper = queryAAI(execution, Types.SERVICE_INSTANCE, nssiId, errorMsg)
            Optional<ServiceInstance> si =wrapper.asBean(ServiceInstance.class)
            if(si.isPresent())
            {
                nssiInstanceList.add(si.get())
            }
        }
        int size = nssiInstanceList.size()
        int proportion = size >0 ?((90/size) as int) : 90
        execution.setVariable("nssiInstanceList", nssiInstanceList)
        execution.setVariable("currentNSSIIndex", 0)
        execution.setVariable("proportion", proportion)
        String msg ="nssiInstanceList size: ${nssiInstanceList.size()}, proportion:${proportion}"
        LOGGER.info(msg)
        LOGGER.trace(" *****${PREFIX} Exit getNSSIListFromAAI *****")
    }

    /**
     * get current NSSI
     * @param execution
     */
    void getCurrentNSSI(DelegateExecution execution)
    {
        LOGGER.trace(" *****${PREFIX} Start getCurrentNSSI *****")
        List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
        List<ServiceInstance> sliceProfileList = execution.getVariable("sliceProfileList")
        int currentIndex = execution.getVariable("currentNSSIIndex") as int
        String profileInstId = ""
        ServiceInstance nssi = nssiInstanceList?.get(currentIndex)
        List<Relationship> relationshipList = nssi.getRelationshipList()?.getRelationship()
        for(ServiceInstance sliceProfileInstance : sliceProfileList) {
            for (Relationship relationship : relationshipList) {
                String relatedTo = relationship.getRelatedTo()
                if (relatedTo == "service-instance"){
                    String relatedLink = relationship.getRelatedLink()?:""
                    String instanceId = relatedLink ? relatedLink.substring(relatedLink.lastIndexOf("/") + 1,relatedLink.length()) : ""
                    if(instanceId.equals(sliceProfileInstance.getServiceInstanceId())){
                        profileInstId = sliceProfileInstance.getServiceInstanceId()
                        break
                    }
                }
            }
            if(profileInstId){
                break
            }
        }

        //@TODO Temp begin*******************
//        AAIPluralResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(profileInstId).sliceProfiles())
//        AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
//        Optional<SliceProfiles> sliceProfilesOpt =wrapper.asBean(SliceProfiles.class)
//        SliceProfiles sliceProfiles
//        String sliceProfileId
//        if(sliceProfilesOpt.isPresent()){
//            sliceProfiles = sliceProfilesOpt.get()
//            org.onap.aai.domain.yang.SliceProfile sliceProfile = sliceProfiles.getSliceProfile().get(0)
//            sliceProfileId = sliceProfile ? sliceProfile.getProfileId() : ""
//        }
        //@TODO Temp end*******************

        def currentNSSI = [:]
        currentNSSI['nssiServiceInstanceId'] = nssi?.getServiceInstanceId()
        currentNSSI['modelInvariantId'] = nssi?.getModelInvariantId()
        currentNSSI['modelVersionId'] = nssi?.getModelVersionId()
        currentNSSI['nssiName'] = nssi?.getServiceInstanceName()
        currentNSSI['sST'] = nssi?.getServiceType()
        currentNSSI['PLMNIdList'] = nssi?.getServiceInstanceLocationId()
        //@TODO Temp

        currentNSSI['profileId'] =  profileInstId
//        currentNSSI['profileId'] =  sliceProfileId
        currentNSSI['snssai'] = execution.getVariable("snssai") ?: ""
        currentNSSI['nsiServiceInstanceId'] = execution.getVariable("nsiId") ?: ""
        currentNSSI['operationId'] = execution.getVariable("operationId") ?: ""
        currentNSSI['e2eServiceInstanceId'] = execution.getVariable("serviceInstanceId") ?: ""
        currentNSSI['msoRequestId'] = execution.getVariable("msoRequestId") ?: ""
        currentNSSI['globalSubscriberId'] = execution.getVariable("globalSubscriberId") ?: ""
        currentNSSI['serviceType'] = execution.getVariable("serviceType") ?: ""
        currentNSSI['serviceModelInfo'] = execution.getVariable("serviceModelInfo") ?: ""
        currentNSSI['proportion'] = (execution.getVariable("proportion") as int)*(currentIndex+1)
        execution.setVariable("currentNSSI", currentNSSI)
        String msg = "Now we deal with nssiServiceInstanceId: ${currentNSSI['nssiServiceInstanceId']}, current Index: ${currentIndex}, current proportion:${currentNSSI['proportion']}"
        LOGGER.info(msg)
        LOGGER.trace(" *****${PREFIX} Exit getCurrentNSSI *****")
    }

    /**
     * parse next nssi
     * @param execution
     */
    void parseNextNSSI(DelegateExecution execution)
    {
        LOGGER.trace(" *****${PREFIX} Start parseNextNSSI *****")
        if(execution.getVariable("WorkflowException") != null){
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "current job failure!")
        }
        def currentIndex = execution.getVariable("currentNSSIIndex")
        List<ServiceInstance> nssiInstanceList = execution.getVariable("nssiInstanceList")
        def nextIndex = ++currentIndex
        LOGGER.info("nextIndex: ${nextIndex}")
        if(nextIndex >= nssiInstanceList.size()){
            execution.setVariable("isAllNSSIFinished", "true")
        }else{
            execution.setVariable("isAllNSSIFinished", "false")
            execution.setVariable("currentNSSIIndex", nextIndex)
        }
        LOGGER.trace(" *****${PREFIX} Exit parseNextNSSI *****")
    }

    /**
     * query AAI
     * @param execution
     * @param aaiObjectName
     * @param instanceId
     * @return AAIResultWrapper
     */
    private AAIResultWrapper queryAAI(DelegateExecution execution, AAIObjectName aaiObjectName, String instanceId, String errorMsg)
    {
        LOGGER.trace(" *****${PREFIX} Start queryAAI *****")
        String globalSubscriberId = execution.getVariable("globalSubscriberId")
        String serviceType = execution.getVariable("serviceType")

        org.onap.aaiclient.client.generated.fluentbuilders.ServiceInstance serviceInstanceType = AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(instanceId)
        def type
        if (aaiObjectName == Types.ALLOTTED_RESOURCE) {
            type = serviceInstanceType.allottedResources()
        } else if (aaiObjectName == Types.SLICE_PROFILES) {
            type = serviceInstanceType.sliceProfiles()
        } else {
            type = serviceInstanceType
        }
        def uri = AAIUriFactory.createResourceUri(type)
        if (!getAAIClient().exists(uri)) {
            exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMsg)
        }
        AAIResultWrapper wrapper = getAAIClient().get(uri, NotFoundException.class)
        LOGGER.trace(" *****${PREFIX} Exit queryAAI *****")
        return wrapper
    }

    void terminateNSIQuery(DelegateExecution execution)
    {
        LOGGER.debug("Start terminateNSIQuery")

        return

        //To test
        String requestId = execution.getVariable("msoRequestId")
        String nxlId = currentNSSI['nsiServiceInstanceId']
        String nxlType = "NSI"
        String messageType = "nsiTerminationResponse"
        String serviceInstanceId = execution.getVariable("serviceInstanceId")
        
        def authHeader = ""
        String basicAuth = UrnPropertiesReader.getVariable("mso.oof.auth", execution)
        String msokey = UrnPropertiesReader.getVariable("mso.msoKey", execution)

        String basicAuthValue = utils.encrypt(basicAuth, msokey)
        if (basicAuthValue != null) {
            LOGGER.debug( "Obtained BasicAuth username and password for OOF: " + basicAuthValue)
            try {
                authHeader = utils.getBasicAuth(basicAuthValue, msokey)
                execution.setVariable("BasicAuthHeaderValue", authHeader)
            } catch (Exception ex) {
                LOGGER.debug( "Unable to encode username and password string: " + ex)
                exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - Unable to " +
                        "encode username and password string")
            }
        } else {
            LOGGER.debug( "Unable to obtain BasicAuth - BasicAuth value null")
            exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Internal Error - BasicAuth " +
                    "value null")
        }

        URL requestUrl = new URL(oofUrl + "/api/oof/terminate/nxi/v1")
        String oofRequest = oofUtils.buildTerminateNxiRequest(requestId, nxlId, nxlType, messageType, serviceInstanceId)
        HttpClient httpClient = new HttpClientFactory().newJsonClient(requestUrl, ONAPComponents.OOF)
        httpClient.addAdditionalHeader("Authorization", authHeader)
        Response httpResponse = httpClient.post(oofRequest)

        int responseCode = httpResponse.getStatus()
        LOGGER.debug("OOF sync response code is: " + responseCode)

        if(responseCode != 200){
            exceptionUtil.buildAndThrowWorkflowException(execution, responseCode, "Received a Bad Sync Response from OOF.")
        }       
        try {
            Map<String, String> resMap = httpResponse.readEntity(Map.class)
            boolean terminateResponse = resMap.get("terminateResponse")
            execution.setVariable("terminateNSI", terminateResponse)
        } catch (Exception ex) {
            LOGGER.debug( "Failed to get terminate Response suggested by OOF.")
            exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Failed to get terminate Response suggested by OOF.")
        }
        LOGGER.debug("Finish terminateNSIQuery")
    }


    /**
     * If no nssi,delete NSI from AAI
     * @param execution
     */
    void deleteNSIInstance(DelegateExecution execution){
        def currentNSSI = execution.getVariable("currentNSSI")
        def nsiId = currentNSSI['nsiServiceInstanceId']
        List<String> nssiIdList = getNSSIIdList(execution, nsiId)
        try
        {
            if(0 == nssiIdList.size()){
                AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(nsiId))
                getAAIClient().delete(serviceInstanceUri)
            }
        } catch (Exception ex) {
            LOGGER.debug( "Failed to delete NSI instance.")
            exceptionUtil.buildAndThrowWorkflowException(execution, 401, "Failed to delete NSI instance.")
        }

    }
}