cfd07d8c391a4533bd8c7efeb120b94b8c9b924a
[so.git] /
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.Optional;
27 import java.util.UUID;
28
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.POST;
31 import javax.ws.rs.Path;
32 import javax.ws.rs.PathParam;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.ext.Provider;
36
37 import org.camunda.bpm.engine.ProcessEngineServices;
38 import org.camunda.bpm.engine.variable.impl.VariableMapImpl;
39 import org.onap.so.bpmn.common.workflow.context.WorkflowContext;
40 import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder;
41 import org.onap.so.bpmn.common.workflow.context.WorkflowResponse;
42 import org.onap.so.logger.MsoLogger;
43 import org.slf4j.MDC;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
46
47 import io.swagger.annotations.Api;
48 import io.swagger.annotations.ApiOperation;
49
50
51 /**
52  * 
53  * @version 1.0
54  * Asynchronous Workflow processing using JAX RS RESTeasy implementation
55  * Both Synchronous and Asynchronous BPMN process can benefit from this implementation since the workflow gets executed in the background
56  * and the server thread is freed up, server scales better to process more incoming requests
57  * 
58  * Usage: For synchronous process, when you are ready to send the response invoke the callback to write the response
59  * For asynchronous process - the activity may send a acknowledgement response and then proceed further on executing the process
60  */
61 @Path("/async")
62 @Api(value = "/async", description = "Provides asynchronous starting of a bpmn process")
63 @Provider
64 @Component
65 public class WorkflowAsyncResource extends ProcessEngineAwareService {
66
67         private static final WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance();
68         
69         
70         protected Optional<ProcessEngineServices> pes4junit = Optional.empty();
71         
72         long workflowPollInterval=1000; 
73
74         @Autowired
75         private WorkflowProcessor processor;
76         
77         @Autowired
78         private WorkflowContextHolder workflowContext;
79         
80         public WorkflowProcessor getProcessor() {
81                 return processor;
82         }
83
84
85
86         public void setProcessor(WorkflowProcessor processor) {
87                 this.processor = processor;
88         }
89
90         protected static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL,WorkflowAsyncResource.class);
91         protected static final long DEFAULT_WAIT_TIME = 60000;  //default wait time
92         
93         /**
94          * Asynchronous JAX-RS method that starts a process instance.
95          * @param asyncResponse an object that will receive the asynchronous response
96          * @param processKey the process key
97          * @param variableMap input variables to the process
98          * @return 
99          */
100         
101         @POST
102         @Path("/services/{processKey}")
103         @ApiOperation(
104                         value = "Starts a new process with the appropriate process Key",
105                         notes = "Aysnc fall outs are only logged"
106                     )
107         @Produces("application/json")
108         @Consumes("application/json")
109         public Response startProcessInstanceByKey (
110                         @PathParam("processKey") String processKey, VariableMapImpl variableMap){
111                 Map<String, Object> inputVariables = getInputVariables(variableMap);    
112                 try {           
113                         MDC.put(MsoLogger.REQUEST_ID, getRequestId(inputVariables));
114                         processor.startProcess(processKey, variableMap);
115                         WorkflowResponse response = waitForResponse(getRequestId(inputVariables)); 
116                         return Response.status(202).entity(response).build();   
117                 } catch (Exception e) {
118                         WorkflowResponse response =  buildUnkownError(getRequestId(inputVariables),e.getMessage());             
119                         return Response.status(500).entity(response).build();   
120                 }               
121         }
122         
123         private WorkflowResponse waitForResponse(String requestId) throws Exception {           
124                 long currentWaitTime = 0;               
125                 while (DEFAULT_WAIT_TIME > currentWaitTime ) {                  
126                         Thread.sleep(workflowPollInterval);
127                         currentWaitTime = currentWaitTime + workflowPollInterval;
128                         WorkflowContext foundContext = contextHolder.getWorkflowContext(requestId);
129                         if(foundContext!=null){
130                                 contextHolder.remove(foundContext);
131                                 return buildResponse(foundContext);
132                         }
133                 }
134                 throw new Exception("TimeOutOccured");
135         }
136
137         private WorkflowResponse buildTimeoutResponse(String requestId) {
138                 WorkflowResponse response = new WorkflowResponse();
139                 response.setMessage("Fail");
140                 response.setResponse("Request timedout, request id:" + requestId);              
141                 response.setMessageCode(500);
142                 return response;
143         }
144         
145         private WorkflowResponse buildUnkownError(String requestId,String error) {
146                 WorkflowResponse response = new WorkflowResponse();
147                 response.setMessage(error);
148                 response.setResponse("UnknownError, request id:" + requestId);          
149                 response.setMessageCode(500);
150                 return response;
151         }
152
153         private WorkflowResponse buildResponse(WorkflowContext foundContext) {
154                 return foundContext.getWorkflowResponse();
155         }
156         
157     protected static String getOrCreate(Map<String, Object> inputVariables, String key) {
158         String value = Objects.toString(inputVariables.get(key), null);
159         if (value == null) {
160             value = UUID.randomUUID().toString();
161             inputVariables.put(key, value);
162         }
163         return value;
164     }
165         
166         // Note: the business key is used to identify the process in unit tests
167         protected static String getBusinessKey(Map<String, Object> inputVariables) {
168         return getOrCreate(inputVariables, "mso-business-key");
169         }
170
171         protected static String getRequestId(Map<String, Object> inputVariables) {
172         return getOrCreate(inputVariables, "mso-request-id");
173         }
174
175
176         
177         protected void recordEvents(String processKey, WorkflowResponse response,
178                         long startTime) {
179                 
180                 msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
181                                 response.getMessage() + " for processKey: "
182                                 + processKey + " with response: " + response.getResponse(), "BPMN", MDC.get(processKey), null);
183                 
184                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
185                                  response.getMessage() + "for processKey: " + processKey + " with response: " + response.getResponse());
186                 
187         }
188
189         protected static void setLogContext(String processKey,
190                         Map<String, Object> inputVariables) {
191                 MsoLogger.setServiceName("MSO." + processKey);
192                 if (inputVariables != null) {
193                         MsoLogger.setLogContext(getKeyValueFromInputVariables(inputVariables,"mso-request-id"), getKeyValueFromInputVariables(inputVariables,"serviceInstanceId"));
194                 }
195         }
196
197         protected static String getKeyValueFromInputVariables(Map<String,Object> inputVariables, String key) {
198                 if (inputVariables == null) {
199                         return "";
200                 }
201
202                 return Objects.toString(inputVariables.get(key), "N/A");
203         }
204
205         protected boolean isProcessEnded(String processInstanceId) {
206                 ProcessEngineServices pes = getProcessEngineServices();
207                 return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
208         }
209         
210         protected static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
211                 Map<String, Object> inputVariables = new HashMap<>();
212                 @SuppressWarnings("unchecked")
213                 Map<String, Object> vMap = (Map<String, Object>) variableMap.get("variables");
214                 for (Map.Entry<String, Object> entry : vMap.entrySet()) {
215                         String vName = entry.getKey();
216                         Object value = entry.getValue();
217                         @SuppressWarnings("unchecked")
218                         Map<String, Object> valueMap = (Map<String,Object>)value; // value, type
219                         inputVariables.put(vName, valueMap.get("value"));
220                 }
221                 return inputVariables;
222         }
223         
224     
225         protected long getWaitTime(Map<String, Object> inputVariables)
226         {
227             
228                 String timeout = Objects.toString(inputVariables.get("mso-service-request-timeout"), null);
229
230                 if (timeout != null) {
231                         try {
232                                 return Long.parseLong(timeout)*1000;
233                         } catch (NumberFormatException nex) {
234                                 msoLogger.debug("Invalid input for mso-service-request-timeout");
235                         }
236                 }
237
238                 return DEFAULT_WAIT_TIME;
239         }
240         
241         
242         
243
244 }