/
PipelineContext.groovy
executable file
·3221 lines (2698 loc) · 120 KB
/
PipelineContext.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 (c) 2012 MCRI, authors
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package bpipe
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.PathMatcher
import java.util.concurrent.locks.Lock;
import java.util.logging.Logger
import java.util.regex.Matcher
import java.util.regex.Pattern;
import bpipe.executor.ProbeCommandExecutor
import bpipe.storage.LocalFileSystemStorageLayer
import bpipe.storage.LocalPipelineFile
import bpipe.storage.StorageLayer
import bpipe.storage.UnknownStoragePipelineFile
import groovy.transform.CompileStatic
import groovy.transform.Memoized
/**
* This context defines implicit functions and variables that are
* made available to Bpipe pipeline stages. These functions are
* only available inside the context of a Bpipe stage, when it is
* executed by Bpipe (ie. they are introduced at runtime).
* <p>
* Note: currently other functions are also made available in two
* other places:
* <li>PipelineCategory
* <li>PipelineDelegate
*/
class PipelineContext {
static Logger log = Logger.getLogger(PipelineContext.name)
/**
* File where half processed files will be listed on shutdown
*/
public static File UNCLEAN_FILE_PATH = new File(".bpipe/inprogress")
/**
* This value is returned when a $thread variable is evaluated in a GString
* (eg. a command from the user). The reason for this is that Groovy eagerly
* evaluates GStrings prior to passing them to a function. That means we can't
* allow the function itself to set the value - as we wish to do for threads
* when the user executes a command and we want to pass the number of threads
* evaluated "just in time". So this special value is set, and then
* it is replaced just before the command executes with an appropriate number
* of threads for the command to use.
*/
public final static String THREAD_LAZY_VALUE = '__bpipe_lazy_resource_threads__'
public final static String MEMORY_LAZY_VALUE = '__bpipe_lazy_resource_memory__'
/**
* Create a Pipeline Context with the specified adidtional bound variables and
* pipeline stages as well.
*
* @param extraBinding extra variables to make referenceable by pipeline stages
* that execute using this context
* @param pipelineStages list of known pipeline stages. These are used to resolve
* inputs when the user uses the implicit 'from' by appending
* an extension to the implicit input variable (eg: $input.csv).
* The stages are searched to find the most recent stage with
* an output that matches the specified extension.
*
*/
public PipelineContext(Binding extraBinding, List<PipelineStage> pipelineStages, Set<Closure> pipelineJoiners, Branch branch) {
super();
if(pipelineStages == null)
throw new IllegalArgumentException("PipelineStages cannot be null")
this.pipelineStages = pipelineStages
this.extraBinding = extraBinding
this.pipelineJoiners = pipelineJoiners
this.initUncleanFilePath()
this.threadId = Thread.currentThread().getId()
this.branch = branch
def pipeline = Pipeline.currentRuntimePipeline.get()
if(pipeline) {
this.applyName = pipeline.name && !pipeline.nameApplied
this.aliases = pipeline.aliases
}
this.outputLog = new OutputLog(branch.name)
}
/**
* Additional variables that are injected into the pipeline stage when it executes.
* In practice, these allow it to resolve pipeline stages that are loaded from external
* files (which otherwise would not be in scope).
*/
Binding extraBinding
/**
* Local variables are specific to this instance of this pipeline stage.
* These are injected in and take values separately even if a stage is used
* twice in a single pipeline
*/
Map<String,Object> localVariables = [:]
/**
* The stage name for which this context is running
*/
String stageName = "Unknown"
/**
* The directory to which the pipeline stage should write its outputs
*/
String outputDirectory = Config.config.defaultOutputDirectory
/**
* The id of the thread that created this context
*/
Long threadId
/**
* The resources used by commands that run in this stage
*/
Map<String,ResourceUnit> usedResources = [ "threads":new ResourceUnit(key: "threads", amount: 1)]
/**
* Whether or not the user has invoked a 'uses { ... }' command on this context
*/
boolean customThreadResources = false
File uncleanFilePath
/**
* Set of aliases to use for mapping file names
*/
Aliases aliases = null
/**
* Documentation attributes for the the pipeline stage
* Mostly this is a map of String => String, but
* tool information is stored as {@link Tool} objects
*/
Map<String, Object> documentation = [:]
/**
* A list of Checkers created during execution of the corresponding
* pipeline stage.
*/
List<Checker> checkers = []
private List<PipelineStage> pipelineStages
/**
* Pipeline joiners are closures that are introduced by Bpipe for
* joining stages together. The context needs to know them (or
* pass them on to others who need them) mainly to exclude
* them from certain functions (eg: they shouldn't be displayed
* to the user in diagrams, etc.)
*/
public Set<Closure> pipelineJoiners
/**
* If this stage is the result of merging multiple branches and is designated as a
* mergepoint, the merging branches are listed here
*/
List<Branch> inboundBranches
/**
* Manager for commands executed by this context
*/
CommandManager commandManager = new CommandManager()
/**
* All outputs from this stage. The key to this map
* is the Bpipe command id (different to process id).
*/
Map<String,Command> trackedOutputs = [:]
/**
* Commands indexed by path to output file
*/
Map<String,String> pathToCommandId = [:]
/**
* When a command is run, output variables that are referenced in
* the command are tracked. This allows them then to be logged
* in the audit trail and saved in the history database
* so that we know which command created the output.
* <p>
* This list is cleared with each new invocation
* by {@link #exec(String, boolean, String)}
*/
List<String> referencedOutputs = []
/**
* A list of internally set inputs/outputs that are not visible to the user
* (see use in Checker)
*/
List<String> internalOutputs = []
List<String> internalInputs = []
List<PipelineFile> pendingGlobOutputs = []
/**
* A list of outputs that are to be marked as preserved.
* These will not be deleted automatically by user initiated
* cleanup operations (see {@link Dependencies#cleanup(java.util.List)}
*/
List<PipelineFile> preservedOutputs = []
/**
* A list of outputs that are to be marked as intermediate.
* These will be deleted automatically by user initiated
* cleanup operations (see {@link Dependencies#cleanup(java.util.List)},
* even if they are leaf outputs from the pipeline
*/
List<PipelineFile> intermediateOutputs = []
/**
* A Map of files that are not independent outputs, but which
* accompany other outputs, as declared by the user.
* Key is output file name, value is accompanied input
*/
Map<String,String> accompanyingOutputs = [:]
/**
* List of patterns that match accompanying outputs
*/
Pattern activeAccompanierPattern = null
/**
* Flag that can be enabled to cause missing properties to resolve to
* outputting the name of the property ie. a reference to $x will produce $x.
* This allows for a crude pass-through of variables from Bpipe to Bash
* when executing commands.
*/
boolean echoWhenNotFound = true
/**
* When set to true, the context should not execute any commands, it should only
* evaluate their arguments to probe $input and $output invocations
* so that files that will use can be determined
*/
boolean probeMode = false
/**
* The name for this segment of the pipeline. The name is blank by default but
* is non-blank when pipeline branches are created from chromosomes or file name matches.
*/
Branch branch
/**
* A list of executable closures to be executed when the next produce statement completes
*/
List<Closure> inputResets = []
/**
* The default output is set prior to the body of the a pipeline stage being run.
* If the pipeline stage does nothing else but references $output then the default output is
* the one that is returned. However the pipeline stage may modify the output
* by use of the transform, filter or produce constructs. If so, the actual output
* is stored in the output property.
*/
private String defaultOutput
/**
* Log that will write output from messages and commands executed
* by this context / stage
*/
private OutputLog outputLog
/**
* Populated with output files for which commands were actually executed
*/
public List<PipelineFile> executedOutputs = []
/**
* Set the default inputs and outputs for this context according to the current
* state of the given pipeline, and our stage name.
* <p>
* Note: initialize may not always be called - for silent "joiner" stages a context
* is created but not initialized, because these have no inputs or outputs.
*
* @param pipeline
*/
@CompileStatic
void initialize(Pipeline pipeline, String stageName) {
this.stageName = stageName
if(pipeline.inboundBranches && (this.stageName != "Unknown")) {
this.inboundBranches = pipeline.inboundBranches
log.info "Stage $stageName is claiming the following inbound branches as a mergepoint: ${inboundBranches*.name}"
pipeline.inboundBranches = null
}
if(this.@output == null && this.@defaultOutput == null) {
String initialDefaultOutput = stageName
if(this.@input) {
// If we are running in a sub-pipeline that has a name, make sure we
// reflect that in the output file name. The name should only be applied to files
// produced form the first stage in the sub-pipeline
if(pipeline.name && !pipeline.nameApplied) {
initialDefaultOutput = String.valueOf(Utils.first(this.@input)) + "." + pipeline.name + "."+stageName
// Note we don't set pipeline.nameApplied = true here
// if it is really applied then that is flagged in PipelineContext
// Setting the applied flag here will stop it from being applied
// in the transform / filter constructs
}
else {
initialDefaultOutput = String.valueOf(Utils.first(this.@input)) + "." + stageName
}
}
// Ensure there is no directory attached to the default output
this.defaultOutput = new File(initialDefaultOutput).name
}
branch.dirChangeListener = { String dirName ->
outputTo(dirName)
}
}
String getDefaultOutput() {
// log.info "Returning default output " + this.@defaultOutput
return this.@defaultOutput
}
void setDefaultOutput(Object defOut) {
this.@defaultOutput = toOutputFolder(defOut)[0]
}
/**
* The list of outputs that this pipeline stage is defined to produce. If specified, this
* list is enforced. That is, if the user then tries to reference an incompatible
* output in one of their commands, they receive an error.
* <p>
* More flexible outputs are specified implicitly. These are 'inferred' outputs that
* are tracked using allInferredOutputs. When a stage executes, this variable is initially
* empty, and it is populated as the outputs get defined - either explicitly (eg: via produce)
* or implicitly. When implicit, it only occurs after the stage executes (see #resolveOutputs)
*/
private List<PipelineFile> output = null
void setOutput(o) {
setRawOutput(toOutputFolder(o))
}
/**
* Set the specified output for this pipeline stage to the given
* files.
*
* @param outs A possibly heterogenous mix of Strings and PipelineFile objects
*/
@CompileStatic
void setRawOutput(List outs) {
this.@output = this.resolvePipelineFiles(outs)
log.info "Actual output set: " + this.@output
}
/**
* Convert a heterogenous list of outputs (strings, files, etc) to standardised
* {@link PipelineFile} objects.
*
* @param outs heterogeneous list of file-like objects
* @return list of PipelineFile
*/
@CompileStatic
List<PipelineFile> resolvePipelineFiles(List outs) {
assert (outs == null) || (outs instanceof List)
if(outs == null || outs.size()<20)
log.info "Setting output $outs on context ${this.hashCode()} in thread ${Thread.currentThread().id}"
else
log.info "Setting ${outs.size()} outputs starting with ${outs[0..9]} on context ${this.hashCode()} in thread ${Thread.currentThread().id}"
if(Thread.currentThread().id != threadId)
log.warning "Thread output being set to $outs from wrong thread ${Thread.currentThread().id} instead of $threadId"
return (List<PipelineFile>)Utils.box(outs).collect { Object o ->
assert !(o instanceof List)
if((o instanceof PipelineFile) && !(o instanceof UnknownStoragePipelineFile))
return o
else {
String oString = String.valueOf(o)
StorageLayer storageLayer = resolveStorageFor(oString)
if(storageLayer == null)
return null
else
return new PipelineFile(oString, storageLayer)
}
}.grep { it != null }
}
@CompileStatic
List<PipelineFile> getRawOutput() {
this.@output
}
@CompileStatic
StorageLayer resolveStorageFor(String outputPath, Map config = null, boolean strict=true) {
if(config == null) {
config = resolveStorageConfig(outputPath, strict)
if(config == null)
return StorageLayer.defaultStorage
}
StorageLayer result = resolveStorageForConfig(config)
log.info "Create storage layer ${result?.class?.name} for output $outputPath"
return result
}
@CompileStatic
private Map resolveStorageConfig(String outputPath, boolean strict) {
String commandId = pathToCommandId[outputPath]
if(commandId == null) {
if(!strict)
return null
}
if(commandId == null)
return null
assert commandId != null
Command command = trackedOutputs[commandId]
if(command == null)
if(!strict)
return null
if(command == null) {
log.severe "No command registered for output path $outputPath"
}
assert command != null
return command.processedConfig
}
@CompileStatic
StorageLayer resolveStorageForConfig(Map config) {
String storage = Config.listValue(config, 'storage')[0]
if(!storage)
return new LocalFileSystemStorageLayer()
return StorageLayer.create(storage)
}
/**
* A synonym for the output directory, designed to allow commands that really have to know
* what directory they are writing to access to it.
*/
@CompileStatic
String getDir() {
return this.@outputDirectory
}
/**
* Outputs referenced through output property extensions
* since the last exec command. The occurrence of an exec
* clears this property.
*/
List inferredOutputs = []
/**
* All outputs referenced through output property extensions during the
* execution of the pipeline stage. Note that these are stored in string format
* and have to be converted to PipelineFile objects to localise to the correct
* storage before being used for most purposes (see {@link #resolvePipelineFiles}).
*/
List<String> allInferredOutputs = []
/**
* A list of inputs resolved directly by references to $input
* and $input<x> variables.
*
* Note that inputs resolved by
* input variable properties (pseudo file extensions) are not tracked
* here but rather inside the PipelineInput wrapper object itself.
* To get a complete list of resolved inputs, call the #getResolvedInputs
* method.
*/
List<PipelineFile> allResolvedInputs = []
/**
* The default output property reference. Actually returns a quasi
* String-like object that intercepts property references
*/
def getOutput() {
try {
return getOutputImpl()
}
catch(Exception e) {
e.printStackTrace()
throw e
}
}
/**
* Internal class to encapsulate logic for resolving outputs
*
* @author simon.sadedin
*/
private class OutputResolver {
String baseOutput
List<String> out
List<PipelineFile> overrideOutputs
OutputResolver() {
baseOutput = Utils.first(getDefaultOutput())
out = rawOutput?.collect { it.path }
overrideOutputs = (List)rawOutput?.clone()?:[]
}
@CompileStatic
void resolveOutput() {
Map<Integer,PipelineInput> allInputs = allUsedInputWrappers
// If an input property was referenced, compute the default from that instead
List<PipelineFile> allResolved = (List<PipelineFile>)allInputs.collect { Map.Entry<Integer,PipelineInput> e ->
PipelineInput resolvedInputs = e.value
// Because an output is being referenced, we need to force the input to resolve
// (it may not have resolved because Groovy does not invoke toString() upon reference, only
// after all variables have been resolved). This is only necessary after a `from` is
// applied because it resets the inputs into a state where previous resolution may have been
// lost
if(forceResolve) {
try {
resolvedInputs.toString()
}
catch(Exception exIgnore) {
// Ignore
}
}
return ((PipelineInput)e.value).resolvedInputs
}.flatten()
if(!allResolved) {
log.info "No inputs resolved by input wrappers: outputs will be based on default ${defaultOutput}"
return
}
else {
resolveFromInputs(allResolved)
}
}
// @CompileStatic - causes error when compiled with gradle
private void resolveFromInputs(List<PipelineFile> allResolved) {
int defaultValueIndex = computeDefaultInputIndex(allResolved)
PipelineFile resolved = allResolved[defaultValueIndex]
log.info("Using non-default output due to input property reference: " + resolved + " from resolved inputs " + allResolved)
if(currentFileNameTransform != null) {
out = currentFileNameTransform.transform(allResolved, applyName)*.path
overrideOutputs = toOutputFolder(out)
}
else
out = [resolved.newName(resolved.name +"." + stageName).path]
checkAccompaniedOutputs([resolved])
// Since we're resolving based on a different input than the default one,
// the pipeline output wrapper should use a different one as a default too
baseOutput = toOutputFolder(out)[0]
}
/**
* Compute the input index that should be used if no particular input can be inferred from the command created.
* <p>
* By default, it's the first input, unless the user split the pipeline into branches by filename, in which case
* it's a the input corresponding to the branch that is executing.
*
* @return the index in the given input list that should be used to compute the output by default
*/
// CompileStatic causes internal error here
private int computeDefaultInputIndex(List<PipelineFile> allResolved) {
// By default, if multiple inputs were resolved by the input wrapper,
// we take the first UNLESS one of the inputs corresponds to a branching
// file (a file responsible for splitting the pipeline into multiple parallel
// paths). In the case of a branching file we use that in preference because
// otherwise multiple parallel paths will resolve to the same output.
int defaultValueIndex = -1;
if(branchInputs) {
defaultValueIndex = allResolved.findIndexOf { PipelineFile inp ->
branchInputs.any { PipelineFile pf -> pf.path == inp.path }
}
}
if(defaultValueIndex<0)
defaultValueIndex = 0
return defaultValueIndex
}
@CompileStatic
void setDefaultIfNull() {
if(!out) {
String defaultOut = getDefaultOutput()
if(defaultOut != null)
out = [getDefaultOutput()]
else
out = []
}
assert out != null
assert out.isEmpty() || out[0] != null
}
}
PipelineOutput getOutputImpl() {
OutputResolver resolver = new OutputResolver()
if(resolver.out == null || this.currentFileNameTransform) { // Output not set elsewhere, or set dynamically based on inputs
resolver.resolveOutput()
}
else {
log.info "Using previously set output: ${this.@output}"
}
resolver.setDefaultIfNull()
resolver.out = toOutputFolder(resolver.out)
resolver.baseOutput = toOutputFolder(resolver.baseOutput)[0]
Pipeline pipeline = Pipeline.currentRuntimePipeline.get()
String branchName = applyName ? pipeline.unappliedBranchNames.join(".") : null
PipelineOutput po = new PipelineOutput(resolver.out,
this.stageName,
resolver.baseOutput,
resolver.overrideOutputs,
inboundBranches,
{ o,replaced -> onNewOutputReferenced(pipeline, o, replaced)})
po.branchName = branchName
if(this.currentFileNameTransform instanceof FilterFileNameTransformer)
po.currentFilter = currentFileNameTransform
po.resolvedInputs = this.resolvedInputs
po.outputDirChangeListener = this.&outputTo
if(this.activeAccompanierPattern)
po.transformMode = "extend"
return po
}
/**
* A pipeline stage can specify outputs in different ways: explicitly (eg: via a
* prescriptive produce() or transform() statement), or implicitly (eg: via references
* to $output variables in exec statements). When outputs are specified explicitly,
* they are set directly on this.@output. In that case we prioritise those.
* However if outputs are not stated explicitly, we derive them by looking at
* all outputs that were referenced implicitly during the stage execution.
* <p>
* Here we finalise the outputs by transferring the implicit ones into the explicit
* output set.
*/
@CompileStatic
void resolveOutputs() {
if(!this.@output && this.allInferredOutputs) {
log.info "Using inferred outputs $allInferredOutputs as outputs because no explicit outputs set"
this.setRawOutput(this.allInferredOutputs)
}
}
/**
* Outputs that have been replaced by overriding from a filter whose extension was
* inferred by an output property reference
*/
List<String> replacedOutputs = []
/**
* Called by the embedded {@link PipelineOutput} object
* that wraps the $output variable whenever a new output
* is referenced in a pipeline.
*
* @param pipeline
* @param replaced if the output replaces a previously inferred output,
* the output that should be replaced. This happens when
* an output is inferred first using $output but then that
* becomes replaced by in input extension reference using
* $output.bam
*/
void onNewOutputReferenced(Pipeline pipeline, Object o, String replaced = null) {
assert o != null
assert !(o instanceof List)
if(!allInferredOutputs.contains(o))
allInferredOutputs << o;
if(!inferredOutputs.contains(o))
inferredOutputs << o;
if(replaced) {
allInferredOutputs.remove(replaced)
inferredOutputs.remove(replaced)
}
if(applyName && pipeline) {
pipeline.nameApplied=true
}
if(replaced) {
this.setRawOutput(Utils.box(this.@output).collect {
if(it.path == replaced) { replacedOutputs.add(replaced) ; return o } else { return it }
})
}
}
def getOutputs() {
def raw = getOutput()
// Used to 'box' the result, but now this is a PipelineOutput that supports direct access by index,
// so should not need it
// def result = Utils.box(raw)
raw.multiple = true
return raw
}
def getOutputByIndex(int index) {
try {
PipelineOutput origOutput = getOutput()
List o = origOutput.output
assert o instanceof List
String result = o[index]
String origDefaultOutput = origOutput.defaultOutput
if(result == null) {
log.info "No previously set output at $index from ${o.size()} outputs. Synthesizing from index based on first output"
if(o[0].indexOf('.')>=0) {
result = o[0].replaceAll("\\.([^.]*)\$",".${index+1}.\$1")
origDefaultOutput = origDefaultOutput.replaceAll("\\.([^.]*)\$",".${index+1}.\$1")
}
else
result = o[0] + (index+1)
}
log.info "Query for output $index base result = $result"
// result = trackOutput(result)
Pipeline pipeline = Pipeline.currentRuntimePipeline.get()
def overrideOutputs = (origOutput.overrideOutputs && origOutput.overrideOutputs.size() > index ? [ origOutput.overrideOutputs[index] ] : [] )
return new PipelineOutput([result],
origOutput.stageName,
origDefaultOutput,
overrideOutputs,
inboundBranches,
{ op,replaced -> onNewOutputReferenced(pipeline, op, replaced)})
}
catch(Exception e) {
e.printStackTrace()
}
}
private trackOutput(def output) {
log.info "Tracking output $output"
referencedOutputs << output
return output
}
void var(Map values) {
values.each { k,v ->
if(!this.localVariables.containsKey(k) && !this.extraBinding.variables.containsKey(k) && !Runner.binding.variables.containsKey(k) && !branch.properties.containsKey(k)) {
log.info "Using default value of variable $k = $v"
if(v instanceof Closure)
this.localVariables[k] = v()
else
this.localVariables[k] = v
}
}
}
void requires(Map values) {
values.each { k,v ->
if([localVariables,
extraBinding.variables,
Runner.binding.variables,
branch.properties,
Pipeline.currentRuntimePipeline.get().variables].any { it.containsKey(k) })
{
// Variable found, OK
return
}
throw new PipelineError(
"""
Pipeline stage ${this.stageName} requires a parameter $k but this parameter was not specified
You can specify it in the following ways:
1. add 'using' to the pipeline definition: ${this.stageName}.using($k:<value>)
2. define the variable in your pipeline script: $k="<value>"
3. provide it from the command line by adding a flag: -p $k=<value>
The parameter $k is described as follows:
$v
""".stripIndent())
}
}
/**
* Coerce all of the arguments (which may be an array of Strings or a single String) to
* point to files in the local directory.
* This method is (and must remain) side-effect free
*
* @return A list of the same type as the inputs (PipelineFile,String)
*/
List toOutputFolder(outputs) {
List boxed = Utils.box(outputs)
if(outputDirectory == null)
return Utils.toDir(boxed, ".")
else
return Utils.toDir(boxed, outputDirectory)
}
void checkAccompaniedOutputs(List<PipelineFile> inputsToCheck) {
def outDir = this.outputDirectory
if(((outDir == null) || (outDir==".")) && this.activeAccompanierPattern) {
List<PipelineFile> resolved = getResolvedInputs() + inputsToCheck
PipelineFile matchedInput = resolved.find { this.activeAccompanierPattern.matcher(it.toString()) }
// If one of the resolved inputs matches an accompanying pattern, then it should
// output to the same directory as the output
if(matchedInput) {
log.info "Input $matchedInput matches accompanier pattern $activeAccompanierPattern"
// TODO - CLOUD - should really be java.nio.path ops
File f = new File(matchedInput.toString())
if(!f.parentFile)
f = new File(new File("."),f.name)
this.outputDirectory = f.parentFile.path
}
}
}
/**
* Input(s) to a pipeline stage
*/
List<PipelineFile> input
/**
* Wrapper that intercepts calls to resolve input properties. This is what
* is returned to a pipeline stage, not the raw input!
*/
PipelineInput inputWrapper
/**
* All input wrappers that got referenced during a pipeline stage, keyed on
* index
*/
Map<Integer,PipelineInput> allUsedInputWrappers = new TreeMap()
/**
* If this context is spawning a new branch in the pipeline, the inputs that
* are responsible for the branch are set here. This is used in certain cases
* to set a different default output
*/
List<PipelineFile> branchInputs
/**
* The inputs to be passed to the next stage of the pipeline.
* Usually this is the same as context.output but it doesn't have
* to be.
*/
List<PipelineFile> nextInputs
@CompileStatic
List<PipelineFile> getRawInput() {
return this.@input
}
@CompileStatic
void setNextInputs(List<PipelineFile> nextInps) {
assert nextInps instanceof List
List notPF = nextInps.grep { !(it instanceof PipelineFile) }
if(!notPF.isEmpty()) {
assert false: "The following next inputs were not pipeline files!: " + notPF.join(',')
}
this.nextInputs = nextInps
}
/**
* Return the value of the specified input<n> where n is the
* parameter supplied (index of input to resolve).
*
* @param i
* @return
*/
@CompileStatic
PipelineInput getInputByIndex(int i) {
PipelineInput wrapper = new PipelineInput(this.@input, pipelineStages, this.aliases)
wrapper.currentFilter = currentFilter
wrapper.defaultValueIndex = i
List<PipelineFile> boxed = Collections.unmodifiableList(this.input)
if(boxed.size()<=i) {
wrapper.parentError = new InputMissingError("Stage '$stageName' expected $i or more inputs but fewer provided", this)
}
else {
this.allResolvedInputs << input[i]
}
if(!inputWrapper)
this.inputWrapper = wrapper
if(!allUsedInputWrappers.containsKey(i)) {
allUsedInputWrappers[i] = wrapper
}
return wrapper
}
/**
* Check if there is an input, if so, return it.
*/
def getInput() {
if(!inputWrapper || inputWrapper instanceof MultiPipelineInput) {
inputWrapper = new PipelineInput(this.@input, pipelineStages, this.aliases)
this.allUsedInputWrappers[0] = inputWrapper
}
inputWrapper.currentFilter = currentFilter
return inputWrapper
}
def setInput(def inp) {
this.@input = Utils.box(inp)
}
def getInputs() {
if(!inputWrapper || !(inputWrapper instanceof MultiPipelineInput)) {
this.inputWrapper = new MultiPipelineInput(this.@input, pipelineStages, this.aliases)
this.allUsedInputWrappers[0] = inputWrapper
}
inputWrapper.currentFilter = currentFilter
return this.inputWrapper;
}
/**
* Output stream, only opened if the stage body references
* the "out" variable
*/
FileOutputStream outFile
/**
* Iterate through the file line by line and pass each line to the given closure.
* Output lines for which the closure returns true to the output.
* Lines beginning with # will not be passed to the body,
* but will be automatically output.
*/
void filterLines(Closure c) {
if(!input)
throw new PipelineError("Attempt to grep on input but no input available")
if(Runner.testMode)
throw new PipelineTestAbort("Would execute filterLines on input $input")
PipelineFile usedInput = Utils.first(input)
// if(!probeMode && !(usedInput.storage instanceof LocalFileSystemStorageLayer))
// throw new PipelineError("Built in filtering only works with local file system storage")