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