3233bfff61192fc21c328143ba2500a719ce841a
[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.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.ExceptionUtil
27 import org.onap.so.bpmn.common.scripts.RequestDBUtil
28 import org.onap.so.bpmn.core.json.JsonUtils
29 import org.onap.so.client.aai.AAIResourcesClient
30 import org.onap.so.db.request.beans.OperationStatus
31 import org.slf4j.Logger
32 import org.slf4j.LoggerFactory
33
34 import java.util.concurrent.TimeUnit
35
36 import static org.apache.commons.lang3.StringUtils.isBlank
37
38 class CheckServiceProcessStatus extends AbstractServiceTaskProcessor  {
39
40
41     String Prefix="CSPS_"
42
43     ExceptionUtil exceptionUtil = new ExceptionUtil()
44
45     RequestDBUtil requestDBUtil = new RequestDBUtil()
46
47     JsonUtils jsonUtil = new JsonUtils()
48
49     AAIResourcesClient client = getAAIClient()
50
51     private static final Logger logger = LoggerFactory.getLogger(CheckServiceProcessStatus.class)
52
53     @Override
54     void preProcessRequest(DelegateExecution execution) {
55         logger.debug(Prefix + "CheckServiceProcessStatus preProcessRequest Start")
56         execution.setVariable("prefix", Prefix)
57
58         String serviceInstanceId = execution.getVariable("serviceInstanceId")
59         String operationId = execution.getVariable("operationId")
60         String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId")
61         String parentOperationId = execution.getVariable("parentOperationId")
62
63         if (isBlank(serviceInstanceId) || isBlank(operationId)) {
64             String msg = "Exception in" + Prefix + "preProcessRequest: Input serviceInstanceId or operationId is null"
65             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
66         }
67
68         if (isBlank(parentServiceInstanceId) || isBlank(parentOperationId)) {
69             execution.setVariable("isNeedUpdateParentStatus", false)
70         }
71
72         String globalSubscriberId = execution.getVariable("globalSubscriberId")
73         if (isBlank(globalSubscriberId)) {
74             execution.setVariable("globalSubscriberId", "5GCustomer")
75         }
76
77         // serviceType: type of service
78         String serviceType = execution.getVariable("processServiceType")
79         if (isBlank(serviceType)) {
80             execution.setVariable("processServiceType", "service")
81         }
82
83         // operationType: type of service
84         String operationType = execution.getVariable("operationType")
85         if (isBlank(operationType)) {
86             execution.setVariable("operationType", "CREATE")
87         }
88
89         //successConditions: processing end success conditions
90         List<String> successConditions = execution.getVariable("successConditions") as List
91
92         //errorConditions: processing end error conditions
93         List<String> errorConditions = execution.getVariable("errorConditions") as List
94
95         if ((successConditions == null || successConditions.size() < 1)
96                 && (errorConditions == null || errorConditions.size() < 1)) {
97             String msg = "Exception in" + Prefix + "preProcessRequest: conditions is null"
98             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
99         } else {
100             for (int i = 0; i < successConditions.size(); i++) {
101                 String condition = successConditions.get(i)
102                 successConditions.set(i, condition.toLowerCase())
103             }
104             for (int i = 0; i < errorConditions.size(); i++) {
105                 String condition = errorConditions.get(i)
106                 errorConditions.set(i, condition.toLowerCase())
107             }
108         }
109
110         execution.setVariable("startTime", System.currentTimeMillis())
111
112         String initProgress = execution.getVariable("initProgress")
113
114         if (isBlank(initProgress)) {
115             execution.setVariable("initProgress", 0)
116         }
117
118         String endProgress = execution.getVariable("endProgress")
119
120         if (isBlank(endProgress)) {
121             execution.setVariable("endProgress", 100)
122         }
123
124         execution.setVariable("progress", 0)
125         logger.debug(Prefix + "preProcessRequest Exit")
126     }
127
128
129     /**
130      * check service status through request operation id, update operation status
131     */
132     def preCheckServiceStatusReq = { DelegateExecution execution ->
133         logger.trace(Prefix + "preCheckServiceStatusReq Start")
134         String serviceInstanceId = execution.getVariable("serviceInstanceId") as String
135         String operationId = execution.getVariable("operationId") as String
136         requestDBUtil.getOperationStatus(execution, serviceInstanceId, operationId)
137         logger.trace(Prefix + "preCheckServiceStatusReq Exit")
138     }
139
140
141     /**
142      * handle service status, if service status is finished or error, set the service status
143      * @param execution
144      */
145     def handlerServiceStatusResp = { DelegateExecution execution ->
146         logger.trace(Prefix + "handlerServiceStatusResp Start")
147         String msg
148         try {
149             def dbResponseCode = execution.getVariable("dbResponseCode") as Integer
150             if (dbResponseCode >= 200 && dbResponseCode < 400) {
151                 String dbResponse = execution.getVariable("dbResponse")
152                 def dbResponseJson = jsonUtil.xml2json(dbResponse) as String
153
154                 String result = jsonUtil.getJsonValue(dbResponseJson,
155                         "Envelope.Body.getServiceOperationStatusResponse.return.result")
156
157                 if (isSuccessCompleted(execution, result)) {
158
159                     handlerSuccess(execution, result)
160                     execution.setVariable("isAllFinished", "true")
161
162                     logger.debug(Prefix + "handlerServiceStatusResp: service success finished, dbResponse_result: "
163                             + result)
164
165                 } else if (isErrorCompleted(execution, result)) {
166
167                     handlerError(execution, result)
168                     execution.setVariable("isAllFinished", "true")
169
170                     logger.debug(Prefix + "handlerServiceStatusResp: service error finished, dbResponse_result: "
171                             + result)
172
173                 } else {
174                     String progress = jsonUtil.getJsonValue(dbResponseJson,
175                             "Envelope.Body.getServiceOperationStatusResponse.return.progress")
176
177                     String oldProgress = execution.getVariable("progress")
178
179                     if (progress == oldProgress) {
180                         execution.setVariable("isNeedUpdateDB", false)
181                     } else {
182                         execution.setVariable("progress", progress)
183                         execution.setVariable("isNeedUpdateDB", true)
184                     }
185                     execution.setVariable("isAllFinished", "false")
186                     TimeUnit.SECONDS.sleep(10)
187                 }
188             } else {
189                 execution.setVariable("isAllFinished", "false")
190                 //todo: retry
191                 TimeUnit.MILLISECONDS.sleep(10)
192             }
193
194         } catch (BpmnError e) {
195             throw e
196         } catch (Exception ex) {
197             msg = "Exception in " + Prefix + "handlerServiceStatusResp: " + ex.getMessage()
198             logger.debug(msg)
199             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
200         }
201
202         logger.trace(Prefix + "handlerServiceStatusResp Exit")
203     }
204
205
206     def timeWaitDelay = { DelegateExecution execution ->
207
208         Long startTime = execution.getVariable("startTime") as Long
209         Long timeOut = execution.getVariable("timeOut") as Long
210
211         timeOut = timeOut == null ? 3 * 60 * 60 * 1000 : timeOut
212
213         if (System.currentTimeMillis() - startTime > timeOut) {
214
215             handlerTimeOut(execution)
216             execution.setVariable("isTimeOut", "YES")
217
218         } else {
219             execution.setVariable("isTimeOut", "NO")
220         }
221     }
222
223
224     private handlerTimeOut = { DelegateExecution execution ->
225
226         Map<String, Object> paramMap = execution.getVariable("timeOutParamMap") as Map
227
228         handlerProcess(execution, "error", paramMap, "error", "with timeout")
229     }
230
231
232     private handlerSuccess = { DelegateExecution execution, String result ->
233
234         Map<String, Object> paramMap = execution.getVariable("successParamMap") as Map
235
236         handlerProcess(execution, result, paramMap, "deactivated", "success")
237     }
238
239
240     private handlerError = { DelegateExecution execution, String result ->
241
242         Map<String, Object> paramMap = execution.getVariable("errorParamMap") as Map
243
244         handlerProcess(execution, result, paramMap, "error", "with error")
245     }
246
247
248     private handlerProcess = { DelegateExecution execution, String result, def paramMap, def status, def msg ->
249
250         if (paramMap != null) {
251             for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
252                 execution.setVariable(entry.getKey(), entry.getValue())
253             }
254         }
255
256
257         if (isBlank(execution.getVariable("operationStatus") as String)) {
258             execution.setVariable("operationStatus", result)
259         }
260
261
262         if (isBlank(execution.getVariable("operationContent") as String)) {
263             String operationContent =  execution.getVariable("processServiceType") + " " +
264                     execution.getVariable("operationType") + " operation finished " + msg
265             execution.setVariable("operationContent", operationContent)
266         }
267
268         if (isBlank(execution.getVariable("orchestrationStatus") as String)) {
269             execution.setVariable("orchestrationStatus", status)
270         }
271
272     }
273
274
275     /**
276      * judge if the service processing success finished
277      */
278     private isSuccessCompleted = { DelegateExecution execution, String result ->
279
280         //successConditions: processing end success conditions
281         List<String> successConditions = execution.getVariable("successConditions") as List
282
283         result = result.toLowerCase()
284         if (successConditions.contains(result)) {
285             return true
286         }
287         return false
288     }
289
290
291     /**
292      * judge if the service processing error finished
293      */
294     private isErrorCompleted = { DelegateExecution execution, String result ->
295
296         //errorConditions: processing end error conditions
297         List<String> errorConditions = execution.getVariable("errorConditions") as List
298
299         result = result.toLowerCase()
300         if (errorConditions.contains(result)) {
301             return true
302         }
303         return false
304     }
305
306
307     def preUpdateOperationProgress = { DelegateExecution execution ->
308         logger.trace(Prefix + "prepareUpdateOperationStatus Start")
309
310         def progress = execution.getVariable("progress") as Integer
311         def initProgress = execution.getVariable("initProgress") as Integer
312         def endProgress = execution.getVariable("endProgress") as Integer
313
314         def resProgress = (initProgress + (endProgress - initProgress) / 100 * progress) as Integer
315
316         def operationType = execution.getVariable("operationType")
317         def operationContent =  execution.getVariable("processServiceType") + " " +
318                 operationType + " operation processing " + resProgress
319
320         // update status creating
321         OperationStatus status = new OperationStatus()
322         status.setServiceId(execution.getVariable("parentServiceInstanceId") as String)
323         status.setOperationId(execution.getVariable("parentOperationId") as String)
324         status.setOperation(operationType as String)
325         status.setResult("processing")
326         status.setProgress(resProgress as String)
327         status.setOperationContent(operationContent as String)
328         status.setUserId(execution.getVariable("globalSubscriberId") as String)
329
330         requestDBUtil.prepareUpdateOperationStatus(execution, status)
331         logger.trace(Prefix + "prepareUpdateOperationStatus Exit")
332     }
333 }