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