f0d43cf8d785b2b0d5ea74a45c1b1354e381569d
[so.git] /
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.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.aai.domain.yang.ServiceProfile
26 import org.onap.aai.domain.yang.ServiceProfiles
27 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
29 import org.onap.so.bpmn.common.scripts.MsoUtils
30 import org.onap.so.bpmn.common.scripts.RequestDBUtil
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.json.JsonUtils
33 import org.onap.so.client.aai.AAIObjectType
34 import org.onap.so.client.aai.AAIResourcesClient
35 import org.onap.so.client.aai.entities.AAIResultWrapper
36 import org.onap.so.client.aai.entities.uri.AAIResourceUri
37 import org.onap.so.client.aai.entities.uri.AAIUriFactory
38 import org.onap.so.db.request.beans.OperationStatus
39 import org.slf4j.Logger
40 import org.slf4j.LoggerFactory
41
42 import javax.ws.rs.NotFoundException
43
44 import static org.apache.commons.lang3.StringUtils.isBlank
45
46 class DeleteSliceService extends AbstractServiceTaskProcessor {
47
48     String Prefix="DELSS_"
49     ExceptionUtil exceptionUtil = new ExceptionUtil()
50     JsonUtils jsonUtil = new JsonUtils()
51     private RequestDBUtil requestDBUtil = new RequestDBUtil()
52
53     private static final Logger logger = LoggerFactory.getLogger( DeleteSliceService.class)
54
55     @Override
56     void preProcessRequest(DelegateExecution execution) {
57         execution.setVariable("prefix", Prefix)
58         String msg = ""
59
60         logger.trace("Starting preProcessRequest")
61
62         try {
63             // check for incoming json message/input
64             String siRequest = execution.getVariable("bpmnRequest")
65             String requestId = execution.getVariable("mso-request-id")
66             execution.setVariable("msoRequestId", requestId)
67
68             //e2eslice-service instance id
69             String serviceInstanceId = execution.getVariable("serviceInstanceId")
70             if (isBlank(serviceInstanceId)) {
71                 msg = "e2eslice-service id is null"
72                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
73             }
74             logger.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
75
76             //subscriberInfo
77             checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
78             checkAndSetRequestParam(siRequest,"serviceType",false, execution)
79             checkAndSetRequestParam(siRequest,"operationId",false, execution)
80
81             //prepare init operation status
82             execution.setVariable("progress", "0")
83             execution.setVariable("result", "processing")
84             execution.setVariable("operationType", "DELETE")
85             execution.setVariable("operationContent", "Prepare init service")
86             updateServiceOperationStatus(execution)
87
88         } catch (BpmnError e) {
89             throw e
90         } catch (Exception ex) {
91             msg = "Exception in preProcessRequest " + ex.getMessage()
92             logger.debug(msg)
93             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
94         }
95         logger.trace("Exit preProcessRequest")
96     }
97
98     /**
99      * send asynchronous response
100      * @param execution
101      */
102     void sendAsyncResponse(DelegateExecution execution) {
103         logger.trace("Staring sendSyncResponse")
104
105         try {
106             String operationId = execution.getVariable("operationId")
107             String syncResponse = """{"operationId":"${operationId}"}""".trim()
108             logger.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
109             sendWorkflowResponse(execution, 202, syncResponse)
110
111         } catch (Exception ex) {
112             String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
113             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
114         }
115         logger.trace("Exit sendSyncResponse")
116     }
117
118     /**
119      * Deletes the slice service instance in aai
120      */
121     void deleteSliceServiceInstance(DelegateExecution execution) {
122         logger.trace("Entered deleteSliceServiceInstance")
123         try {
124
125             AAIResourcesClient resourceClient = new AAIResourcesClient()
126             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
127             resourceClient.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("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     private 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             AAIResourcesClient resourceClient = new AAIResourcesClient()
174             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
175             AAIResultWrapper wrapper = resourceClient.get(resourceUri, NotFoundException.class)
176             Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
177             if(serviceProfilesOpt.isPresent()){
178                 ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
179                 ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
180                 profileId = serviceProfile ? serviceProfile.getProfileId() : ""
181             }
182             resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
183             if (!resourceClient.exists(resourceUri)) {
184                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
185             }
186             resourceClient.delete(resourceUri)
187         }
188         catch (any)
189         {
190             String msg = "delete service profile from aai failed! cause-"+any.getCause()
191             logger.error(any.printStackTrace())
192             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
193         }
194     }
195
196      void sendSyncError(DelegateExecution execution) {
197         logger.info("Starting sendSyncError")
198
199         try {
200             String errorMessage
201             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
202                 WorkflowException wfe = execution.getVariable("WorkflowException")
203                 errorMessage = wfe.getErrorMessage()
204             } else {
205                 errorMessage = "Sending Sync Error."
206             }
207
208             String buildworkflowException =
209                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
210                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
211                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
212                                    </aetgt:WorkflowException>"""
213
214             logger.debug(buildworkflowException)
215             sendWorkflowResponse(execution, 500, buildworkflowException)
216
217         } catch (Exception ex) {
218             logger.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
219         }
220
221     }
222
223     void prepareEndOperationStatus(DelegateExecution execution){
224         logger.debug(" ======== STARTED prepareEndOperationStatus Process ======== ")
225
226         execution.setVariable("progress", "100")
227         execution.setVariable("result", "error")
228         execution.setVariable("operationContent", "NSSMF Terminate service failure")
229
230         WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
231         String errorMessage = wfex.getErrorMessage()
232         errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
233         execution.setVariable("reason",errorMessage)
234         updateServiceOperationStatus(execution)
235
236         logger.debug("======== COMPLETED prepareEndOperationStatus Process ======== ")
237     }
238
239     /**
240      * check parameters from request body
241      * set to execution
242      * @param siRequest
243      * @param paraName
244      * @param isErrorException
245      * @param execution
246      */
247     private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
248     {
249         String msg = ""
250         String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
251         if (isBlank(paramValue)) {
252             msg = "Input ${paraName} is null"
253             logger.error(msg)
254             if(isErrorException)
255             {
256                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
257             }
258
259         } else {
260             execution.setVariable(paraName, paramValue)
261         }
262     }
263 }