aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/SDNCAdapterCallbackServiceImpl.java
blob: 4585d620ac7433758b209fa75e76d61afba32c9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*-
 * ============LICENSE_START=======================================================
 * OPENECOMP - MSO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.mso.bpmn.common.workflow.service;

import java.util.HashMap;
import java.util.Map;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.ws.rs.core.Context;
import javax.xml.ws.WebServiceContext;

import org.camunda.bpm.BpmPlatform;
import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
import org.camunda.bpm.engine.ProcessEngineServices;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.ExecutionQuery;
import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest;
import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse;
import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCCallbackAdapterPortType;
import org.openecomp.mso.bpmn.core.PropertyConfiguration;
import org.openecomp.mso.logger.MessageEnum;
import org.openecomp.mso.logger.MsoLogger;
/**
 * @version 1.0
 *  
 */
@WebService(serviceName="SDNCAdapterCallbackService", targetNamespace="http://org.openecomp/workflow/sdnc/adapter/schema/v1")
public class SDNCAdapterCallbackServiceImpl implements SDNCCallbackAdapterPortType {

	private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
	private final int DEFAULT_RETRY_ATTEMPTS = 60;
	private final int DEFAULT_SLEEP_TIME = 500;

	private final String logMarker = "[SDNC-CALLBACK]";

	@Context WebServiceContext wsContext;

	private volatile ProcessEngineServices pes4junit = null;

	@WebMethod(operationName = "SDNCAdapterCallback")
    @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse")
    public SDNCAdapterResponse sdncAdapterCallback(
            @WebParam(name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackRequest")
            SDNCAdapterCallbackRequest sdncAdapterCallbackRequest) {

		//Callback URL to use http://localhost:28080/mso/SDNCAdapterCallbackService
		ProcessEngineServices pes = getProcessEngineServices();
		RuntimeService runtimeService = pes.getRuntimeService();
		String receivedRequestId = sdncAdapterCallbackRequest.getCallbackHeader().getRequestId();
		MsoLogger.setServiceName("MSO." + "sdncAdapter");
		MsoLogger.setLogContext(receivedRequestId, "N/A");
		msoLogger.debug(logMarker + "Received callback response:" + sdncAdapterCallbackRequest.toString());
		SDNCAdapterResponse sdncAdapterResponse;
		long startTime = System.currentTimeMillis();

		/*Correlating the response with the running instance*/

		// NOTE: the following loop is a workaround for problems we've had
		// with reliability of the runtime service.  It seems that queries
		// sometimes return results, and sometimes they don't.  This might
		// be a problem in mysql only.  We aren't sure if it affects camunda
		// on oracle or mariadb.  The workaround is to repeat the request
		// a number of times until it succeeds.  If it doesn't succeed after
		// 60 tries, then we give up.

		int maxAttempts = DEFAULT_RETRY_ATTEMPTS;
		int attempt = 1;
		int sleepTime = DEFAULT_SLEEP_TIME;

		Map<String,String> bpmnProperties = getMSOBPMNURNProperties();
		if (bpmnProperties != null) {
			try {
				maxAttempts = Integer.parseInt(bpmnProperties.get("mso.callbackRetryAttempts"));
				msoLogger.debug(logMarker + "mso.callbackRetryAttempts=" + maxAttempts);
				sleepTime = Integer.parseInt(bpmnProperties.get("mso.callbackRetrySleepTime"));
				msoLogger.debug(logMarker + "mso.callbackRetrySleepTime:" + sleepTime);
			} catch (Exception ex) {
				
			msoLogger.debug (logMarker 						
						+ "Error parsing mso.callbackRetrySleepTime/mso.callbackRetryAttempts:" 
						+ sleepTime + ":" 
						+ maxAttempts);
				
			}
		}

		/* Check to make sure the process instance is reay for correlation*/
		try{
			isReadyforCorrelation(runtimeService, receivedRequestId, maxAttempts, sleepTime );
		}catch(Exception e){
			String msg =
				"SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '"
						+ receivedRequestId
						+ "' but that RequestId doesn't exist or has timed out waiting for the callback";
			sdncAdapterResponse = new SDNCAdapterExceptionResponse(e);
			
			msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), 
					MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e);
			
			msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker 
					+ "Completed the execution of MSO SDNCAdapterCallbackService." );
			
			msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
					logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", 
					MsoLogger.getServiceName(), "sdncAdapterCallback");
			
			return sdncAdapterResponse;
		}

		msoLogger.debug(logMarker + "*** Received MSO sdncAdapterCallbackService ******");
		
		msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Call to MSO sdncAdapterCallbackService");		
		
		msoLogger.debug(logMarker + "Callback response string:\n"  + sdncAdapterCallbackRequest.toString());

		String reqId = receivedRequestId;
		Map<String,Object> variables = new HashMap<String,Object>();
		variables.put("SDNCA_requestId", reqId );
		variables.put("sdncAdapterCallbackRequest", sdncAdapterCallbackRequest.toString());
		while (true) {
			try {
				// sdncAdapterCallbackRequest is the message event name (defined in the bpmn process)
				runtimeService.createMessageCorrelation("sdncAdapterCallbackRequest")
					.setVariables(variables)
					.processInstanceVariableEquals("SDNCA_requestId", reqId).correlate();
				sdncAdapterResponse = new SDNCAdapterResponse();
				msoLogger.debug(logMarker + "***** Completed processing of MSO sdncAdapterCallbackService ******");
				
				msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker 
						+ "Completed the execution of MSO SDNCAdapterCallbackService.");
				
				msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
						logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", 
						MsoLogger.getServiceName(), "sdncAdapterCallback");
				
				return sdncAdapterResponse;
			} catch(MismatchingMessageCorrelationException e) {
				msoLogger.debug(logMarker + "[CORM]correlation id mismatch (attempt " + attempt + "/" + maxAttempts + ")");
				if (attempt == maxAttempts) {
					// Couldn't correlate requestId to any active flow
					//MsoLogger logger = MsoLogger.getMsoLogger("SDNCAdapterCallbackService");
					String msg =
						"SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '"
								+ receivedRequestId
								+ "' but that RequestId could not be correlated to any active process - ignoring the Request";
					sdncAdapterResponse = new SDNCAdapterExceptionResponse(e);
					
					msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), 
							MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e);
					
					msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker 
							+ "Completed the execution of MSO SDNCAdapterCallbackService." );
					
					msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
							logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", 
							MsoLogger.getServiceName(), "sdncAdapterCallback");
					
					return sdncAdapterResponse;
				}

				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException e2) {
					String msg =
						"SDNC Adapter Callback Service received a SDNC Adapter Callback Request with RequestId '"
								+ receivedRequestId
								+ "' but correlation was interrupted";
					sdncAdapterResponse = new SDNCAdapterExceptionResponse(e);
					
					msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), 
							MsoLogger.ErrorCode.UnknownError, logMarker + ":" + msg, e);
					
					msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, logMarker 
							+ "Completed the execution of MSO SDNCAdapterCallbackService.");
					
					msoLogger.recordMetricEvent ( startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, 
							logMarker + "Completed the execution of MSO SDNCAdapterCallbackService.", "BPMN", 
							MsoLogger.getServiceName(), "sdncAdapterCallback");
					
					return sdncAdapterResponse;
				}
			}

			attempt++;
		}
	}


	private Map<String,String> getMSOBPMNURNProperties() {
		PropertyConfiguration propertyConfiguration = PropertyConfiguration.getInstance();
		Map<String,String> props = propertyConfiguration.getProperties("mso.bpmn.urn.properties");
		return props;
	}

	private void isReadyforCorrelation(RuntimeService runtimeService,
			String receivedRequestId, int retries, int sleepTime){
		ExecutionQuery waitingInstances = null;
		long waitingInstancesCount = 0;

		//Workaround for performance testing, explicit wait for a second for the transactions to be committed
		//Also check to make sure the process didn't timeout before trying to correlate
		
		do{
		  waitingInstances = runtimeService.createExecutionQuery() //
					.messageEventSubscriptionName("sdncAdapterCallbackRequest")
					.processVariableValueEquals("SDNCA_requestId", receivedRequestId);
		  waitingInstancesCount = waitingInstances.count();
		  retries--;
		  msoLogger.debug(logMarker + "waitingInstancesCount: " + waitingInstancesCount);
		  try {
				Thread.sleep(sleepTime);
			  } catch (InterruptedException e) {
				
				msoLogger.error (MessageEnum.BPMN_SDNC_CALLBACK_EXCEPTION, "BPMN", MsoLogger.getServiceName(), 
						MsoLogger.ErrorCode.UnknownError, logMarker, e);
				
			  }
		}while (waitingInstancesCount==0 && retries > 0); 
		if(waitingInstancesCount > 0){
			msoLogger.debug(logMarker + "waitingInstancesCount before timeout check: " + waitingInstancesCount);
			waitingInstancesCount = waitingInstances.processVariableValueEquals("asynchronousResponseTimeout", false).count();
			msoLogger.debug(logMarker + "waitingInstancesCount after timeout check: " + waitingInstancesCount);
			if(waitingInstancesCount<=0){
				msoLogger.debug(logMarker + "detected timeout on flow to correlate");
				throw new IllegalStateException("process timed out");
			}
		}else{
			//flow may have already ended, so can't check timeout variable. Throw exception?
			msoLogger.debug(logMarker + "no flow to correlate to");
			throw new IllegalStateException("no flow to correlate to");
		}
	}

	private ProcessEngineServices getProcessEngineServices() {
		if (pes4junit == null) {
			return BpmPlatform.getDefaultProcessEngine();
		} else {
			return pes4junit;
		}
	}

	@WebMethod(exclude=true)
	public void setProcessEngineServices4junit(ProcessEngineServices pes) {
		pes4junit = pes;
	}

	public class SDNCAdapterExceptionResponse extends SDNCAdapterResponse {
		private Exception ex;

		public SDNCAdapterExceptionResponse(Exception ex) {
			super();
			this.ex = ex;
		}

		public Exception getException() {
			return ex;
		}
	}
}