/
ProcessConfig.groovy
727 lines (630 loc) · 20.9 KB
/
ProcessConfig.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
/*
* Copyright 2013-2019, Centre for Genomic Regulation (CRG)
*
* 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.script
import java.util.regex.Pattern
import groovy.transform.PackageScope
import groovy.util.logging.Slf4j
import nextflow.Const
import nextflow.NF
import nextflow.exception.ConfigParseException
import nextflow.exception.IllegalConfigException
import nextflow.exception.IllegalDirectiveException
import nextflow.exception.ScriptRuntimeException
import nextflow.executor.BashWrapperBuilder
import nextflow.processor.ConfigList
import nextflow.processor.ErrorStrategy
import nextflow.processor.TaskConfig
import static nextflow.util.CacheHelper.HashMode
import nextflow.script.params.*
/**
* Holds the process configuration properties
*
* @author Paolo Di Tommaso <paolo.ditommaso@gmail.com>
*/
@Slf4j
class ProcessConfig implements Map<String,Object>, Cloneable {
static final public transient LABEL_REGEXP = ~/[a-zA-Z]([a-zA-Z0-9_]*[a-zA-Z0-9]+)?/
static final public List<String> DIRECTIVES = [
'afterScript',
'beforeScript',
'echo',
'cache',
'conda',
'cpus',
'container',
'containerOptions',
'cleanup',
'clusterOptions',
'disk',
'echo',
'errorStrategy',
'executor',
'ext',
'gpu',
'machineType',
'queue',
'label',
'maxErrors',
'maxForks',
'maxRetries',
'memory',
'module',
'penv',
'pod',
'publishDir',
'scratch',
'shell',
'storeDir',
'tag',
'time',
'validExitStatus',
// input-output qualifiers
'file',
'set',
'val',
'each',
'env',
'stdin',
'stdout',
'stageInMode',
'stageOutMode'
]
/**
* Names of directives that can be used more than once in the process definition
*/
@PackageScope
static final List<String> repeatableDirectives = ['label','module','pod','publishDir']
/**
* Default directives values
*/
@PackageScope
static final Map<String,Object> DEFAULT_CONFIG = [
echo: false,
cacheable: true,
shell: BashWrapperBuilder.BASH,
validExitStatus: [0],
maxRetries: 0,
maxErrors: -1,
errorStrategy: ErrorStrategy.TERMINATE
]
/**
* Map instance that holds the process configuration
*/
@Delegate
@PackageScope
protected Map<String,Object> configProperties
/**
* Reference to the main script object
*/
private BaseScript ownerScript
/**
* Name of the process to which this config object is associated
*/
private String processName
/**
* When {@code true} a {@link MissingPropertyException} is thrown when
* trying to access a property not existing
*/
private boolean throwExceptionOnMissingProperty
/**
* List of process input definitions
*/
private inputs = new InputsList()
/**
* List of process output definitions
*/
private outputs = new OutputsList()
/**
* Initialize the taskConfig object with the defaults values
*
* @param script The owner {@code BaseScript} configuration object
*/
ProcessConfig( BaseScript script ) {
ownerScript = script
configProperties = new LinkedHashMap()
configProperties.putAll( DEFAULT_CONFIG )
}
/* Only for testing purpose */
@PackageScope
ProcessConfig( Map delegate ) {
configProperties = delegate
}
@Override
ProcessConfig clone() {
def copy = (ProcessConfig)super.clone()
copy.@configProperties = new LinkedHashMap<>(configProperties)
copy.@inputs = inputs.clone()
copy.@outputs = outputs.clone()
return copy
}
/**
* Define the name of the process to which this config object is associated
*
* @param name String representing the name of the process to which this config object is associated
* @return The {@link ProcessConfig} instance itself
*/
@PackageScope
ProcessConfig setProcessName( String name ) {
this.processName = name
return this
}
/**
* Enable special behavior to allow the configuration object
* invoking directive method from the process DSL
*
* @param value {@code true} enable capture mode, {@code false} otherwise
* @return The object itself
*/
@PackageScope
ProcessConfig throwExceptionOnMissingProperty( boolean value ) {
this.throwExceptionOnMissingProperty = value
return this
}
private void checkName(String name) {
if( DIRECTIVES.contains(name) ) return
if( name == 'when' ) return
String message = "Unknown process directive: `$name`"
def alternatives = DIRECTIVES.closest(name)
if( alternatives.size()==1 ) {
message += '\n\nDid you mean of these?'
alternatives.each {
message += "\n $it"
}
}
throw new IllegalDirectiveException(message)
}
Object invokeMethod(String name, Object args) {
/*
* This is need to patch #497 -- what is happening is that when in the config file
* is defined a directive like `memory`, `cpus`, etc in by using a closure,
* this closure is interpreted as method definition and it get invoked if a
* directive with the same name is defined in the process definition.
* To avoid that the offending property is removed from the map before the method
* is evaluated.
*/
if( configProperties.get(name) instanceof Closure )
configProperties.remove(name)
this.metaClass.invokeMethod(this,name,args)
}
def methodMissing( String name, def args ) {
checkName(name)
if( args instanceof Object[] ) {
if( args.size()==1 ) {
configProperties[ name ] = args[0]
}
else {
configProperties[ name ] = args.toList()
}
}
else {
configProperties[ name ] = args
}
return this
}
@Override
Object getProperty( String name ) {
switch( name ) {
case 'inputs':
return getInputs()
case 'outputs':
return getOutputs()
case 'cacheable':
return isCacheable()
case 'ext':
if( !configProperties.containsKey('ext') ) {
configProperties.put('ext', new HashMap())
}
return configProperties.get('ext')
default:
if( configProperties.containsKey(name) )
return configProperties.get(name)
else if( throwExceptionOnMissingProperty )
throw new MissingPropertyException("Unknown variable '$name'", name, null)
else
return null
}
}
Object put( String name, Object value ) {
if( name in repeatableDirectives ) {
final result = configProperties.get(name)
configProperties.remove(name)
this.metaClass.invokeMethod(this, name, value)
return result
}
else {
if( name == 'gpu' ) gpuWarn()
return configProperties.put(name,value)
}
}
@PackageScope
BaseScript getOwnerScript() { ownerScript }
@PackageScope
TaskConfig createTaskConfig() {
new TaskConfig(configProperties)
}
/**
* Apply the settings defined in the configuration file for the given annotation label, for example:
*
* ```
* process {
* withLabel: foo {
* cpus = 1
* memory = 2.gb
* }
* }
* ```
*
* @param configDirectives
* A map object modelling the setting defined defined by the user in the nextflow configuration file *
* @param category
* The type of annotation either {@code withLabel:} or {@code withName:}
* @param processLabel
* A specific label representing the object holding the configuration setting to apply
*/
@PackageScope
void applyConfigForLabel( Map<String,?> configDirectives, String category, String processLabel ) {
assert category in ['withLabel:','withName:']
assert processName != null
assert processLabel != null
for( String rule : configDirectives.keySet() ) {
if( !rule.startsWith(category) )
continue
final isLabel = category=='withLabel:'
final pattern = rule.substring(category.size()).trim()
final target = isLabel ? processLabel : processName
if( !matchesSelector(target, pattern) )
continue
log.debug "Config settings `$rule` matches ${isLabel ? "label `$target` for process with name $processName" : "process $processName"}"
def settings = configDirectives.get(rule)
if( settings instanceof Map ) {
applyConfigSettings(settings)
}
else if( settings != null ) {
throw new ConfigParseException("Unknown config settings for label `$processLabel` -- settings=$settings ")
}
}
}
static boolean matchesSelector( String target, String pattern ) {
final isNegated = pattern.startsWith('!')
if( isNegated )
pattern = pattern.substring(1).trim()
return Pattern.compile(pattern).matcher(target).matches() ^ isNegated
}
/**
* Apply the settings defined in the configuration file to the actual process configuration object
*
* @param settings
* A map object modelling the setting defined defined by the user in the nextflow configuration file
*/
@PackageScope
void applyConfigSettings(Map<String,?> settings) {
if( !settings )
return
for( Entry<String,?> entry: settings ) {
if( entry.key.startsWith('$'))
continue
if( entry.key.startsWith("withLabel:") || entry.key.startsWith("withName:"))
continue
if( !DIRECTIVES.contains(entry.key) )
log.warn "Unknown directive `$entry.key` for process `$processName`"
if( entry.key == 'params' ) // <-- patch issue #242
continue
if( entry.key == 'ext' ) {
if( this.getProperty('ext') instanceof Map ) {
// update missing 'ext' properties found in 'process' scope
def ext = this.getProperty('ext') as Map
entry.value.each { String k, v -> ext[k] = v }
}
continue
}
this.put(entry.key,entry.value)
}
}
/**
* Apply the process settings defined globally in the process config scope
*
* @param processDefaults
* A map object representing the setting to be applied to the process
* (provided it does not already define a different value for
* the same config setting).
*
*/
@PackageScope
void applyConfigDefaults( Map processDefaults ) {
for( String key : processDefaults.keySet() ) {
if( key == 'params' )
continue
final value = processDefaults.get(key)
final current = this.getProperty(key)
if( key == 'ext' ) {
if( value instanceof Map && current instanceof Map ) {
final ext = current as Map
value.each { k,v -> if(!ext.containsKey(k)) ext.put(k,v) }
}
}
else if( !this.containsKey(key) || (DEFAULT_CONFIG.containsKey(key) && current==DEFAULT_CONFIG.get(key)) ) {
this.put(key, value)
}
}
}
/**
* Type shortcut to {@code #configProperties.inputs}
*/
InputsList getInputs() {
inputs
}
/**
* Type shortcut to {@code #configProperties.outputs}
*/
OutputsList getOutputs() {
outputs
}
/*
* note: without this method definition {@link BaseScript#echo} will be invoked
*/
ProcessConfig echo( value ) {
configProperties.echo = value
return this
}
/// input parameters
InParam _in_val( obj ) {
new ValueInParam(this).bind(obj)
}
InParam _in_file( obj ) {
new FileInParam(this).bind(obj)
}
InParam _in_each( obj ) {
new EachInParam(this).bind(obj)
}
InParam _in_set( Object... obj ) {
new SetInParam(this).bind(obj)
}
InParam _in_stdin( obj = null ) {
def result = new StdInParam(this)
if( obj ) result.bind(obj)
result
}
InParam _in_env( obj ) {
new EnvInParam(this).bind(obj)
}
/// output parameters
OutParam _out_val( Object obj ) {
new ValueOutParam(this).bind(obj)
}
OutParam _out_file( Object obj ) {
// note: check that is a String type to avoid to force
// the evaluation of GString object to a string
if( obj instanceof String && obj == '-' )
new StdOutParam(this).bind(obj)
else
new FileOutParam(this).bind(obj)
}
OutParam _out_set( Object... obj ) {
new SetOutParam(this) .bind(obj)
}
OutParam _out_stdout( obj = null ) {
def result = new StdOutParam(this).bind('-')
if( obj ) {
if(NF.isDsl2()) throw new ScriptRuntimeException("Process `stdout` output channel should not be specified when using DSL 2 -- Use `stdout()` instead")
result.into(obj)
}
result
}
/**
* Defines a special *dummy* input parameter, when no inputs are
* provided by the user for the current task
*/
void fakeInput() {
new DefaultInParam(this)
}
void fakeOutput() {
new DefaultOutParam(this)
}
boolean isCacheable() {
def value = configProperties.cache
if( value == null )
return true
if( value instanceof Boolean )
return value
if( value instanceof String && value in Const.BOOL_NO )
return false
return true
}
HashMode getHashMode() {
HashMode.of(configProperties.cache) ?: HashMode.STANDARD
}
protected boolean isValidLabel(String lbl) {
def p = lbl.indexOf('=')
if( p==-1 )
return LABEL_REGEXP.matcher(lbl).matches()
def left = lbl.substring(0,p)
def right = lbl.substring(p+1)
return LABEL_REGEXP.matcher(left).matches() && LABEL_REGEXP.matcher(right).matches()
}
/**
* Implements the process {@code label} directive.
*
* Note this directive can be specified (invoked) more than one time in
* the process context.
*
* @param lbl
* The label to be attached to the process.
* @return
* The {@link ProcessConfig} instance itself.
*/
ProcessConfig label(String lbl) {
if( !lbl ) return this
// -- check that label has a valid syntax
if( !isValidLabel(lbl) )
throw new IllegalConfigException("Not a valid process label: $lbl -- Label must consist of alphanumeric characters or '_', must start with an alphabetic character and must end with an alphanumeric character")
// -- get the current label, it must be a list
def allLabels = (List)configProperties.get('label')
if( !allLabels ) {
allLabels = new ConfigList()
configProperties.put('label', allLabels)
}
// -- avoid duplicates
if( !allLabels.contains(lbl) )
allLabels.add(lbl)
return this
}
List<String> getLabels() {
(List<String>) configProperties.get('label') ?: Collections.emptyList()
}
/**
* Implements the process {@code module} directive.
*
* See also http://modules.sourceforge.net
*
* @param moduleName
* The module name to be used to execute the process.
* @return
* The {@link ProcessConfig} instance itself.
*/
ProcessConfig module( moduleName ) {
// when no name is provided, just exit
if( !moduleName )
return this
def result = (List)configProperties.module
if( result == null ) {
result = new ConfigList()
configProperties.put('module', result)
}
if( moduleName instanceof List )
result.addAll(moduleName)
else
result.add(moduleName)
return this
}
/**
* Implements the {@code errorStrategy} directive
*
* @see ErrorStrategy
*
* @param strategy
* A string representing the error strategy to be used.
* @return
* The {@link ProcessConfig} instance itself.
*/
ProcessConfig errorStrategy( strategy ) {
configProperties.put('errorStrategy', strategy)
return this
}
/**
* Allow the user to specify publishDir directive as a map eg:
*
* publishDir path:'/some/dir', mode: 'copy'
*
* @param params
* A map representing the the publishDir setting
* @return
* The {@link ProcessConfig} instance itself
*/
ProcessConfig publishDir(Map params) {
if( !params )
return this
def dirs = (List)configProperties.get('publishDir')
if( !dirs ) {
dirs = new ConfigList()
configProperties.put('publishDir', dirs)
}
dirs.add(params)
return this
}
/**
* Allow the user to specify publishDir directive with a path and a list of named parameters, eg:
*
* publishDir '/some/dir', mode: 'copy'
*
* @param params
* A map representing the publishDir properties
* @param target
* The target publishDir path
* @return
* The {@link ProcessConfig} instance itself
*/
ProcessConfig publishDir(Map params, target) {
params.put('path', target)
publishDir( params )
}
/**
* Allow the user to specify the publishDir as a string path, eg:
*
* publishDir '/some/dir'
*
* @param target
* The target publishDir path
* @return
* The {@link ProcessConfig} instance itself
*/
ProcessConfig publishDir( target ) {
if( target instanceof List ) {
for( Object item : target ) { publishDir(item) }
}
else if( target instanceof Map ) {
publishDir( target as Map )
}
else {
publishDir([path: target])
}
return this
}
/**
* Allow use to specify K8s `pod` options
*
* @param entry
* A map object representing pod config options
* @return
* The {@link ProcessConfig} instance itself
*/
ProcessConfig pod( Map entry ) {
if( !entry )
return this
def allOptions = (List)configProperties.get('pod')
if( !allOptions ) {
allOptions = new ConfigList()
configProperties.put('pod', allOptions)
}
allOptions.add(entry)
return this
}
ProcessConfig gpu( Map params, value ) {
gpuWarn()
if( value instanceof Number ) {
if( params.limit==null )
params.limit=value
else if( params.request==null )
params.request=value
}
else if( value != null )
throw new IllegalArgumentException("Not a valid gpu directive value: $value [${value.getClass().getName()}]")
gpu(params)
return this
}
ProcessConfig gpu( value ) {
gpuWarn()
if( value instanceof Number )
configProperties.put('gpu', [limit: value])
else if( value instanceof Map )
configProperties.put('gpu', value)
else if( value != null )
throw new IllegalArgumentException("Not a valid gpu directive value: $value [${value.getClass().getName()}]")
return this
}
private void gpuWarn() {
log.warn1 "Directive `gpu` is an experimental feature -- it may change in a feature release"
}
}