-
Notifications
You must be signed in to change notification settings - Fork 13
/
LocalExecutionMonitor.java
executable file
·547 lines (508 loc) · 19.6 KB
/
LocalExecutionMonitor.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
package org.apache.taverna.platform.execution.impl.local;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Logger;
import org.apache.taverna.facade.ResultListener;
import org.apache.taverna.invocation.InvocationContext;
import org.apache.taverna.invocation.WorkflowDataToken;
import org.apache.taverna.lang.observer.Observable;
import org.apache.taverna.lang.observer.Observer;
import org.apache.taverna.monitor.MonitorManager.AddPropertiesMessage;
import org.apache.taverna.monitor.MonitorManager.DeregisterNodeMessage;
import org.apache.taverna.monitor.MonitorManager.MonitorMessage;
import org.apache.taverna.monitor.MonitorManager.RegisterNodeMessage;
import org.apache.taverna.monitor.MonitorableProperty;
import org.apache.taverna.reference.ErrorDocument;
import org.apache.taverna.reference.ExternalReferenceSPI;
import org.apache.taverna.reference.IdentifiedList;
import org.apache.taverna.reference.ReferenceService;
import org.apache.taverna.reference.ReferenceServiceException;
import org.apache.taverna.reference.ReferenceSet;
import org.apache.taverna.reference.StackTraceElementBean;
import org.apache.taverna.reference.T2Reference;
import org.apache.taverna.reference.T2ReferenceType;
import org.apache.taverna.reference.impl.external.file.FileReference;
import org.apache.taverna.reference.impl.external.http.HttpReference;
import org.apache.taverna.workflowmodel.Dataflow;
import org.apache.taverna.workflowmodel.DataflowOutputPort;
import org.apache.taverna.workflowmodel.Processor;
import org.apache.taverna.workflowmodel.processor.activity.Activity;
import org.apache.taverna.workflowmodel.processor.dispatch.events.DispatchJobEvent;
import org.apache.taverna.workflowmodel.processor.dispatch.events.DispatchResultEvent;
import org.apache.taverna.robundle.Bundle;
import org.apache.taverna.databundle.DataBundles;
import org.apache.taverna.platform.execution.api.InvalidWorkflowException;
import org.apache.taverna.platform.report.ActivityReport;
import org.apache.taverna.platform.report.Invocation;
import org.apache.taverna.platform.report.ProcessorReport;
import org.apache.taverna.platform.report.StatusReport;
import org.apache.taverna.platform.report.WorkflowReport;
/**
* A workflow monitor for local executions.
*
* @author David Withers
*/
public class LocalExecutionMonitor implements Observer<MonitorMessage> {
private static final Logger logger = Logger
.getLogger(LocalExecutionMonitor.class.getName());
private static final String ID_SEPARATOR = "/";
private Map<String, StatusReport<?, ?>> reports;
private Map<String, Invocation> invocations;
private Map<String, String> invocationToActivity;
private Map<T2Reference, Path> referenceToPath;
private final String facadeId;
private final Bundle dataBundle;
public LocalExecutionMonitor(WorkflowReport workflowReport,
Bundle dataBundle, WorkflowToDataflowMapper mapping, String facadeId)
throws InvalidWorkflowException {
this.dataBundle = dataBundle;
this.facadeId = facadeId;
reports = new HashMap<>();
invocations = new HashMap<>();
invocationToActivity = new HashMap<>();
referenceToPath = new HashMap<>();
mapReports("", workflowReport, mapping);
}
private void mapReports(String id, WorkflowReport workflowReport,
WorkflowToDataflowMapper mapping) throws InvalidWorkflowException {
Dataflow dataflow = mapping.getDataflow(workflowReport.getSubject());
String dataflowId = null;
if (id.isEmpty()) {
dataflowId = dataflow.getLocalName();
} else {
dataflowId = id + ID_SEPARATOR + dataflow.getLocalName();
}
reports.put(dataflowId, workflowReport);
for (ProcessorReport processorReport : workflowReport
.getProcessorReports()) {
Processor processor = mapping.getDataflowProcessor(processorReport
.getSubject());
String processorId = dataflowId + ID_SEPARATOR
+ processor.getLocalName();
reports.put(processorId, (LocalProcessorReport) processorReport);
for (ActivityReport activityReport : processorReport
.getActivityReports()) {
Activity<?> activity = mapping
.getDataflowActivity(activityReport.getSubject());
String activityId = processorId + ID_SEPARATOR
+ activity.hashCode();
reports.put(activityId, activityReport);
WorkflowReport nestedWorkflowReport = activityReport
.getNestedWorkflowReport();
if (nestedWorkflowReport != null)
mapReports(activityId, nestedWorkflowReport, mapping);
}
}
}
@Override
public void notify(Observable<MonitorMessage> sender, MonitorMessage message)
throws Exception {
String[] owningProcess = message.getOwningProcess();
if (owningProcess.length > 0 && owningProcess[0].equals(facadeId)) {
if (message instanceof RegisterNodeMessage) {
RegisterNodeMessage regMessage = (RegisterNodeMessage) message;
registerNode(regMessage.getWorkflowObject(), owningProcess,
regMessage.getProperties());
} else if (message instanceof DeregisterNodeMessage) {
deregisterNode(owningProcess);
} else if (message instanceof AddPropertiesMessage) {
AddPropertiesMessage addMessage = (AddPropertiesMessage) message;
addPropertiesToNode(owningProcess,
addMessage.getNewProperties());
} else {
logger.warning("Unknown message " + message + " from " + sender);
}
}
}
public void registerNode(Object dataflowObject, String[] owningProcess,
Set<MonitorableProperty<?>> properties) {
if (dataflowObject instanceof Dataflow) {
Dataflow dataflow = (Dataflow) dataflowObject;
Invocation parentInvocation = invocations
.get(getParentInvocationId(owningProcess));
WorkflowReport report = (WorkflowReport) reports
.get(getReportId(owningProcess));
report.setStartedDate(new Date());
Invocation invocation = new Invocation(
getInvocationName(owningProcess), parentInvocation, report);
if (parentInvocation == null) {
if (DataBundles.hasInputs(dataBundle)) {
try {
invocation.setInputs(DataBundles.getPorts(DataBundles
.getInputs(dataBundle)));
} catch (IOException e) {
logger.log(WARNING, "Error setting input ports", e);
}
}
try {
Path outputs = DataBundles.getOutputs(dataBundle);
DataflowResultListener dataflowResultListener = new DataflowResultListener(
outputs);
for (DataflowOutputPort dataflowOutputPort : dataflow
.getOutputPorts()) {
String portName = dataflowOutputPort.getName();
Path portPath = DataBundles.getPort(outputs, portName);
invocation.setOutput(portName, portPath);
dataflowOutputPort
.addResultListener(dataflowResultListener);
}
} catch (IOException e) {
logger.log(WARNING, "Error setting output ports", e);
}
invocations.put(getInvocationId(owningProcess), invocation);
} else {
invocation.setInputs(parentInvocation.getInputs());
NestedDataflowResultListener resultListener = new NestedDataflowResultListener(
invocation);
for (DataflowOutputPort dataflowOutputPort : dataflow
.getOutputPorts()) {
dataflowOutputPort.addResultListener(resultListener);
}
invocations.put(getInvocationId(owningProcess), invocation);
}
} else if (dataflowObject instanceof Processor) {
StatusReport<?, ?> report = reports.get(getReportId(owningProcess));
report.setStartedDate(new Date());
if (report instanceof LocalProcessorReport)
((LocalProcessorReport) report).addProperties(properties);
} else if (dataflowObject instanceof Activity) {
Activity<?> activity = (Activity<?>) dataflowObject;
invocationToActivity.put(owningProcess[owningProcess.length - 1],
String.valueOf(activity.hashCode()));
} else if (dataflowObject instanceof DispatchJobEvent) {
DispatchJobEvent jobEvent = (DispatchJobEvent) dataflowObject;
StatusReport<?, ?> report = reports.get(getReportId(owningProcess));
// create a new invocation
Invocation parentInvocation;
Invocation invocation;
if (report instanceof ActivityReport) {
parentInvocation = invocations
.get(getParentInvocationId(owningProcess)
+ indexToString(jobEvent.getIndex()));
invocation = new Invocation(getInvocationName(owningProcess),
jobEvent.getIndex(), parentInvocation, report);
invocations.put(getInvocationId(owningProcess), invocation);
} else {
parentInvocation = invocations
.get(getParentInvocationId(owningProcess));
invocation = new Invocation(getInvocationName(owningProcess)
+ indexToString(jobEvent.getIndex()),
jobEvent.getIndex(), parentInvocation, report);
invocations.put(getInvocationId(owningProcess)
+ indexToString(jobEvent.getIndex()), invocation);
}
// set the invocation inputs
try {
for (Entry<String, T2Reference> inputInfo : jobEvent.getData()
.entrySet()) {
invocation.setInput(
inputInfo.getKey(),
getIntermediate(inputInfo.getValue(),
jobEvent.getContext()));
}
} catch (IOException | URISyntaxException e) {
logger.log(WARNING, "Error saving intermediate inputs for "
+ jobEvent.getOwningProcess(), e);
}
} else if (dataflowObject instanceof DispatchResultEvent) {
DispatchResultEvent resultEvent = (DispatchResultEvent) dataflowObject;
StatusReport<?, ?> report = reports.get(getReportId(owningProcess));
// find the invocation
Invocation invocation;
if (report instanceof ActivityReport)
invocation = invocations.remove(getInvocationId(owningProcess));
else
invocation = invocations.remove(getInvocationId(owningProcess)
+ indexToString(resultEvent.getIndex()));
if (invocation == null) {
logger.log(SEVERE, "Can't find invocation for owning process "
+ owningProcess);
return;
}
// set the invocation outputs
try {
for (Entry<String, T2Reference> outputInfo : resultEvent.getData()
.entrySet()) {
invocation.setOutput(
outputInfo.getKey(),
getIntermediate(outputInfo.getValue(),
resultEvent.getContext()));
}
} catch (IOException | URISyntaxException e) {
logger.log(WARNING, "Error saving intermediate outputs for "
+ resultEvent.getOwningProcess(), e);
}
invocation.setCompletedDate(new Date());
}
}
public void deregisterNode(String[] owningProcess) {
StatusReport<?, ?> report = reports.get(getReportId(owningProcess));
if (report == null) {
return;
} else if (report instanceof WorkflowReport) {
Invocation invocation = invocations
.remove(getInvocationId(owningProcess));
invocation.setCompletedDate(new Date());
report.setCompletedDate(new Date());
} else if (report instanceof LocalProcessorReport) {
((LocalProcessorReport) report).saveProperties();
report.setCompletedDate(new Date());
} else if (report instanceof ActivityReport) {
// Invocation may still exist if the activity failed
Invocation invocation = invocations
.remove(getInvocationId(owningProcess));
if (invocation != null) {
invocation.setCompletedDate(new Date());
report.setFailedDate(new Date());
} else
report.setCompletedDate(new Date());
invocationToActivity
.remove(owningProcess[owningProcess.length - 1]);
}
}
public void addPropertiesToNode(String[] owningProcess,
Set<MonitorableProperty<?>> newProperties) {
StatusReport<?, ?> report = reports.get(getReportId(owningProcess));
if (report instanceof LocalProcessorReport) {
LocalProcessorReport processorReport = (LocalProcessorReport) report;
processorReport.addProperties(newProperties);
}
}
private String getParentInvocationId(String[] owningProcess) {
List<String> id = new ArrayList<>();
for (int i = 1; i < owningProcess.length - 1; i++)
if (i % 4 != 0)
id.add(owningProcess[i]);
return toPath(id);
}
private String getInvocationId(String[] owningProcess) {
List<String> id = new ArrayList<>();
for (int i = 1; i < owningProcess.length; i++)
if (i % 4 != 0)
id.add(owningProcess[i]);
return toPath(id);
}
private String getInvocationName(String[] owningProcess) {
return owningProcess[owningProcess.length - 1];
}
private String toPath(List<String> id) {
StringBuilder sb = new StringBuilder();
String sep = "";
for (String string : id) {
sb.append(sep).append(string);
sep = ID_SEPARATOR;
}
return sb.toString();
}
private String getReportId(String[] owningProcess) {
List<String> id = new ArrayList<>();
for (int i = 1, position = 0; i < owningProcess.length; i++) {
if (i % 4 == 0)
continue;
if (position == 2) {
id.add(invocationToActivity.get(owningProcess[i]));
position = 0;
} else {
id.add(owningProcess[i]);
position++;
}
}
return toPath(id);
}
public String getProcessorId(String[] owningProcess) {
StringBuffer sb = new StringBuffer();
for (int i = 1, skip = 0; i < owningProcess.length; i++, skip--)
if (i <= 2 || skip < 0) {
sb.append(owningProcess[i]);
skip = 3;
}
return sb.toString();
}
private String indexToString(int[] index) {
StringBuilder indexString = new StringBuilder();
for (int i = 0; i < index.length; i++) {
if (i != 0)
indexString.append(":");
indexString.append(index[i] + 1);
}
return indexString.toString();
}
private Path getIntermediate(T2Reference t2Reference,
InvocationContext context) throws IOException, URISyntaxException {
if (referenceToPath.containsKey(t2Reference))
return referenceToPath.get(t2Reference);
Path path = referencePath(t2Reference);
convertReferenceToPath(path, t2Reference, context);
referenceToPath.put(t2Reference, path);
return path;
}
private Path referencePath(T2Reference t2Reference) throws IOException {
String local = t2Reference.getLocalPart();
try {
return DataBundles.getIntermediate(dataBundle,
UUID.fromString(local));
} catch (IllegalArgumentException ex) {
return DataBundles.getIntermediates(dataBundle)
.resolve(t2Reference.getNamespacePart())
.resolve(t2Reference.getLocalPart());
}
}
public static String getStackTraceElementString(
StackTraceElementBean stackTraceElement) {
StringBuilder sb = new StringBuilder();
sb.append(stackTraceElement.getClassName()).append('.')
.append(stackTraceElement.getMethodName());
if (stackTraceElement.getFileName() == null) {
sb.append("(unknown file)");
} else {
sb.append('(').append(stackTraceElement.getFileName()).append(':')
.append(stackTraceElement.getLineNumber()).append(')');
}
return sb.toString();
}
public void convertReferenceToPath(Path path, T2Reference reference,
InvocationContext context) throws IOException, URISyntaxException {
ReferenceService referenceService = context.getReferenceService();
if (reference.getReferenceType() == T2ReferenceType.ReferenceSet) {
if (DataBundles.isMissing(path)) {
ReferenceSet rs = referenceService.getReferenceSetService()
.getReferenceSet(reference);
if (rs == null)
throw new ReferenceServiceException(
"Could not find ReferenceSet " + reference);
// Check that there are references in the set
if (rs.getExternalReferences().isEmpty())
throw new ReferenceServiceException("ReferenceSet "
+ reference + " is empty");
for (ExternalReferenceSPI ers : rs.getExternalReferences()) {
if (ers instanceof FileReference) {
URI uri = ((FileReference) ers).getFile().toURI();
DataBundles.setReference(path, uri);
} else if (ers instanceof HttpReference) {
URI uri = ((HttpReference) ers).getHttpUrl().toURI();
DataBundles.setReference(path, uri);
} else {
try (InputStream in = ers.openStream(context)) {
Files.copy(in, path);
}
}
}
}
} else if (reference.getReferenceType() == T2ReferenceType.ErrorDocument) {
if (DataBundles.isMissing(path)) {
ErrorDocument errorDocument = referenceService
.getErrorDocumentService().getError(reference);
String message = errorDocument.getMessage();
StringBuilder trace = new StringBuilder();
if (errorDocument.getExceptionMessage() != null
&& !errorDocument.getExceptionMessage().isEmpty()) {
trace.append(errorDocument.getExceptionMessage());
trace.append("\n");
}
List<StackTraceElementBean> stackTraceStrings = errorDocument
.getStackTraceStrings();
for (StackTraceElementBean stackTraceElement : stackTraceStrings) {
trace.append(getStackTraceElementString(stackTraceElement));
trace.append("\n");
}
List<Path> causes = new ArrayList<>();
for (T2Reference errorReference : errorDocument
.getErrorReferences())
causes.add(getIntermediate(errorReference, context));
DataBundles.setError(path, message, trace.toString(),
causes.toArray(new Path[causes.size()]));
}
} else { // it is an IdentifiedList<T2Reference>
IdentifiedList<T2Reference> identifiedList = referenceService
.getListService().getList(reference);
if (!DataBundles.isList(path))
DataBundles.createList(path);
for (T2Reference ref : identifiedList)
convertReferenceToPath(DataBundles.newListItem(path), ref,
context);
}
}
private class NestedDataflowResultListener implements ResultListener {
private final Invocation invocation;
public NestedDataflowResultListener(Invocation invocation) {
this.invocation = invocation;
}
@Override
public void resultTokenProduced(WorkflowDataToken token, String portName) {
try {
if (token.isFinal())
invocation
.setOutput(
portName,
getIntermediate(token.getData(),
token.getContext()));
} catch (IOException | URISyntaxException e) {
logger.log(SEVERE, "Unable to convert T2Reference", e);
}
}
}
private class DataflowResultListener implements ResultListener {
private Path outputs;
private Map<String, Integer> depthSeen = new HashMap<>();
public DataflowResultListener(Path outputs) {
this.outputs = outputs;
}
@Override
public void resultTokenProduced(WorkflowDataToken token, String portName) {
Integer depth = depthSeen.get(portName);
if (depth == null || depth.equals(token.getIndex().length)) {
if (depth == null)
depthSeen.put(portName, token.getIndex().length);
try {
Path port = DataBundles.getPort(outputs, portName);
Path path = getPath(port, 0, token.getIndex());
convertReferenceToPath(path, token.getData(),
token.getContext());
} catch (IOException | URISyntaxException e) {
logger.log(SEVERE, "Unable to convert T2Reference", e);
}
}
}
private Path getPath(Path path, int depth, int[] index)
throws IOException {
if (depth == index.length)
return path;
if (!DataBundles.isList(path))
DataBundles.createList(path);
return getPath(DataBundles.getListItem(path, index[depth]),
depth + 1, index);
}
}
}