/
TaskProcessor.groovy
2586 lines (2185 loc) · 91.6 KB
/
TaskProcessor.groovy
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2013-2024, Seqera Labs
*
* 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.
*/
package nextflow.processor
import static nextflow.processor.ErrorStrategy.*
import java.lang.reflect.InvocationTargetException
import java.nio.file.FileSystems
import java.nio.file.LinkOption
import java.nio.file.NoSuchFileException
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicIntegerArray
import java.util.concurrent.atomic.LongAdder
import java.util.regex.Matcher
import java.util.regex.Pattern
import ch.artecat.grengine.Grengine
import com.google.common.hash.HashCode
import groovy.json.JsonOutput
import groovy.transform.CompileStatic
import groovy.transform.Memoized
import groovy.transform.PackageScope
import groovy.util.logging.Slf4j
import groovyx.gpars.agent.Agent
import groovyx.gpars.dataflow.Dataflow
import groovyx.gpars.dataflow.DataflowQueue
import groovyx.gpars.dataflow.DataflowReadChannel
import groovyx.gpars.dataflow.DataflowWriteChannel
import groovyx.gpars.dataflow.expression.DataflowExpression
import groovyx.gpars.dataflow.operator.DataflowEventAdapter
import groovyx.gpars.dataflow.operator.DataflowOperator
import groovyx.gpars.dataflow.operator.DataflowProcessor
import groovyx.gpars.dataflow.operator.PoisonPill
import groovyx.gpars.dataflow.stream.DataflowStreamWriteAdapter
import groovyx.gpars.group.PGroup
import nextflow.NF
import nextflow.Nextflow
import nextflow.Session
import nextflow.ast.NextflowDSLImpl
import nextflow.ast.TaskCmdXform
import nextflow.ast.TaskTemplateVarsXform
import nextflow.cloud.CloudSpotTerminationException
import nextflow.dag.NodeMarker
import nextflow.exception.FailedGuardException
import nextflow.exception.IllegalArityException
import nextflow.exception.MissingFileException
import nextflow.exception.MissingValueException
import nextflow.exception.ProcessEvalException
import nextflow.exception.ProcessException
import nextflow.exception.ProcessFailedException
import nextflow.exception.ProcessRetryableException
import nextflow.exception.ProcessSubmitTimeoutException
import nextflow.exception.ProcessUnrecoverableException
import nextflow.exception.ShowOnlyExceptionMessage
import nextflow.exception.UnexpectedException
import nextflow.executor.CachedTaskHandler
import nextflow.executor.Executor
import nextflow.executor.StoredTaskHandler
import nextflow.extension.CH
import nextflow.extension.DataflowHelper
import nextflow.file.FileHelper
import nextflow.file.FileHolder
import nextflow.file.FilePatternSplitter
import nextflow.file.FilePorter
import nextflow.plugin.Plugins
import nextflow.processor.tip.TaskTipProvider
import nextflow.script.BaseScript
import nextflow.script.BodyDef
import nextflow.script.ProcessConfig
import nextflow.script.ScriptMeta
import nextflow.script.ScriptType
import nextflow.script.TaskClosure
import nextflow.script.bundle.ResourcesBundle
import nextflow.script.params.BaseOutParam
import nextflow.script.params.CmdEvalParam
import nextflow.script.params.DefaultOutParam
import nextflow.script.params.EachInParam
import nextflow.script.params.EnvInParam
import nextflow.script.params.EnvOutParam
import nextflow.script.params.FileInParam
import nextflow.script.params.FileOutParam
import nextflow.script.params.InParam
import nextflow.script.params.MissingParam
import nextflow.script.params.OptionalParam
import nextflow.script.params.OutParam
import nextflow.script.params.StdInParam
import nextflow.script.params.StdOutParam
import nextflow.script.params.TupleInParam
import nextflow.script.params.TupleOutParam
import nextflow.script.params.ValueInParam
import nextflow.script.params.ValueOutParam
import nextflow.util.ArrayBag
import nextflow.util.BlankSeparatedList
import nextflow.util.CacheHelper
import nextflow.util.Escape
import nextflow.util.LockManager
import nextflow.util.LoggerHelper
import nextflow.util.TestOnly
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer
/**
* Implement nextflow process execution logic
*
* @author Paolo Di Tommaso <paolo.ditommaso@gmail.com>
*/
@Slf4j
class TaskProcessor {
static enum RunType {
SUBMIT('Submitted process'),
RETRY('Re-submitted process')
String message;
RunType(String str) { message=str };
}
static final public String TASK_CONTEXT_PROPERTY_NAME = 'task'
final private static Pattern ENV_VAR_NAME = ~/[a-zA-Z_]+[a-zA-Z0-9_]*/
final private static Pattern QUESTION_MARK = ~/(\?+)/
@TestOnly private static volatile TaskProcessor currentProcessor0
@TestOnly static TaskProcessor currentProcessor() { currentProcessor0 }
/**
* Keeps track of the task instance executed by the current thread
*/
protected final ThreadLocal<TaskRun> currentTask = new ThreadLocal<>()
/**
* Unique task index number (run)
*/
final protected AtomicInteger indexCount = new AtomicInteger()
/**
* The current workflow execution session
*/
protected Session session
/**
* The script object which defines this task
*/
protected BaseScript ownerScript
/**
* The processor descriptive name
*/
protected String name
/**
* The piece of code to be execute provided by the user
*/
protected BodyDef taskBody
/**
* The corresponding {@code DataflowProcessor} which will receive and
* manage accordingly the task inputs
*
* note: it must be declared volatile -- issue #41
*/
protected volatile DataflowProcessor operator
/**
* The underlying executor which will run the task
*/
protected Executor executor
/**
* The corresponding task configuration properties, it holds the inputs/outputs
* definition as well as other execution meta-declaration
*/
protected ProcessConfig config
/**
* Count the number of time an error occurred
*/
private volatile int errorCount
/**
* Set to true the very first time the error is shown.
*
* Note: it is declared static because the error must be shown only the
* very first time for all processes
*/
private static final AtomicBoolean errorShown = new AtomicBoolean()
/**
* Flag set {@code true} when the processor termination has been invoked
*
* See {@code #checkProcessTermination}
*/
protected volatile boolean completed
protected boolean allScalarValues
protected boolean hasEachParams
/**
* The state is maintained by using an agent
*/
protected Agent<StateObj> state
/**
* Groovy engine used to evaluate dynamic code
*/
protected Grengine grengine
/**
* Whenever the process is executed only once
*/
protected boolean singleton
/**
* Track the status of input ports. When 1 the port is open (waiting for data),
* when 0 the port is closed (ie. received the STOP signal)
*/
protected AtomicIntegerArray openPorts
/**
* Process ID number. The first is 1, the second 2 and so on ..
*/
private final int id
private LongAdder forksCount
private int maxForks
private static int processCount
private static LockManager lockManager = new LockManager()
private List<Map<Short,List>> fairBuffers = new ArrayList<>()
private int currentEmission
private Boolean isFair0
private CompilerConfiguration compilerConfig() {
final config = new CompilerConfiguration()
config.addCompilationCustomizers( new ASTTransformationCustomizer(TaskTemplateVarsXform) )
config.addCompilationCustomizers( new ASTTransformationCustomizer(TaskCmdXform) )
return config
}
@TestOnly
static void reset() {
processCount=0
errorShown.set(false)
currentProcessor0 = null
}
/*
* Initialise the process ID
*
* Note: processes are create in a sequential manner (by the main thread that parse the script)
* so it does not require a synchronized block
*/
{
id = ++processCount
grengine = session && session.classLoader ? new Grengine(session.classLoader, compilerConfig()) : new Grengine(compilerConfig())
currentProcessor0 = this
}
/* for testing purpose - do not remove */
protected TaskProcessor() { }
/**
* Create and initialize the processor object
*
* @param name
* @param executor
* @param session
* @param script
* @param config
* @param taskBody
*/
TaskProcessor(String name, Executor executor, Session session, BaseScript script, ProcessConfig config, BodyDef taskBody ) {
assert executor
assert session
assert script
assert taskBody
this.executor = executor
this.session = session
this.ownerScript = script
this.config = config
this.taskBody = taskBody
this.name = name
this.maxForks = config.maxForks && config.maxForks>0 ? config.maxForks as int : 0
this.forksCount = maxForks ? new LongAdder() : null
this.isFair0 = config.getFair()
}
/**
* @return The processor unique id
*/
int getId() { id }
/**
* @return The {@code TaskConfig} object holding the task configuration properties
*/
ProcessConfig getConfig() { config }
/**
* @return The current {@code Session} instance
*/
Session getSession() { session }
/**
* @return The processor name
*/
String getName() { name }
/**
* @return The {@link Executor} associated to this processor
*/
Executor getExecutor() { executor }
/**
* @return The {@code DataflowOperator} underlying this process
*/
DataflowProcessor getOperator() { operator }
/**
* @return The {@code BaseScript} object which represents pipeline script
*/
BaseScript getOwnerScript() { ownerScript }
/**
* Define the type of script hold by the {@code #code} property
*/
protected ScriptType getScriptType() { taskBody.type }
/**
* @return The user provided script block
*/
BodyDef getTaskBody() { taskBody }
Set<String> getDeclaredNames() {
Set<String> result = new HashSet<>(20)
result.addAll(config.getInputs().getNames())
result.addAll(config.getOutputs().getNames())
return result
}
LongAdder getForksCount() { forksCount }
int getMaxForks() { maxForks }
boolean hasErrors() { errorCount>0 }
@Memoized
protected TaskTipProvider getTipProvider() {
final provider = Plugins.getPriorityExtensions(TaskTipProvider).find(it-> it.enabled())
if( !provider )
throw new IllegalStateException("Unable to find any tip provider")
return provider
}
/**
* Create a "preview" for a task run. This method is only meant for the creation of "mock" task run
* to allow the access for the associated {@link TaskConfig} during a pipeline "preview" execution.
*
* Note this returns an "eventually" task configuration object. Also Inputs and output parameters are NOT
* resolved by this method.
*
* @return A {@link TaskRun} object holding a reference to the associated {@link TaskConfig}
*/
TaskRun createTaskPreview() {
final task = new TaskRun(
processor: this,
type: scriptType,
config: config.createTaskConfig(),
context: new TaskContext(this)
)
task.config.context = task.context
task.config.process = task.processor.name
task.config.executor = task.processor.executor.name
return task
}
protected void checkWarn(String msg, Map opts=null) {
if( NF.isStrictMode() )
throw new ProcessUnrecoverableException(msg)
if( opts )
log.warn1(opts, msg)
else
log.warn(msg)
}
/**
* Launch the 'script' define by the code closure as a local bash script
*
* @param code A {@code Closure} returning a bash script e.g.
* <pre>
* {
* """
* #!/bin/bash
* do this ${x}
* do that ${y}
* :
* """
* }
*
* @return {@code this} instance
*/
def run() {
// -- check that the task has a body
if ( !taskBody )
throw new IllegalStateException("Missing task body for process `$name`")
// -- check that input tuple defines at least two elements
def invalidInputTuple = config.getInputs().find { it instanceof TupleInParam && it.inner.size()<2 }
if( invalidInputTuple )
checkWarn "Input `tuple` must define at least two elements -- Check process `$name`"
// -- check that output tuple defines at least two elements
def invalidOutputTuple = config.getOutputs().find { it instanceof TupleOutParam && it.inner.size()<2 }
if( invalidOutputTuple )
checkWarn "Output `tuple` must define at least two elements -- Check process `$name`"
/**
* Verify if this process run only one time
*/
allScalarValues = config.getInputs().allScalarInputs()
hasEachParams = config.getInputs().any { it instanceof EachInParam }
/*
* Normalize input channels
*/
config.fakeInput()
/*
* Normalize the output
* - even though the output may be empty, let return the stdout as output by default
*/
if ( config.getOutputs().size() == 0 ) {
config.fakeOutput()
}
// the state agent
state = new Agent<>(new StateObj(name))
state.addListener { StateObj old, StateObj obj ->
try {
log.trace "<$name> Process state changed to: $obj -- finished: ${obj.isFinished()}"
if( !completed && obj.isFinished() ) {
terminateProcess()
completed = true
}
}
catch( Throwable e ) {
session.abort(e)
}
}
// register the processor
// note: register the task *before* creating (and starting the dataflow operator) in order
// a race condition on the processes barrier - this fix issue #43
session.processRegister(this)
// create the underlying dataflow operator
createOperator()
session.notifyProcessCreate(this)
/*
* When there is a single output channel, return let returns that item
* otherwise return the list
*/
def result = config.getOutputs().channels
return result.size() == 1 ? result[0] : result
}
/**
* Template method which extending classes have to override in order to
* create the underlying *dataflow* operator associated with this processor
*
* See {@code DataflowProcessor}
*/
protected void createOperator() {
def opInputs = new ArrayList(config.getInputs().getChannels())
/*
* check if there are some iterators declaration
* the list holds the index in the list of all *inputs* for the {@code each} declaration
*/
List<Integer> iteratorIndexes = []
config.getInputs().eachWithIndex { param, index ->
if( param instanceof EachInParam ) {
log.trace "Process ${name} > got each param: ${param.name} at index: ${index} -- ${param.dump()}"
iteratorIndexes << index
}
}
/**
* The thread pool used by GPars. The thread pool to be used is set in the static
* initializer of {@link nextflow.cli.CmdRun} class. See also {@link nextflow.util.CustomPoolFactory}
*/
final PGroup group = Dataflow.retrieveCurrentDFPGroup()
/*
* When one (or more) {@code each} are declared as input, it is created an extra
* operator which will receive the inputs from the channel (excepts the values over iterate)
*
* The operator will *expand* the received inputs, iterating over the user provided value and
* forwarding the final values the the second *parallel* processor executing the user specified task
*/
if( iteratorIndexes ) {
log.debug "Creating *combiner* operator for each param(s) at index(es): ${iteratorIndexes}"
// don't care about the last channel, being the control channel it doesn't bring real values
final size = opInputs.size()-1
// the iterator operator needs to executed just one time
// thus add a dataflow queue binding a single value and then a stop signal
def termination = new DataflowQueue<>()
termination << Boolean.TRUE
opInputs[size] = termination
// the channel forwarding the data from the *iterator* process to the target task
final linkingChannels = new ArrayList(size)
size.times { linkingChannels[it] = new DataflowQueue() }
// the script implementing the iterating process
final forwarder = new ForwardClosure(size, iteratorIndexes)
// instantiate the iteration process
def DataflowOperator op1
def stopAfterFirstRun = allScalarValues
def interceptor = new BaseProcessInterceptor(opInputs, stopAfterFirstRun)
def params = [inputs: opInputs, outputs: linkingChannels, maxForks: 1, listeners: [interceptor]]
session.allOperators << (op1 = new DataflowOperator(group, params, forwarder))
// fix issue #41
start(op1)
// set as next inputs the result channels of the iteration process
// adding the 'control' channel removed previously
opInputs = new ArrayList(size+1)
opInputs.addAll( linkingChannels )
opInputs.add( config.getInputs().getChannels().last() )
}
/*
* finally create the operator
*/
// note: do not specify the output channels in the operator declaration
// this allows us to manage them independently from the operator life-cycle
this.singleton = allScalarValues && !hasEachParams
this.openPorts = createPortsArray(opInputs.size())
config.getOutputs().setSingleton(singleton)
def interceptor = new TaskProcessorInterceptor(opInputs, singleton)
def params = [inputs: opInputs, maxForks: session.poolSize, listeners: [interceptor] ]
def invoke = new InvokeTaskAdapter(this, opInputs.size())
session.allOperators << (operator = new DataflowOperator(group, params, invoke))
// notify the creation of a new vertex the execution DAG
NodeMarker.addProcessNode(this, config.getInputs(), config.getOutputs())
// fix issue #41
start(operator)
}
private start(DataflowProcessor op) {
if( !NF.dsl2 ) {
op.start()
return
}
session.addIgniter {
log.debug "Starting process > $name"
op.start()
}
}
private AtomicIntegerArray createPortsArray(int size) {
def result = new AtomicIntegerArray(size)
for( int i=0; i<size; i++ )
result.set(i, 1)
return result
}
/**
* The processor execution body
*
* @param args
* The args array is expected to be composed by two elements:
* the first must be an object object of type {@link TaskStartParams},
* the second is the list of task input messages as received by the process
*/
final protected void invokeTask( Object[] args ) {
assert args.size()==2
final params = (TaskStartParams) args[0]
final values = (List) args[1]
// create and initialize the task instance to be executed
log.trace "Invoking task > $name with params=$params; values=$values"
// -- create the task run instance
final task = createTaskRun(params)
// -- set the task instance as the current in this thread
currentTask.set(task)
// -- validate input lengths
validateInputTuples(values)
// -- map the inputs to a map and use to delegate closure values interpolation
final secondPass = [:]
int count = makeTaskContextStage1(task, secondPass, values)
makeTaskContextStage2(task, secondPass, count)
// verify that `when` guard, when specified, is satisfied
if( !checkWhenGuard(task) )
return
TaskClosure block
if( session.stubRun && (block=task.config.getStubBlock()) ) {
task.resolve(block)
}
else {
// -- resolve the task command script
task.resolve(taskBody)
}
// -- verify if exists a stored result for this case,
// if true skip the execution and return the stored data
if( checkStoredOutput(task) )
return
def hash = createTaskHashKey(task)
checkCachedOrLaunchTask(task, hash, resumable)
}
@Memoized
private List<TupleInParam> getDeclaredInputTuple() {
getConfig().getInputs().ofType(TupleInParam)
}
protected void validateInputTuples( List values ) {
def declaredSets = getDeclaredInputTuple()
for( int i=0; i<declaredSets.size(); i++ ) {
final param = declaredSets[i]
final entry = values[param.index]
final expected = param.inner.size()
final actual = entry instanceof Collection ? entry.size() : (entry instanceof Map ? entry.size() : 1)
if( actual != expected ) {
final msg = "Input tuple does not match tuple declaration in process `$name` -- offending value: $entry"
checkWarn(msg, [firstOnly: true, cacheKey: this])
}
}
}
/**
* @return A string 'she-bang' formatted to the added on top script to be executed.
* The interpreter to be used define by the *taskConfig* property {@code shell}
*/
static String shebangLine(shell) {
assert shell, "Missing 'shell' property in process configuration"
String result = shell instanceof List ? shell.join(' ') : shell
if( result.startsWith('/') ) {
result = '#!' + result
}
else {
result= '#!/usr/bin/env ' + result
}
return result
}
/**
* Remove extra leading, trailing whitespace and newlines chars,
* also if the script does not start with a {@code shebang} line,
* add the default by using the current {@code #shell} attribute
*/
static String normalizeScript(String script, shell) {
assert script != null
def result = new StringBuilder()
result << script.stripIndent(true).trim()
result << '\n'
if( result[0] != '#' || result[1] != '!') {
result.insert(0, shebangLine(shell) + '\n')
}
return result.toString()
}
/**
* Given the task script extract the top *she-bang* interpreter declaration removing the {@code #!} characters.
* @param script The script to be executed
*
* @return The interpreter as defined in the she-bang declaration, for example {@code /usr/bin/env perl}
*/
static String fetchInterpreter( String script ) {
if( script && script[0] == '#' && script[1] == '!') {
return script.readLines()[0].substring(2)
}
return null
}
/**
* Create a new {@code TaskRun} instance, initializing the following properties :
* <li>{@code TaskRun#id}
* <li>{@code TaskRun#status}
* <li>{@code TaskRun#index}
* <li>{@code TaskRun#name}
* <li>{@code TaskRun#process}
*
* @return The new newly created {@code TaskRun}
*/
final protected TaskRun createTaskRun(TaskStartParams params) {
final task = new TaskRun(
id: params.id,
index: params.index,
processor: this,
type: scriptType,
config: config.createTaskConfig(),
context: new TaskContext(this)
)
// setup config
task.config.index = task.index
task.config.process = task.processor.name
task.config.executor = task.processor.executor.name
/*
* initialize the inputs/outputs for this task instance
*/
config.getInputs().each { InParam param ->
if( param instanceof TupleInParam )
param.inner.each { task.setInput(it) }
else if( param instanceof EachInParam )
task.setInput(param.inner)
else
task.setInput(param)
}
config.getOutputs().each { OutParam param ->
if( param instanceof TupleOutParam ) {
param.inner.each { task.setOutput(it) }
}
else
task.setOutput(param)
}
return task
}
/**
* Try to check if exists a previously executed process result in the a cached folder. If it exists
* use the that result and skip the process execution, otherwise the task is sumitted for execution.
*
* @param task
* The {@code TaskRun} instance to be executed
* @param hash
* The unique {@code HashCode} for the given task inputs
* @param script
* The script to be run (only when it's a merge task)
* @return
* {@code false} when a cached result has been found and the execution has skipped,
* or {@code true} if the task has been submitted for execution
*
*/
@CompileStatic
final protected void checkCachedOrLaunchTask( TaskRun task, HashCode hash, boolean shouldTryCache ) {
int tries = task.failCount +1
while( true ) {
hash = CacheHelper.defaultHasher().newHasher().putBytes(hash.asBytes()).putInt(tries).hash()
Path resumeDir = null
boolean exists = false
try {
final entry = session.cache.getTaskEntry(hash, this)
resumeDir = entry ? FileHelper.asPath(entry.trace.getWorkDir()) : null
if( resumeDir )
exists = resumeDir.exists()
log.trace "[${safeTaskName(task)}] Cacheable folder=${resumeDir?.toUriString()} -- exists=$exists; try=$tries; shouldTryCache=$shouldTryCache; entry=$entry"
final cached = shouldTryCache && exists && entry.trace.isCompleted() && checkCachedOutput(task.clone(), resumeDir, hash, entry)
if( cached )
break
}
catch (Throwable t) {
log.warn1("[${safeTaskName(task)}] Unable to resume cached task -- See log file for details", causedBy: t)
}
if( exists ) {
tries++
continue
}
final lock = lockManager.acquire(hash)
final workDir = task.getWorkDirFor(hash)
try {
if( resumeDir != workDir )
exists = workDir.exists()
if( !exists && !workDir.mkdirs() )
throw new IOException("Unable to create directory=$workDir -- check file system permissions")
}
finally {
lock.release()
}
// submit task for execution
submitTask( task, hash, workDir )
break
}
}
/**
* Check if exists a *storeDir* for the specified task. When if exists
* and contains the expected result files, the process execution is skipped.
*
* @param task The task for which check the stored output
* @return {@code true} when the folder exists and it contains the expected outputs,
* {@code false} otherwise
*/
final boolean checkStoredOutput( TaskRun task ) {
if( !task.config.storeDir ) {
log.trace "[${safeTaskName(task)}] Store dir not set -- return false"
return false
}
// -- when store path is set, only output params of type 'file' can be specified
final ctx = task.context
def invalid = task.getOutputs().keySet().any {
if( it instanceof ValueOutParam ) {
return !ctx.containsKey(it.name)
}
if( it instanceof FileOutParam ) {
return false
}
return true
}
if( invalid ) {
checkWarn "[${safeTaskName(task)}] StoreDir can only be used when using 'file' outputs"
return false
}
if( !task.config.getStoreDir().exists() ) {
log.trace "[${safeTaskName(task)}] Store dir does not exist > ${task.config.storeDir} -- return false"
// no folder -> no cached result
return false
}
try {
// -- expose task exit status to make accessible as output value
task.config.exitStatus = TaskConfig.EXIT_ZERO
// -- check if all output resources are available
collectOutputs(task)
log.info "[skipping] Stored process > ${safeTaskName(task)}"
// set the exit code in to the task object
task.exitStatus = TaskConfig.EXIT_ZERO
task.cached = true
session.notifyTaskCached(new StoredTaskHandler(task))
// -- now bind the results
finalizeTask0(task)
return true
}
catch( MissingFileException | MissingValueException e ) {
log.trace "[${safeTaskName(task)}] Missed store > ${e.getMessage()} -- folder: ${task.config.storeDir}"
task.exitStatus = Integer.MAX_VALUE
task.workDir = null
return false
}
}
/**
* Check whenever the outputs for the specified task already exist
*
* @param task The task instance
* @param folder The folder where the outputs are stored (eventually)
* @return {@code true} when all outputs are available, {@code false} otherwise
*/
final boolean checkCachedOutput(TaskRun task, Path folder, HashCode hash, TaskEntry entry) {
// check if exists the task exit code file
def exitCode = null
def exitFile = folder.resolve(TaskRun.CMD_EXIT)
if( task.type == ScriptType.SCRIPTLET ) {
def str
try {
str = exitFile.text?.trim()
}
catch( IOException e ) {
log.trace "[${safeTaskName(task)}] Exit file can't be read > $exitFile -- return false -- Cause: ${e.message}"
return false
}
exitCode = str.isInteger() ? str.toInteger() : null
if( !task.isSuccess(exitCode) ) {
log.trace "[${safeTaskName(task)}] Exit code is not valid > $str -- return false"
return false
}
}
/*
* verify cached context map
*/
if( !entry ) {
log.trace "[${safeTaskName(task)}] Missing cache entry -- return false"
return false
}
if( task.hasCacheableValues() && !entry.context ) {
log.trace "[${safeTaskName(task)}] Missing cache context -- return false"
return false
}
/*
* verify stdout file
*/
final stdoutFile = folder.resolve( TaskRun.CMD_OUTFILE )
if( entry.context != null ) {
task.context = entry.context
task.config.context = entry.context
task.code?.delegate = entry.context
}
try {
// -- expose task exit status to make accessible as output value
task.config.exitStatus = exitCode
// -- check if all output resources are available
collectOutputs(task, folder, stdoutFile, task.context)
// set the exit code in to the task object
task.cached = true
task.hash = hash
task.workDir = folder
task.stdout = stdoutFile
if( exitCode != null ) {
task.exitStatus = exitCode
}
log.info "[${task.hashLog}] Cached process > ${task.name}"
// -- notify cached event
if( entry )
session.notifyTaskCached(new CachedTaskHandler(task,entry.trace))
// -- now bind the results
finalizeTask0(task)
return true
}
catch( MissingFileException | MissingValueException e ) {
log.trace "[${safeTaskName(task)}] Missed cache > ${e.getMessage()} -- folder: $folder"
task.exitStatus = Integer.MAX_VALUE
task.workDir = null
return false
}
}
/**
* Handles an error raised during the processor execution
*
* @param error The exception raised during the task execution
* @param task The {@code TaskDef} instance which raised the exception
* @return {@code true} to terminate the processor execution,
* {@code false} ignore the error and continue to process other pending tasks
*/
final protected boolean handleException( Throwable error, TaskRun task = null ) {
log.trace "Handling error: $error -- task: $task"
def fault = resumeOrDie(task, error)
log.trace "Task fault (2): $fault"
if (fault instanceof TaskFault) {