-
Notifications
You must be signed in to change notification settings - Fork 29
/
OptimizedMultiThreadedDataFlowExecutor.java
314 lines (279 loc) · 15.2 KB
/
OptimizedMultiThreadedDataFlowExecutor.java
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package com.flipkart.databuilderframework.engine;
import com.flipkart.databuilderframework.model.*;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
/**
* The executor for a {@link com.flipkart.databuilderframework.model.DataFlow}.
*/
public class OptimizedMultiThreadedDataFlowExecutor extends DataFlowExecutor {
private static final Logger logger = LoggerFactory.getLogger(OptimizedMultiThreadedDataFlowExecutor.class.getSimpleName());
private final ExecutorService executorService;
public OptimizedMultiThreadedDataFlowExecutor(ExecutorService executorService) {
this.executorService = executorService;
}
public OptimizedMultiThreadedDataFlowExecutor(DataBuilderFactory dataBuilderFactory, ExecutorService executorService) {
super(dataBuilderFactory);
this.executorService = executorService;
}
/**
* {@inheritDoc}
*/
@Override
protected DataExecutionResponse run(DataBuilderContext dataBuilderContext,
DataFlowInstance dataFlowInstance,
DataDelta dataDelta,
DataFlow dataFlow,
DataBuilderFactory builderFactory) throws DataBuilderFrameworkException, DataValidationException {
CompletionService<DataContainer> completionExecutor = new ExecutorCompletionService<DataContainer>(executorService);
ExecutionGraph executionGraph = dataFlow.getExecutionGraph();
DataSet dataSet = dataFlowInstance.getDataSet().accessor().copy(); //Create own copy to work with
DataSetAccessor dataSetAccessor = DataSet.accessor(dataSet);
dataSetAccessor.merge(dataDelta);
Map<String, Data> responseData = Maps.newTreeMap();
Set<String> activeDataSet = Sets.newHashSet();
for (Data data : dataDelta.getDelta()) {
activeDataSet.add(data.getData());
}
List<List<DataBuilderMeta>> dependencyHierarchy = executionGraph.getDependencyHierarchy();
Set<String> newlyGeneratedData = Sets.newHashSet();
Set<DataBuilderMeta> processedBuilders = Collections.synchronizedSet(Sets.<DataBuilderMeta>newHashSet());
while(true) {
for (List<DataBuilderMeta> levelBuilders : dependencyHierarchy) {
List<Future<DataContainer>> dataFutures = Lists.newArrayList();
BuilderRunner singleRef = null; //refrence to builderRunner when size of levelBuilders == 1 to avoid running it behind thread
for (DataBuilderMeta builderMeta : levelBuilders) {
if (processedBuilders.contains(builderMeta)) {
continue;
}
//If there is an intersection, means some of it's inputs have changed. Reevaluate
if (Sets.intersection(builderMeta.getEffectiveConsumes(), activeDataSet).isEmpty()) {
continue;
}
DataBuilder builder = builderFactory.create(builderMeta);
if (!dataSetAccessor.checkForData(builder.getDataBuilderMeta().getConsumes())) {
continue;
}
BuilderRunner builderRunner = new BuilderRunner(dataBuilderExecutionListener, dataFlowInstance,
builderMeta, dataDelta, responseData,
builder, dataBuilderContext, processedBuilders, dataSet);
if(levelBuilders.size() == 1){
singleRef = builderRunner;
}else{
Future<DataContainer> future = completionExecutor.submit(builderRunner);
dataFutures.add(future);
}
}
//Now wait for something to complete.
int listSize = dataFutures.size();
for(int i = 0; i < listSize || singleRef != null; i++) { //listSize == 0 when singleRef is present, or condition allows this logic to run once
try {
DataContainer responseContainer = null;
if(singleRef != null){
try {
responseContainer = singleRef.call();
} catch (Exception e) {
throw new ExecutionException(e); //to map this to existing exception handling
}finally{
singleRef = null; // make this null to avoid loopback hell
}
}else{
responseContainer = completionExecutor.take().get();
}
Data response = responseContainer.getGeneratedData();
String data = responseContainer.getBuilderMeta().getProduces();
if(responseContainer.isHasError()) {
if(null != responseContainer.getValidationException()) {
throw responseContainer.getValidationException();
}
throw responseContainer.getException();
}
if (null != response) {
Preconditions.checkArgument(response.getData().equalsIgnoreCase(data),
"Builder is supposed to produce %s but produces %s",
data, response.getData());
dataSetAccessor.merge(response);
responseData.put(response.getData(), response);
activeDataSet.add(response.getData());
if(null != dataFlow.getTransients() && !dataFlow.getTransients().contains(response.getData())) {
newlyGeneratedData.add(response.getData());
}
}
}
catch (InterruptedException e) {
throw new DataBuilderFrameworkException(DataBuilderFrameworkException.ErrorCode.BUILDER_EXECUTION_ERROR,
"Error while waiting for error ", e);
} catch (ExecutionException e) {
throw new DataBuilderFrameworkException(DataBuilderFrameworkException.ErrorCode.BUILDER_EXECUTION_ERROR,
"Error while waiting for error ", e.getCause());
}
}
}
if(newlyGeneratedData.contains(dataFlow.getTargetData())) {
//logger.debug("Finished running this instance of the flow. Exiting.");
break;
}
if(newlyGeneratedData.isEmpty()) {
//logger.debug("Nothing happened in this loop, exiting..");
break;
}
// StringBuilder stringBuilder = new StringBuilder();
// for(String data : newlyGeneratedData) {
// stringBuilder.append(data + ", ");
// }
//logger.info("Newly generated: " + stringBuilder);
activeDataSet.clear();
activeDataSet.addAll(newlyGeneratedData);
newlyGeneratedData.clear();
if(!dataFlow.isLoopingEnabled()) {
break;
}
}
DataSet finalDataSet = dataSetAccessor.copy(dataFlow.getTransients());
dataFlowInstance.setDataSet(finalDataSet);
return new DataExecutionResponse(responseData);
}
private static final class DataContainer {
private final DataBuilderMeta builderMeta;
private final Data generatedData;
private boolean hasError = false;
private final DataBuilderFrameworkException exception;
private final DataValidationException validationException;
private DataContainer(DataBuilderMeta builderMeta, Data generatedData) {
this.builderMeta = builderMeta;
this.generatedData = generatedData;
this.exception = null;
this.validationException = null;
}
private DataContainer(DataBuilderMeta builderMeta, DataBuilderFrameworkException exception) {
this.builderMeta = builderMeta;
this.generatedData = null;
this.hasError = true;
this.exception = exception;
this.validationException = null;
}
private DataContainer(DataBuilderMeta builderMeta, DataValidationException validationException) {
this.builderMeta = builderMeta;
this.generatedData = null;
this.hasError = true;
this.exception = null;
this.validationException = validationException;
}
public DataBuilderMeta getBuilderMeta() {
return builderMeta;
}
public Data getGeneratedData() {
return generatedData;
}
public DataBuilderFrameworkException getException() {
return exception;
}
public DataValidationException getValidationException() {
return validationException;
}
public boolean isHasError() {
return hasError;
}
}
private static final class BuilderRunner implements Callable<DataContainer> {
private List<DataBuilderExecutionListener> dataBuilderExecutionListener;
private DataFlowInstance dataFlowInstance;
private DataBuilderMeta builderMeta;
private DataDelta dataDelta;
private Map<String,Data> responseData;
private DataBuilder builder;
private DataBuilderContext dataBuilderContext;
private final Set<DataBuilderMeta> procesedBuilders;
private DataSet dataSet;
private BuilderRunner(List<DataBuilderExecutionListener> dataBuilderExecutionListener,
DataFlowInstance dataFlowInstance,
DataBuilderMeta builderMeta,
DataDelta dataDelta,
Map<String, Data> responseData,
DataBuilder builder,
DataBuilderContext dataBuilderContext,
Set<DataBuilderMeta> procesedBuilders,
DataSet dataSet) {
this.dataBuilderExecutionListener = dataBuilderExecutionListener;
this.dataFlowInstance = dataFlowInstance;
this.builderMeta = builderMeta;
this.dataDelta = dataDelta;
this.responseData = responseData;
this.builder = builder;
this.dataBuilderContext = dataBuilderContext;
this.procesedBuilders = procesedBuilders;
this.dataSet = dataSet;
}
@Override
public DataContainer call() throws Exception {
for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
try {
listener.beforeExecute(dataBuilderContext, dataFlowInstance, builderMeta, dataDelta, responseData);
} catch (Throwable t) {
logger.error("Error running pre-execution execution listener: ", t);
}
}
try {
Data response = builder.process(dataBuilderContext.immutableCopy(
dataSet.accessor().getAccesibleDataSetFor(builder)));
//logger.debug("Ran " + builderMeta.getName());
procesedBuilders.add(builderMeta);
for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
try {
listener.afterExecute(dataBuilderContext, dataFlowInstance, builderMeta, dataDelta, responseData, response);
} catch (Throwable t) {
logger.error("Error running post-execution listener: ", t);
}
}
if(null != response) {
Preconditions.checkArgument(response.getData().equalsIgnoreCase(builderMeta.getProduces()),
"Builder is supposed to produce %s but produces %s",
builderMeta.getProduces(), response.getData());
response.setGeneratedBy(builderMeta.getName());
}
return new DataContainer(builderMeta, response);
} catch (DataBuilderException e) {
logger.error("Error running builder: " + builderMeta.getName());
for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
try {
listener.afterException(dataBuilderContext, dataFlowInstance, builderMeta, dataDelta, responseData, e);
} catch (Throwable error) {
logger.error("Error running post-execution listener: ", error);
}
}
return new DataContainer(builderMeta, new DataBuilderFrameworkException(DataBuilderFrameworkException.ErrorCode.BUILDER_EXECUTION_ERROR,
"Error running builder: " + builderMeta.getName(), e.getDetails(), e));
} catch (DataValidationException e) {
logger.error("Validation error in data produced by builder" +builderMeta.getName());
for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
try {
listener.afterException(dataBuilderContext, dataFlowInstance, builderMeta, dataDelta, responseData, e);
} catch (Throwable error) {
logger.error("Error running post-execution listener: ", error);
}
}
return new DataContainer(builderMeta, new DataValidationException(DataValidationException.ErrorCode.DATA_VALIDATION_EXCEPTION,
"Error running builder: " + builderMeta.getName(), new DataExecutionResponse(responseData), e.getDetails(), e));
}
catch (Throwable t) {
logger.error("Error running builder: " + builderMeta.getName());
for (DataBuilderExecutionListener listener : dataBuilderExecutionListener) {
try {
listener.afterException(dataBuilderContext, dataFlowInstance, builderMeta, dataDelta, responseData, t);
} catch (Throwable error) {
logger.error("Error running post-execution listener: ", error);
}
}
Map<String, Object> objectMap = new HashMap<String, Object>();
objectMap.put("MESSAGE", t.getMessage());
return new DataContainer(builderMeta, new DataBuilderFrameworkException(DataBuilderFrameworkException.ErrorCode.BUILDER_EXECUTION_ERROR,
"Error running builder: " + builderMeta.getName() + t.getMessage(), objectMap, t));
}
}
}
}