Merge "add nsi name info to an and cn"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DeleteSliceService.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (c) 2019, CMCC Technologies Co., Ltd.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import org.onap.aaiclient.client.aai.entities.uri.AAISimpleUri
24
25 import static org.apache.commons.lang3.StringUtils.isBlank
26 import javax.ws.rs.NotFoundException
27 import org.camunda.bpm.engine.delegate.BpmnError
28 import org.camunda.bpm.engine.delegate.DelegateExecution
29 import org.onap.aai.domain.yang.ServiceProfile
30 import org.onap.aai.domain.yang.ServiceProfiles
31 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
32 import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri
33 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
34 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
35 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
36 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
37 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
38 import org.onap.so.bpmn.common.scripts.ExceptionUtil
39 import org.onap.so.bpmn.common.scripts.MsoUtils
40 import org.onap.so.bpmn.common.scripts.RequestDBUtil
41 import org.onap.so.bpmn.core.WorkflowException
42 import org.onap.so.bpmn.core.json.JsonUtils
43 import org.onap.so.db.request.beans.OperationStatus
44 import org.slf4j.Logger
45 import org.slf4j.LoggerFactory
46
47 class DeleteSliceService extends AbstractServiceTaskProcessor {
48
49     private final String PREFIX ="DeleteSliceService"
50     ExceptionUtil exceptionUtil = new ExceptionUtil()
51     JsonUtils jsonUtil = new JsonUtils()
52     private RequestDBUtil requestDBUtil = new RequestDBUtil()
53
54     private static final Logger LOGGER = LoggerFactory.getLogger( DeleteSliceService.class)
55
56     @Override
57     void preProcessRequest(DelegateExecution execution) {
58         execution.setVariable("prefix", PREFIX)
59         String msg = ""
60
61         LOGGER.debug("*****${PREFIX} preProcessRequest *****")
62
63         try {
64             // check for incoming json message/input
65             String siRequest = execution.getVariable("bpmnRequest")
66             String requestId = execution.getVariable("mso-request-id")
67             execution.setVariable("msoRequestId", requestId)
68
69             //e2eslice-service instance id
70             String serviceInstanceId = execution.getVariable("serviceInstanceId")
71             if (isBlank(serviceInstanceId)) {
72                 msg = "e2eslice-service id is null"
73                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
74             }
75             LOGGER.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
76
77             //subscriberInfo
78             checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
79             checkAndSetRequestParam(siRequest,"serviceType",false, execution)
80             checkAndSetRequestParam(siRequest,"operationId",false, execution)
81             checkAndSetRequestParam(siRequest,"scriptName",false, execution)
82             //prepare init operation status
83             execution.setVariable("progress", "0")
84             execution.setVariable("result", "processing")
85             execution.setVariable("operationType", "DELETE")
86             execution.setVariable("operationContent", "Delete Slice service operation start")
87             updateServiceOperationStatus(execution)
88
89         } catch (BpmnError e) {
90             throw e
91         } catch (Exception ex) {
92             msg = "Exception in preProcessRequest " + ex.getMessage()
93             LOGGER.debug(msg)
94             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
95         }
96         LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
97     }
98
99     /**
100      * send asynchronous response
101      * @param execution
102      */
103     void sendAsyncResponse(DelegateExecution execution) {
104         LOGGER.trace("${PREFIX} Start sendSyncResponse ")
105
106         try {
107             String operationId = execution.getVariable("operationId")
108             String syncResponse = """{"operationId":"${operationId}"}""".trim()
109             LOGGER.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
110             sendWorkflowResponse(execution, 202, syncResponse)
111
112         } catch (Exception ex) {
113             String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
114             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
115         }
116         LOGGER.trace("${PREFIX} Exit sendSyncResponse")
117     }
118
119     /**
120      * Deletes the slice service instance in aai
121      */
122     void deleteSliceServiceInstance(DelegateExecution execution) {
123         LOGGER.trace("${PREFIX} Start deleteSliceServiceInstance")
124         try {
125
126             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(execution.getVariable("globalSubscriberId")).serviceSubscription(execution.getVariable("serviceType")).serviceInstance(execution.getVariable("serviceInstanceId")))
127             getAAIClient().delete(serviceInstanceUri)
128
129             execution.setVariable("progress", "100")
130             execution.setVariable("result", "finished")
131             execution.setVariable("operationContent", "NSMF completes slicing service termination.")
132             updateServiceOperationStatus(execution)
133
134             LOGGER.trace("${PREFIX} Exited deleteSliceServiceInstance")
135         }catch(Exception e){
136             LOGGER.debug("Error occured within deleteSliceServiceInstance method: " + e)
137             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteSliceServiceInstance from aai")
138         }
139     }
140
141     /**
142      * update operation status
143      * @param execution
144      */
145     private void updateServiceOperationStatus(DelegateExecution execution){
146
147         OperationStatus operationStatus = new OperationStatus()
148         operationStatus.setServiceId(execution.getVariable("serviceInstanceId"))
149         operationStatus.setOperationId(execution.getVariable("operationId"))
150         operationStatus.setUserId(execution.getVariable("globalSubscriberId"))
151         operationStatus.setResult(execution.getVariable("result"))
152         operationStatus.setProgress(execution.getVariable("progress"))
153         operationStatus.setOperationContent(execution.getVariable("operationContent"))
154         operationStatus.setReason(execution.getVariable("reason"))
155         operationStatus.setOperation(execution.getVariable("operationType"))
156
157         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
158     }
159
160     /**
161      * delete service profile from aai
162      * @param execution
163      */
164     void delServiceProfileFromAAI(DelegateExecution execution)
165     {
166         String globalSubscriberId = execution.getVariable("globalSubscriberId")
167         String serviceType = execution.getVariable("serviceType")
168         String serviceInstanceId = execution.getVariable("serviceInstanceId")
169         String profileId = ""
170
171         try
172         {
173             AAIPluralResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(serviceInstanceId).serviceProfiles())
174             AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
175             Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
176             if(serviceProfilesOpt.isPresent()){
177                 ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
178                 ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
179                 profileId = serviceProfile ? serviceProfile.getProfileId() : ""
180             }
181             AAISimpleUri profileUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(serviceInstanceId).serviceProfile(profileId))
182             if (!getAAIClient().exists(profileUri)) {
183                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
184             }
185             getAAIClient().delete(profileUri)
186         }
187         catch (any)
188         {
189             String msg = "delete service profile from aai failed! cause-"+any.getCause()
190             LOGGER.error(any.printStackTrace())
191             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
192         }
193     }
194
195      void sendSyncError(DelegateExecution execution) {
196         LOGGER.debug("${PREFIX} Start sendSyncError")
197
198         try {
199             String errorMessage = "Sending Sync Error."
200             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
201                 WorkflowException wfe = execution.getVariable("WorkflowException")
202                 errorMessage = wfe.getErrorMessage()
203             }
204
205             String buildworkflowException =
206                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
207                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
208                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
209                                    </aetgt:WorkflowException>"""
210
211             LOGGER.debug(buildworkflowException)
212             sendWorkflowResponse(execution, 500, buildworkflowException)
213
214         } catch (Exception ex) {
215             LOGGER.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
216         }
217
218     }
219
220     void prepareEndOperationStatus(DelegateExecution execution){
221         LOGGER.debug(" ======== ${PREFIX} STARTED prepareEndOperationStatus Process ======== ")
222
223         execution.setVariable("progress", "100")
224         execution.setVariable("result", "error")
225         execution.setVariable("operationContent", "NSSMF Terminate service failure")
226
227         WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
228         String errorMessage = wfex.getErrorMessage()
229         errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
230         execution.setVariable("reason",errorMessage)
231         updateServiceOperationStatus(execution)
232
233         LOGGER.debug("======== ${PREFIX} COMPLETED prepareEndOperationStatus Process ======== ")
234     }
235
236     /**
237      * check parameters from request body
238      * set to execution
239      * @param siRequest
240      * @param paraName
241      * @param isErrorException
242      * @param execution
243      */
244     private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
245     {
246         String msg = ""
247         String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
248         if (isBlank(paramValue)) {
249             msg = "Input ${paraName} is null"
250             LOGGER.error(msg)
251             if(isErrorException)
252             {
253                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
254             }
255
256         } else {
257             execution.setVariable(paraName, paramValue)
258         }
259     }
260 }