-
Notifications
You must be signed in to change notification settings - Fork 594
/
Session.groovy
1302 lines (1083 loc) · 38.5 KB
/
Session.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-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
import java.lang.reflect.Method
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import com.google.common.hash.HashCode
import com.upplication.s3fs.S3OutputStream
import groovy.transform.CompileDynamic
import groovy.transform.CompileStatic
import groovy.transform.Memoized
import groovy.transform.PackageScope
import groovy.util.logging.Slf4j
import groovyx.gpars.GParsConfig
import groovyx.gpars.dataflow.operator.DataflowProcessor
import nextflow.config.Manifest
import nextflow.container.ContainerConfig
import nextflow.dag.DAG
import nextflow.exception.AbortOperationException
import nextflow.exception.AbortSignalException
import nextflow.exception.IllegalConfigException
import nextflow.exception.MissingLibraryException
import nextflow.executor.ExecutorFactory
import nextflow.extension.ChannelFactory
import nextflow.file.FileHelper
import nextflow.file.FilePorter
import nextflow.processor.ErrorStrategy
import nextflow.processor.TaskFault
import nextflow.processor.TaskHandler
import nextflow.processor.TaskProcessor
import nextflow.script.BaseScript
import nextflow.script.ProcessConfig
import nextflow.script.ProcessFactory
import nextflow.script.ScriptBinding
import nextflow.script.ScriptFile
import nextflow.script.ScriptRunner
import nextflow.script.WorkflowMetadata
import nextflow.trace.AnsiLogObserver
import nextflow.trace.GraphObserver
import nextflow.trace.ReportObserver
import nextflow.trace.StatsObserver
import nextflow.trace.TimelineObserver
import nextflow.trace.TraceFileObserver
import nextflow.trace.TraceObserver
import nextflow.trace.TraceRecord
import nextflow.trace.WebLogObserver
import nextflow.trace.WorkflowStats
import nextflow.util.Barrier
import nextflow.util.ConfigHelper
import nextflow.util.Duration
import nextflow.util.HistoryFile
import nextflow.util.NameGenerator
import sun.misc.Signal
import sun.misc.SignalHandler
import static nextflow.Const.S3_UPLOADER_CLASS
/**
* Holds the information on the current execution
*
* @author Paolo Di Tommaso <paolo.ditommaso@gmail.com>
*/
@Slf4j
@CompileStatic
class Session implements ISession {
/**
* Keep a list of all processor created
*/
final Collection<DataflowProcessor> allOperators = new ConcurrentLinkedQueue<>()
final List<Closure> igniters = new ArrayList<>(10)
/**
* Creates process executors
*/
ExecutorFactory executorFactory
/**
* Script binding
*/
ScriptBinding binding
/**
* Holds the configuration object
*/
Map config
/**
* Enable / disable tasks result caching
*/
boolean cacheable
/**
* whenever it has been launched in resume mode
*/
boolean resumeMode
/**
* The folder where tasks temporary files are stored
*/
Path workDir
/**
* Bucket work directory for cloud based executors
*/
Path bucketDir
/**
* The folder where the main script is contained
*/
Path baseDir
/**
* The pipeline script name (without parent path)
*/
String scriptName
/**
* The main script object
*/
BaseScript script
/**
* Mnemonic name of this run instance
*/
String runName
/**
* Folder(s) containing libs and classes to be added to the classpath
*/
List<Path> libDir
/**
* List files that concurrent on the session configuration
*/
List<Path> configFiles
String profile
String commandLine
/**
* Local path where script generated classes are saved
*/
private Path classesDir
private Path binDir
private Map<String,Path> binEntries = [:]
/**
* The unique identifier of this session
*/
private UUID uniqueId
private DAG dag
private CacheDB cache
private Barrier processesBarrier = new Barrier()
private Barrier monitorsBarrier = new Barrier()
private volatile boolean cancelled
private volatile boolean aborted
private volatile boolean terminated
private volatile ExecutorService execService
private volatile TaskFault fault
private volatile Throwable error
private Queue<Closure<Void>> shutdownCallbacks = new ConcurrentLinkedQueue<>()
private int poolSize
private List<TraceObserver> observers = Collections.emptyList()
private Closure errorAction
private boolean statsEnabled
private WorkflowMetadata workflowMetadata
private WorkflowStats workflowStats
private FilePorter filePorter
boolean getStatsEnabled() { statsEnabled }
private boolean dumpHashes
private List<String> dumpChannels
boolean getDumpHashes() { dumpHashes }
List<String> getDumpChannels() { dumpChannels }
TaskFault getFault() { fault }
Throwable getError() { error }
WorkflowStats getWorkflowStats() { workflowStats }
WorkflowMetadata getWorkflowMetadata() { workflowMetadata }
Path getClassesDir() { classesDir }
ScriptBinding.ParamsMap getParams() { binding.getParams() }
boolean ansiLog
private AnsiLogObserver ansiLogObserver
AnsiLogObserver getAnsiLogObserver() { ansiLogObserver }
FilePorter getFilePorter() { filePorter }
/**
* Creates a new session with an 'empty' (default) configuration
*/
Session() {
create(new LinkedHashMap(10))
}
/**
* Create a new session given the configuration specified
*
* @param config
*/
Session(Map obj) {
final config = obj instanceof ConfigObject ? obj.toMap() : obj
create(config)
}
/**
* @return The current session {@link UUID}
*/
UUID getUniqueId() { uniqueId }
/**
* @return The session max number of thread allowed
*/
int getPoolSize() { poolSize }
CacheDB getCache() { cache }
/**
* Creates a new session using the configuration properties provided
*
* @param binding
*/
private void create( Map config ) {
assert config != null
this.config = config
this.dumpHashes = config.dumpHashes
this.dumpChannels = (List<String>)config.dumpChannels
this.binding = new ScriptBinding()
// -- poor man session object dependency injection
Global.setSession(this)
Global.setConfig(config)
// -- init static structs
NF.init()
// -- cacheable flag
cacheable = config.cacheable
// -- sets resumeMode and uniqueId
if( config.resume ) {
resumeMode = true
uniqueId = UUID.fromString(config.resume as String)
}
else {
uniqueId = UUID.randomUUID()
}
log.debug "Session uuid: $uniqueId"
// -- set the run name
this.runName = config.runName ?: NameGenerator.next()
log.debug "Run name: $runName"
// -- normalize taskConfig object
if( config.process == null ) config.process = [:]
if( config.env == null ) config.env = [:]
if( !config.poolSize ) {
final cpus = Runtime.getRuntime().availableProcessors()
config.poolSize = cpus==1 ? 2 : cpus
}
// -- set the thread pool size
this.poolSize = config.poolSize as int
log.debug "Executor pool size: ${poolSize}"
// -- DAG object
this.dag = new DAG()
// -- init work dir
this.workDir = ((config.workDir ?: 'work') as Path).complete()
this.setLibDir( config.libDir as String )
// -- file porter config
this.filePorter = new FilePorter(this)
}
/**
* Initialize the session workDir, libDir, baseDir and scriptName variables
*/
Session init( ScriptFile scriptFile, List<String> args=null ) {
if(!workDir.mkdirs()) throw new AbortOperationException("Cannot create work-dir: $workDir -- Make sure you have write permissions or specify a different directory by using the `-w` command line option")
log.debug "Work-dir: ${workDir.toUriString()} [${FileHelper.getPathFsType(workDir)}]"
if( config.bucketDir ) {
this.bucketDir = config.bucketDir as Path
log.debug "Bucket-dir: ${bucketDir.toUriString()}"
}
if( scriptFile ) {
// the folder that contains the main script
this.setBaseDir(scriptFile.main.parent)
// set the script name attribute
this.setScriptName(scriptFile.main.name)
}
// set the byte-code target directory
this.classesDir = FileHelper.createLocalDir()
this.executorFactory = new ExecutorFactory()
this.observers = createObservers()
this.statsEnabled = observers.any { it.enableMetrics() }
this.workflowMetadata = new WorkflowMetadata(this, scriptFile)
// configure script params
binding.setParams( (Map)config.params )
binding.setArgs( new ScriptRunner.ArgsList(args) )
cache = new CacheDB(uniqueId,runName).open()
return this
}
Session setBinding(ScriptBinding binding ) {
this.binding = binding
return this
}
ProcessFactory newProcessFactory(BaseScript script) {
new ProcessFactory(script, this)
}
/**
* Given the `run` command line options creates the required {@link TraceObserver}s
*
* @param runOpts The {@code CmdRun} object holding the run command options
* @return A list of {@link TraceObserver} objects or an empty list
*/
@PackageScope
List<TraceObserver> createObservers() {
def result = new ArrayList(10)
createStatsObserver(result) // keep as first, because following may depend on it
createTraceFileObserver(result)
createReportObserver(result)
createTimelineObserver(result)
createDagObserver(result)
createWebLogObserver(result)
createAnsiLogObserver(result)
return result
}
protected void createAnsiLogObserver(Collection<TraceObserver> result) {
if( ansiLog ) {
this.ansiLogObserver = new AnsiLogObserver()
result << ansiLogObserver
}
}
/**
* Create workflow message observer
* @param result
*/
protected void createWebLogObserver(Collection<TraceObserver> result) {
Boolean isEnabled = config.navigate('weblog.enabled') as Boolean
String url = config.navigate('weblog.url') as String
if (isEnabled) {
if ( !url ) url = WebLogObserver.DEF_URL
def observer = new WebLogObserver(url)
result << observer
}
}
protected void createStatsObserver(Collection<TraceObserver> result) {
final observer = new StatsObserver()
this.workflowStats = observer.stats
result << observer
}
/**
* Create workflow report file observer
*/
protected void createReportObserver(Collection<TraceObserver> result) {
Boolean isEnabled = config.navigate('report.enabled') as Boolean
if( isEnabled ) {
String fileName = config.navigate('report.file')
def maxTasks = config.navigate('report.maxTasks', ReportObserver.DEF_MAX_TASKS) as int
if( !fileName ) fileName = ReportObserver.DEF_FILE_NAME
def report = (fileName as Path).complete()
def observer = new ReportObserver(report)
observer.maxTasks = maxTasks
result << observer
}
}
/**
* Create timeline report file observer
*/
protected void createTimelineObserver(Collection<TraceObserver> result) {
Boolean isEnabled = config.navigate('timeline.enabled') as Boolean
if( isEnabled ) {
String fileName = config.navigate('timeline.file')
if( !fileName ) fileName = TimelineObserver.DEF_FILE_NAME
def traceFile = (fileName as Path).complete()
def observer = new TimelineObserver(traceFile)
result << observer
}
}
protected void createDagObserver(Collection<TraceObserver> result) {
Boolean isEnabled = config.navigate('dag.enabled') as Boolean
if( isEnabled ) {
String fileName = config.navigate('dag.file')
if( !fileName ) fileName = GraphObserver.DEF_FILE_NAME
def traceFile = (fileName as Path).complete()
def observer = new GraphObserver(traceFile)
result << observer
}
}
/*
* create the execution trace observer
*/
protected void createTraceFileObserver(Collection<TraceObserver> result) {
Boolean isEnabled = config.navigate('trace.enabled') as Boolean
if( isEnabled ) {
String fileName = config.navigate('trace.file')
if( !fileName ) fileName = TraceFileObserver.DEF_FILE_NAME
def traceFile = (fileName as Path).complete()
def observer = new TraceFileObserver(traceFile)
config.navigate('trace.raw') { it -> observer.useRawNumbers(it == true) }
config.navigate('trace.sep') { observer.separator = it }
config.navigate('trace.fields') { observer.setFieldsAndFormats(it) }
result << observer
}
}
/*
* intercepts interruption signal i.e. CTRL+C
* - on the first invoke session#abort
* - on third force termination with System#exit
*/
private void registerSignalHandlers() {
int c = 0
final ctrl_c = { Signal sig ->
switch( ++c ) {
case 1: abort(new AbortSignalException(sig)); println ''; break
case 2: println "One more CTRL+C to force exit"; break
default: log.info 'Adieu'; System.exit(1)
}
} as SignalHandler
// -- abort session handler
final abort_h = { Signal sig -> abort(new AbortSignalException(sig)) } as SignalHandler
// -- register handlers
Signal.handle( new Signal("INT"), ctrl_c)
Signal.handle( new Signal("TERM"), abort_h)
Signal.handle( new Signal("HUP"), abort_h)
}
void addIgniter( Closure action ) {
igniters.add(action)
}
void fireDataflowNetwork() {
if( !NextflowMeta.instance.isDsl2() )
return
// bridge any dataflow queue into a broadcast channel
ChannelFactory.broadcast()
log.debug "Ignite dataflow network (${igniters.size()})"
for( def action : igniters ) {
try {
action.call()
}
catch( Exception e ) {
log.error(e.message ?: "Failed to trigger dataflow network", e)
abort(e)
break
}
}
}
/**
* Dump the current dataflow network listing
* the status of active processes and operators
* for debugging purpose
*/
String dumpNetworkStatus() {
try {
def msg = dag.dumpActiveNodes()
msg ? "The following nodes are still active:\n" + msg : null
}
catch( Exception e ) {
log.debug "Unexpected error dumping DGA status", e
return null
}
}
Session start() {
log.debug "Session start invoked"
// register shut-down cleanup hooks
registerSignalHandlers()
// create tasks executor
execService = Executors.newFixedThreadPool(poolSize)
// signal start to trace observers
observers.each { trace -> trace.onFlowStart(this) }
return this
}
ScriptBinding getBinding() { binding }
@Memoized
ClassLoader getClassLoader() { getClassLoader0() }
@PackageScope
ClassLoader getClassLoader0() {
// extend the class-loader if required
final gcl = new GroovyClassLoader()
final libraries = ConfigHelper.resolveClassPaths(getLibDir())
for( Path lib : libraries ) {
def path = lib.complete()
log.debug "Adding to the classpath library: ${path}"
gcl.addClasspath(path.toString())
}
return gcl
}
Barrier getBarrier() { monitorsBarrier }
/**
* The folder where script binaries file are located, by default the folder 'bin'
* in the script base directory
*/
Path getBinDir() { binDir }
Map<String,Path> getBinEntries() { binEntries ?: Collections.<String,Path>emptyMap() }
void setBaseDir( Path baseDir ) {
this.baseDir = baseDir
def path = baseDir.resolve('bin')
if( path.exists() && path.isDirectory() ) {
this.binDir = path
this.binEntries = findBinEntries(path)
}
else {
log.debug "Script base path does not exist or is not a directory: ${path}"
}
}
protected Map<String,Path> findBinEntries(Path path) {
Map<String,Path> result = [:]
path
.listFiles { file -> Files.isExecutable(file) }
.each { Path file -> result.put(file.name,file) }
return result
}
void setLibDir( String str ) {
if( !str ) return
def files = str.split( File.pathSeparator ).collect { String it -> Paths.get(it) }
if( !files ) return
libDir = []
for( Path file : files ) {
if( !file.exists() )
throw new MissingLibraryException("Cannot find specified library: ${file.complete()}")
libDir << file
}
}
List<Path> getLibDir() {
if( libDir )
return libDir
libDir = []
def localLib = baseDir ? baseDir.resolve('lib') : Paths.get('lib')
if( localLib.exists() ) {
log.debug "Using default localLib path: $localLib"
libDir << localLib
}
return libDir
}
Map getConfigEnv() {
if( !config.env )
return Collections.emptyMap()
if( config.env instanceof Map )
return new LinkedHashMap((Map)config.env)
throw new IllegalStateException("Not a valid config env object: $config.env")
}
@Memoized
Manifest getManifest() {
if( !config.manifest )
return new Manifest()
if( config.manifest instanceof Map )
return new Manifest(config.manifest as Map)
else {
log.warn "Invalid config manifest definition [${this.getClass().getName()}]"
return new Manifest()
}
}
/**
* Await the termination of all processors
*/
void await() {
log.debug "Session await"
processesBarrier.awaitCompletion()
log.debug "Session await > all process finished"
terminated = true
monitorsBarrier.awaitCompletion()
log.debug "Session await > all barriers passed"
}
void destroy() {
try {
log.trace "Session > destroying"
if( !aborted ) {
allOperatorsJoin()
log.trace "Session > after processors join"
}
shutdown0()
log.trace "Session > after cleanup"
execService.shutdown()
execService = null
log.trace "Session > executor shutdown"
// -- close db
cache?.close()
// -- shutdown s3 uploader
shutdownS3Uploader()
// -- cleanup script classes dir
classesDir.deleteDir()
}
finally {
// -- update the history file
if( HistoryFile.DEFAULT.exists() ) {
HistoryFile.DEFAULT.update(runName,isSuccess())
}
log.trace "Session destroyed"
}
}
final private allOperatorsJoin() {
int attempts=0
while( allOperators.size() ) {
if( attempts++>0 )
log.debug "This looks weird, attempt number $attempts to join pending operators"
final itr = allOperators.iterator()
while( itr.hasNext() ) {
final op = itr.next()
op.join()
itr.remove()
}
}
}
final protected void shutdown0() {
log.trace "Shutdown: $shutdownCallbacks"
while( shutdownCallbacks.size() ) {
def hook = shutdownCallbacks.poll()
try {
if( hook )
hook.call()
}
catch( Exception e ) {
log.debug "Failed to execute shutdown hook: $hook", e
}
}
// -- invoke observers completion handlers
def copy = new ArrayList<TraceObserver>(observers)
for( TraceObserver observer : copy ) {
try {
if( observer )
observer.onFlowComplete()
}
catch( Exception e ) {
log.debug "Failed to invoke observer completion handler: $observer", e
}
}
// -- global
Global.cleanUp()
}
/**
* Halt the pipeline execution choosing exiting immediately or completing current
* pending task depending the chosen {@link ErrorStrategy}
*
* @param fault A {@link TaskFault} instance representing the error that caused the pipeline to stop
*/
void fault(TaskFault fault, TaskHandler handler=null) {
if( this.fault ) { return }
this.fault = fault
if( fault.task && fault.task.errorAction == ErrorStrategy.FINISH ) {
cancel(handler)
}
else {
abort(fault.error)
}
}
/**
* Cancel the pipeline execution waiting for the current running tasks to complete
*/
@PackageScope
void cancel(TaskHandler handler) {
log.info "Execution cancelled -- Finishing pending tasks before exit"
cancelled = true
notifyError(handler)
executorFactory.signalExecutors()
processesBarrier.forceTermination()
allOperators *. terminate()
}
/**
* Terminate the pipeline execution killing all running tasks
*
* @param cause A {@link Throwable} instance representing the execution that caused the pipeline execution to abort
*/
void abort(Throwable cause = null) {
if( aborted ) return
log.debug "Session aborted -- Cause: ${cause?.message ?: cause ?: '-'}"
aborted = true
error = cause
try {
// log the dataflow network status
def status = dumpNetworkStatus()
if( status )
log.debug(status)
// force termination
notifyError(null)
executorFactory.signalExecutors()
processesBarrier.forceTermination()
monitorsBarrier.forceTermination()
operatorsForceTermination()
}
catch( Throwable e ) {
log.debug "Unexpected error while aborting execution", e
}
}
private void operatorsForceTermination() {
def operators = allOperators.toArray() as DataflowProcessor[]
for( int i=0; i<operators.size(); i++ ) {
operators[i].terminate()
}
}
@PackageScope
void forceTermination() {
terminated = true
processesBarrier.forceTermination()
monitorsBarrier.forceTermination()
allOperators *. terminate()
execService?.shutdownNow()
GParsConfig.shutdown()
}
boolean isTerminated() { terminated }
boolean isAborted() { aborted }
boolean isCancelled() { cancelled }
boolean isSuccess() { !aborted && !cancelled }
void processRegister(TaskProcessor process) {
log.debug ">>> barrier register (process: ${process.name})"
processesBarrier.register(process)
}
void processDeregister(TaskProcessor process) {
log.debug "<<< barrier arrive (process: ${process.name})"
processesBarrier.arrive(process)
}
DAG getDag() { this.dag }
ExecutorService getExecService() { execService }
/**
* Validate the config file
*
* @param processNames The list of process names defined in the pipeline script
*/
void validateConfig(Collection<String> processNames) {
def warns = validateConfig0(processNames)
for( String str : warns )
log.warn str
}
protected List<String> validateConfig0(Collection<String> processNames) {
def result = []
if( !(config.process instanceof Map) )
return result
// verifies that all process config names have a match with a defined process
def keys = (config.process as Map).keySet()
for(String key : keys) {
String name = null
if( key.startsWith('$') ) {
name = key.substring(1)
}
else if( key.startsWith('withName:') ) {
name = key.substring('withName:'.length())
}
if( name )
checkValidProcessName(processNames, name, result)
}
return result
}
/**
* Check that the specified name belongs to the list of existing process names
*
* @param selector The process name to check
* @param processNames The list of processes declared in the workflow script
* @param errorMessage A list of strings used to return the error message to the caller
* @return {@code true} if the name specified belongs to the list of process names or {@code false} otherwise
*/
protected boolean checkValidProcessName(Collection<String> processNames, String selector, List<String> errorMessage) {
final matches = processNames.any { name -> ProcessConfig.matchesSelector(name, selector) }
if( matches )
return true
def suggestion = processNames.closest(selector)
def message = "There's no process matching config selector: $selector"
if( suggestion )
message += " -- Did you mean: ${suggestion.first()}?"
errorMessage << message.toString()
return false
}
/**
* Register a shutdown hook to close services when the session terminates
* @param Closure
*/
void onShutdown( Closure shutdown ) {
if( !shutdown )
return
shutdownCallbacks << shutdown
}
void notifyProcessCreate(TaskProcessor process) {
for( int i=0; i<observers.size(); i++ ) {
final observer = observers.get(i)
try {
observer.onProcessCreate(process)
}
catch( Exception e ) {
log.debug(e.getMessage(), e)
}
}
}
void notifyProcessTerminate(TaskProcessor process) {
for( int i=0; i<observers.size(); i++ ) {
final observer = observers.get(i)
try {
observer.onProcessTerminate(process)
}
catch( Exception e ) {
log.debug(e.getMessage(), e)
}
}
}
/**
* Notifies that a task has been submitted
*/
void notifyTaskSubmit( TaskHandler handler ) {
final task = handler.task
log.info "[${task.hashLog}] ${task.runType.message} > ${task.name}"
// -- save a record in the cache index
cache.putIndexAsync(handler)
for( int i=0; i<observers.size(); i++ ) {
final observer = observers.get(i)
try {
observer.onProcessSubmit(handler, handler.getTraceRecord())
}
catch( Exception e ) {
log.debug(e.getMessage(), e)
}
}
}
/**
* Notifies task start event
*/
void notifyTaskStart( TaskHandler handler ) {
for( int i=0; i<observers.size(); i++ ) {
final observer = observers.get(i)
try {
observer.onProcessStart(handler, handler.getTraceRecord())
}
catch( Exception e ) {
log.debug(e.getMessage(), e)
}
}
}
/**
* Notifies task termination event
*
* @param handler
*/
void notifyTaskComplete( TaskHandler handler ) {
// save the completed task in the cache DB
final trace = handler.getTraceRecord()
cache.putTaskAsync(handler, trace)
// notify the event to the observers
for( int i=0; i<observers.size(); i++ ) {
final observer = observers.get(i)
try {
observer.onProcessComplete(handler, trace)
}
catch( Exception e ) {
log.debug(e.getMessage(), e)
}
}
}
void notifyTaskCached( TaskHandler handler ) {