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