Containerization feature of SO
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / java / org / onap / so / bpmn / common / workflow / service / WorkflowProcessor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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.common.workflow.service;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.Objects;
26 import java.util.UUID;
27
28 import org.camunda.bpm.engine.RuntimeService;
29 import org.camunda.bpm.engine.runtime.ProcessInstance;
30 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
31 import org.onap.so.bpmn.common.workflow.context.WorkflowCallbackResponse;
32 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
33 import org.onap.so.logger.MsoLogger;
34 import org.slf4j.MDC;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.scheduling.annotation.Async;
37 import org.springframework.stereotype.Service;
38
39 @Service
40 public class WorkflowProcessor extends ProcessEngineAwareService {
41         
42         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, WorkflowProcessor.class);
43         
44         protected static final String logMarker = "[WRKFLOW-RESOURCE]";
45         protected static final long DEFAULT_WAIT_TIME = 30000;  //default wait time
46         
47         @Async
48         public void startProcess( String processKey, VariableMapImpl variableMap) throws InterruptedException
49         {
50                 MDC.getCopyOfContextMap();
51                 long startTime = System.currentTimeMillis();
52                 Map<String, Object> inputVariables = null;
53                 String processInstanceId = null;
54                 try {
55                         inputVariables = getInputVariables(variableMap);
56                         setLogContext(processKey, inputVariables);
57
58                         // This variable indicates that the flow was invoked asynchronously
59                         inputVariables.put("isAsyncProcess", "true");
60                         
61                         
62                         setLogContext(processKey, inputVariables);
63
64                         // Note: this creates a random businessKey if it wasn't specified.
65                         String businessKey = getBusinessKey(inputVariables);
66
67                         msoLogger.debug("***Received MSO startProcessInstanceByKey with processKey: " + processKey
68                                         + " and variables: " + inputVariables);
69
70                         RuntimeService runtimeService = getProcessEngineServices().getRuntimeService();
71                         ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, businessKey,
72                                         inputVariables);
73                         processInstanceId = processInstance.getId();
74
75                         msoLogger.debug(logMarker + "Process " + processKey + ":" + processInstanceId + " "
76                                         + (processInstance.isEnded() ? "ENDED" : "RUNNING"));
77                 } catch (Exception e) {
78
79                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
80                                         logMarker + "Error in starting the process: " + e.getMessage());
81
82                         WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse();
83                         callbackResponse.setStatusCode(500);
84                         callbackResponse.setMessage("Fail");
85                         callbackResponse.setResponse("Error occurred while executing the process: " + e);
86
87                         WorkflowContextHolder.getInstance().processCallback(processKey, processInstanceId,
88                                         getRequestId(inputVariables), callbackResponse);
89                 }
90         }
91         
92         protected static void setLogContext(String processKey,
93                         Map<String, Object> inputVariables) {
94                 MsoLogger.setServiceName("MSO." + processKey);
95                 if (inputVariables != null) {
96                         MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"mso-service-instance-id"));
97                 }
98         }
99         
100         protected static String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {
101                 if (inputVariables == null) {
102                         return "";
103                 }
104
105                 return Objects.toString(inputVariables.get(key), "N/A");
106         }
107         
108         // Note: the business key is used to identify the process in unit tests
109         protected static String getBusinessKey(Map<String, Object> inputVariables) {
110         return getOrCreate(inputVariables, "mso-business-key");
111         }
112
113         protected static String getRequestId(Map<String, Object> inputVariables) {
114         return getOrCreate(inputVariables, "mso-request-id");
115         }
116         
117         protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
118                 Map<String, Object> inputVariables = new HashMap<>();
119                 @SuppressWarnings("unchecked")
120                 Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
121                 for (Map.Entry<String, Object> entry : vMap.entrySet()) {
122                         String vName = entry.getKey();
123                         Object value = entry.getValue();
124                         @SuppressWarnings("unchecked")
125                         Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
126                         inputVariables.put(vName, valueMap.get("value"));
127                 }
128                 return inputVariables;
129         }
130         
131     protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
132         String value = Objects.toString(inputVariables.get(key), null);
133         if (value == null) {
134             value = UUID.randomUUID().toString();
135             inputVariables.put(key, value);
136         }
137         return value;
138     }
139     
140         protected long getWaitTime(Map<String, Object> inputVariables)
141         {
142             
143                 String timeout = Objects.toString(inputVariables.get("mso-service-request-timeout"), null);
144
145                 if (timeout != null) {
146                         try {
147                                 return Long.parseLong(timeout)*1000;
148                         } catch (NumberFormatException nex) {
149                                 msoLogger.debug("Invalid input for mso-service-request-timeout");
150                         }
151                 }
152
153                 return DEFAULT_WAIT_TIME;
154         }
155 }