4ed0ea6a44d6d0dfbfae09eda1fe34754b9b2df0
[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.Relationship
26 import org.onap.aai.domain.yang.RelationshipData
27 import org.onap.aai.domain.yang.RelationshipList
28 import org.onap.aai.domain.yang.ServiceInstance
29 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
30 import org.onap.so.bpmn.common.scripts.ExceptionUtil
31 import org.onap.so.bpmn.common.scripts.MsoUtils
32 import org.onap.so.bpmn.common.scripts.RequestDBUtil
33 import org.onap.so.bpmn.core.UrnPropertiesReader
34 import org.onap.so.bpmn.core.WorkflowException
35 import org.onap.so.bpmn.core.json.JsonUtils
36 import org.onap.so.client.aai.AAIObjectType
37 import org.onap.so.client.aai.AAIResourcesClient
38 import org.onap.so.client.aai.entities.AAIResultWrapper
39 import org.onap.so.client.aai.entities.uri.AAIResourceUri
40 import org.onap.so.client.aai.entities.uri.AAIUriFactory
41 import org.onap.so.db.request.beans.OperationStatus
42 import org.slf4j.Logger
43 import org.slf4j.LoggerFactory
44
45 import javax.ws.rs.NotFoundException
46
47 import static org.apache.commons.lang3.StringUtils.isBlank
48
49 class ActivateCommunicationService extends AbstractServiceTaskProcessor {
50
51     String Prefix="ACS_"
52
53     ExceptionUtil exceptionUtil = new ExceptionUtil()
54
55     RequestDBUtil requestDBUtil = new RequestDBUtil()
56
57     JsonUtils jsonUtil = new JsonUtils()
58
59     AAIResourcesClient client = getAAIClient()
60
61     private static final Logger logger = LoggerFactory.getLogger(ActivateCommunicationService.class)
62
63     @Override
64     void preProcessRequest(DelegateExecution execution) {
65         logger.debug(Prefix + "preProcessRequest Start")
66         execution.setVariable("prefix", Prefix)
67         String msg
68
69         try {
70             // check for incoming json message/input
71             String siRequest = execution.getVariable("bpmnRequest")
72             logger.debug(siRequest)
73
74             String requestId = execution.getVariable("mso-request-id")
75             execution.setVariable("msoRequestId", requestId)
76             logger.info("Input Request:" + siRequest + " reqId:" + requestId)
77
78             String serviceInstanceId = execution.getVariable("serviceInstanceId")
79             if (isBlank(serviceInstanceId)) {
80                 msg = "Input serviceInstanceId' is null"
81                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
82             }
83
84             String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId")
85             if (isBlank(globalSubscriberId)) {
86                 msg = "Input globalSubscriberId' is null"
87                 logger.info(msg)
88                 execution.setVariable("globalSubscriberId", "5GCustomer")
89             } else {
90                 execution.setVariable("globalSubscriberId", globalSubscriberId)
91             }
92
93             String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType")
94             if (isBlank(subscriptionServiceType)) {
95                 msg = "Input subscriptionServiceType is null"
96                 logger.debug(msg)
97                 execution.setVariable("subscriptionServiceType", "5G")
98             } else {
99                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
100             }
101
102             String operationId = jsonUtil.getJsonValue(siRequest, "operationId")
103             execution.setVariable("operationId", operationId)
104
105             String operationType = execution.getVariable("operationType")
106             execution.setVariable("operationType", operationType.toUpperCase())
107
108         } catch (BpmnError e) {
109             throw e
110         } catch (Exception ex) {
111             msg = "Exception in preProcessRequest " + ex.getMessage()
112             logger.info(msg)
113             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
114         }
115         logger.debug(Prefix + "preProcessRequest Exit")
116     }
117
118
119     def checkAAIOrchStatus = { DelegateExecution execution ->
120
121         logger.debug(Prefix + "checkAAIOrchStatus Start")
122
123         String msg
124         String serviceInstanceId = execution.getVariable("serviceInstanceId")
125         String globalSubscriberId = execution.getVariable("globalSubscriberId")
126         String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
127         String operationType = execution.getVariable("operationType")
128
129         logger.debug("serviceInstanceId: " + serviceInstanceId)
130
131         //check the cms status
132         try {
133             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
134                     globalSubscriberId, subscriptionServiceType, serviceInstanceId)
135
136             if (!client.exists(uri)) {
137                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
138             }
139
140             AAIResultWrapper wrapper = client.get(uri, NotFoundException.class)
141             Optional<ServiceInstance> si = wrapper.asBean(ServiceInstance.class)
142             if(si.isPresent()) {
143
144                 if (si.get().getOrchestrationStatus().toLowerCase() == "activated" &&
145                         operationType.equalsIgnoreCase("deactivation")) {
146                     logger.info("Service is in active state")
147                     execution.setVariable("serviceExpectStatus", "deactivated")
148                     execution.setVariable("isContinue", "true")
149                     execution.setVariable("requestParam", "deactivate")
150
151                 } else if (si.get().getOrchestrationStatus().toLowerCase()  == "deactivated" &&
152                         operationType.equalsIgnoreCase("activation")){
153                     logger.info("Service is  in de-activated state")
154                     execution.setVariable("serviceExpectStatus", "activated")
155                     execution.setVariable("isContinue", "true")
156                     execution.setVariable("requestParam", "activate")
157
158                 } else {
159                     execution.setVariable("isContinue", "false")
160                 }
161
162                 RelationshipList relationshipList = si.get().getRelationshipList()
163                 List<Relationship> relationship
164                 if (relationshipList != null && (relationship = relationshipList.getRelationship()) != null
165                         && relationship.size() > 0) {
166                     List<RelationshipData> relationshipDatas = relationship.get(0).getRelationshipData()
167
168                     for (RelationshipData relationshipData : relationshipDatas) {
169                         execution.setVariable("e2e_" + relationshipData.getRelationshipKey(),
170                                 relationshipData.getRelationshipValue())
171                     }
172                 } else {
173                     msg = "the communication service has no e2e service"
174                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
175                 }
176             }
177
178         } catch (BpmnError e) {
179             throw e
180         } catch (Exception ex) {
181             msg = "Exception in " + Prefix + "checkAAIOrchStatus: " + ex.getMessage()
182             logger.info( msg)
183             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
184         }
185
186         logger.debug(Prefix + "checkAAIOrchStatus Exit")
187     }
188
189
190     def prepareInitOperationStatus = { DelegateExecution execution ->
191         logger.debug(Prefix + "prepareInitOperationStatus Start")
192
193         String serviceId = execution.getVariable("serviceInstanceId")
194
195         // 生成 operationId
196         String operationId = execution.getVariable("operationId")
197
198         String operationType = execution.getVariable("operationType")
199
200         OperationStatus initStatus = new OperationStatus()
201         initStatus.setServiceId(serviceId)
202         initStatus.setOperationId(operationId)
203         initStatus.setOperation(operationType)
204         initStatus.setUserId(execution.getVariable("globalSubscriberId") as String)
205         initStatus.setResult("processing")
206         initStatus.setProgress("0")
207         initStatus.setReason("")
208         initStatus.setOperationContent("communication service active operation start")
209
210         requestDBUtil.prepareUpdateOperationStatus(execution, initStatus)
211
212         logger.debug(Prefix + "prepareInitOperationStatus Exit")
213     }
214
215
216     def sendSyncResponse = { DelegateExecution execution ->
217         logger.debug(Prefix + "sendSyncResponse Start")
218         try {
219             String operationId = execution.getVariable("operationId")
220
221             String restRequest = """{"operationId":"${operationId}"}""".trim()
222             logger.debug(" sendSyncResponse to APIH:" + "\n" + restRequest)
223
224             sendWorkflowResponse(execution, 202, restRequest)
225             execution.setVariable("sentSyncResponse", true)
226         } catch (Exception ex) {
227             String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
228             logger.debug(msg)
229             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
230         }
231         logger.debug(Prefix + "sendSyncResponse Exit")
232     }
233
234
235     def preRequestSend2NSMF = { DelegateExecution execution ->
236         logger.debug(Prefix + "preRequestSend2NSMF Start")
237         try {
238
239             String e2eServiceInstanceId = execution.getVariable("e2e_service-instance.service-instance-id")
240             execution.setVariable("e2eServiceInstanceId", e2eServiceInstanceId)
241
242             String requestParam = execution.getVariable("requestParam")
243             //String NSMF_endpoint = "/onap/so/infra/e2eServiceInstances/v3"
244             def NSMF_endpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution)
245             def url = NSMF_endpoint + "/e2eServiceInstances/v3/${e2eServiceInstanceId}/${requestParam}"
246             execution.setVariable("NSMF_endpoint", url)
247
248             //get from model catalog inputs
249             String payload = """
250                 {
251                     "globalSubscriberId": "${execution.getVariable("globalSubscriberId")}",
252                     "serviceType": "${execution.getVariable("subscriptionServiceType")}"
253                 }
254             """
255             execution.setVariable("CSMF_NSMFRequest", payload.replaceAll("\\s+", ""))
256
257         } catch (BpmnError e) {
258             throw e
259         } catch (Exception ex) {
260             String msg = "Exception in " + Prefix + "preRequestSend2NSMF. " + ex.getMessage()
261             logger.error(msg)
262             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
263         }
264
265         logger.debug(Prefix + "preRequestSend2NSMF Exit")
266     }
267
268
269     def processNSMFResponse = { DelegateExecution execution ->
270         logger.debug(Prefix + "processNSMFResponse Start")
271         //oof
272         try {
273             def CSMF_NSMFResponseCode = execution.getVariable("CSMF_NSMFResponseCode") as Integer
274             if (CSMF_NSMFResponseCode >= 200 && CSMF_NSMFResponseCode < 400) {
275                 def CSMF_NSMFResponse = execution.getVariable("CSMF_NSMFResponse") as String
276                 def e2eOperationId = jsonUtil.getJsonValue(CSMF_NSMFResponse, "operationId")
277
278                 execution.setVariable("e2eOperationId", e2eOperationId)
279                 execution.setVariable("ProcessNsmfSuccess", "OK")
280             } else {
281                 execution.setVariable("ProcessNsmfSuccess", "ERROR")
282                 execution.setVariable("operationStatus", "error")
283                 execution.setVariable("operationContent",
284                         "communication service " + execution.getVariable("operationType")
285                                 + " operation error: nsmf response fail")
286                 execution.setVariable("orchestrationStatus", "error")
287             }
288
289         } catch (BpmnError e) {
290             throw e
291         } catch (Exception ex) {
292             String msg = "Exception in " + Prefix + "processOOFResponse. " + ex.getMessage()
293             logger.info(msg)
294             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
295         }
296         logger.debug(Prefix + "processNSMFResponse Exit")
297     }
298
299
300     def prepareUpdateOperationStatus = { DelegateExecution execution ->
301         logger.debug(Prefix + "prepareUpdateOperationStatus Start")
302         // update status creating
303         OperationStatus status = new OperationStatus()
304         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
305         status.setOperationId(execution.getVariable("operationId") as String)
306         status.setOperation(execution.getVariable("operationType") as String)
307         status.setResult("processing")
308         status.setProgress("20")
309         status.setOperationContent("communication service "+ execution.getVariable("operationType")
310                 + " operation processing: waiting nsmf service create finished")
311         status.setUserId(execution.getVariable("globalSubscriberId") as String)
312
313         requestDBUtil.prepareUpdateOperationStatus(execution, status)
314         logger.debug(Prefix + "prepareUpdateOperationStatus Exit")
315     }
316
317
318     //todo
319     def prepareCallCheckProcessStatus = { DelegateExecution execution ->
320         logger.debug(Prefix + "prepareCallCheckProcessStatus Start")
321
322         def successConditions = new ArrayList<>()
323         successConditions.add("finished")
324         execution.setVariable("successConditions", successConditions)
325
326         def errorConditions = new ArrayList<>()
327         errorConditions.add("error")
328         execution.setVariable("errorConditions", errorConditions)
329
330         execution.setVariable("processServiceType", "communication service")
331
332         execution.setVariable("timeOut", 3 * 60 * 60 * 1000)
333
334         def successParamMap = new HashMap<String, Object>()
335         successParamMap.put("orchestrationStatus", execution.getVariable("serviceExpectStatus"))
336
337         execution.setVariable("successParamMap", successParamMap)
338
339         def errorParamMap = new HashMap<String, Object>()
340         errorParamMap.put("orchestrationStatus", "error")
341
342         execution.setVariable("errorParamMap", errorParamMap)
343
344         def timeOutParamMap = new HashMap<String, Object>()
345         timeOutParamMap.put("orchestrationStatus", "error")
346
347         execution.setVariable("timeOutParamMap", timeOutParamMap)
348
349         execution.setVariable("initProgress", 20)
350         execution.setVariable("endProgress", 90)
351
352         logger.debug(Prefix + "prepareCallCheckProcessStatus Exit")
353     }
354
355
356     /**
357      * prepare update operation status to complete after NSMF process success
358      * @param execution
359      */
360     def prepareCompleteStatus = { DelegateExecution execution ->
361
362         logger.debug(Prefix + "prepareCompleteStatus Start")
363         String operationType = execution.getVariable("operationType")
364         OperationStatus status = new OperationStatus()
365         status.setServiceId(execution.getVariable("serviceInstanceId") as String)
366         status.setOperationId(execution.getVariable("operationId") as String)
367         status.setOperation(operationType)
368         status.setResult(execution.getVariable("operationStatus") as String)
369         status.setProgress("100")
370         status.setOperationContent(execution.getVariable("operationContent") as String)
371         status.setUserId(execution.getVariable("globalSubscriberId") as String)
372
373         requestDBUtil.prepareUpdateOperationStatus(execution, status)
374         logger.debug("prepareCompleteStatus end, serviceInstanceId: " + execution.getVariable("serviceInstanceId")
375                 + ", operationId: " + execution.getVariable("operationId"))
376
377         logger.debug(Prefix + "prepareCompleteStatus Exit")
378     }
379
380
381     /**
382      * update NSMF complete status to AAI when the NSMF process finished
383      * @param execution
384      */
385     def updateFinishStatusInAAI = { DelegateExecution execution ->
386         logger.debug(Prefix + "updateFinishStatusInAAI Start")
387         String msg
388         try {
389
390             String serviceInstanceId = execution.getVariable("serviceInstanceId")
391             String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
392             String globalSubscriberId = execution.getVariable("globalSubscriberId")
393             String orchestrationStatus = execution.getVariable("orchestrationStatus")
394             // create service
395             ServiceInstance csi = new ServiceInstance()
396             csi.setOrchestrationStatus(orchestrationStatus)
397             AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,
398                     globalSubscriberId, subscriptionServiceType, serviceInstanceId)
399             client.update(uri, csi)
400
401         } catch (BpmnError e) {
402             throw e
403         } catch (Exception ex) {
404             msg = "Exception in complete communication service " + ex.getMessage()
405             logger.debug(msg)
406             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
407         }
408         logger.debug(Prefix + "updateFinishStatusInAAI Exit")
409     }
410
411
412     public sendSyncError = { DelegateExecution execution ->
413         logger.debug("sendSyncError Start")
414         try {
415             String errorMessage
416             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
417                 WorkflowException wfe = execution.getVariable("WorkflowException") as WorkflowException
418                 errorMessage = wfe.getErrorMessage()
419             } else {
420                 errorMessage = "Sending Sync Error."
421             }
422
423             String buildWorkflowException =
424                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
425                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
426                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
427                                    </aetgt:WorkflowException>"""
428
429             logger.debug(buildWorkflowException)
430             sendWorkflowResponse(execution, 500, buildWorkflowException)
431
432         } catch (Exception ex) {
433             logger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
434         }
435         logger.debug(Prefix + "sendSyncError Exit")
436     }
437
438 }