-
Notifications
You must be signed in to change notification settings - Fork 515
/
__init__.py
2615 lines (2316 loc) · 92.8 KB
/
__init__.py
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
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2022, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
from abc import abstractmethod
import asyncio
import os
import sys
import contextlib
import time
import json
import stat
import shutil
import shlex
import threading
import concurrent.futures
import subprocess
import tempfile
from functools import partial
from collections import namedtuple
import base64
import uuid
import re
import math
from snakemake.target_jobs import encode_target_jobs_cli_args
from fractions import Fraction
from snakemake.shell import shell
from snakemake.logging import logger
from snakemake.stats import Stats
from snakemake.utils import makedirs
from snakemake.io import get_wildcard_names, Wildcards
from snakemake.exceptions import print_exception, get_exception_origin
from snakemake.exceptions import format_error, RuleException, log_verbose_traceback
from snakemake.exceptions import (
WorkflowError,
SpawnedJobError,
CacheMissException,
)
from snakemake.common import (
Mode,
get_container_image,
get_uuid,
lazy_property,
async_lock,
)
from snakemake.executors.common import format_cli_arg, join_cli_args
# TODO move each executor into a separate submodule
async def sleep():
# do not sleep on CI. In that case we just want to quickly test everything.
if os.environ.get("CI") != "true":
await asyncio.sleep(10)
else:
await asyncio.sleep(1)
class AbstractExecutor:
def __init__(
self,
workflow,
dag,
printreason=False,
quiet=False,
printshellcmds=False,
printthreads=True,
keepincomplete=False,
):
self.workflow = workflow
self.dag = dag
self.quiet = quiet
self.printreason = printreason
self.printshellcmds = printshellcmds
self.printthreads = printthreads
self.latency_wait = workflow.latency_wait
self.keepincomplete = keepincomplete
def get_default_remote_provider_args(self):
return join_cli_args(
[
self.workflow_property_to_arg("default_remote_prefix"),
self.workflow_property_to_arg("default_remote_provider", attr="name"),
]
)
def get_set_resources_args(self):
return format_cli_arg(
"--set-resources",
[
f"{rule}:{name}={value}"
for rule, res in self.workflow.overwrite_resources.items()
for name, value in res.items()
],
skip=not self.workflow.overwrite_resources,
)
def get_default_resources_args(self, default_resources=None):
default_resources = default_resources or self.workflow.default_resources
return format_cli_arg("--default-resources", default_resources.args)
def get_resource_scopes_args(self):
return format_cli_arg(
"--set-resource-scopes", self.workflow.overwrite_resource_scopes
)
def get_resource_declarations_dict(self, job):
def isdigit(i):
s = str(i)
# Adapted from https://stackoverflow.com/a/1265696
if s[0] in ("-", "+"):
return s[1:].isdigit()
return s.isdigit()
excluded_resources = self.workflow.resource_scopes.excluded.union(
{"_nodes", "_cores"}
)
return {
resource: value
for resource, value in job.resources.items()
if isinstance(value, int)
# need to check bool seperately because bool is a subclass of int
and isdigit(value) and resource not in excluded_resources
}
def get_resource_declarations(self, job):
resources = [
f"{resource}={value}"
for resource, value in self.get_resource_declarations_dict(job).items()
]
return format_cli_arg("--resources", resources)
def run_jobs(self, jobs, callback=None, submit_callback=None, error_callback=None):
"""Run a list of jobs that is ready at a given point in time.
By default, this method just runs each job individually.
This method can be overwritten to submit many jobs in a more efficient way than one-by-one.
Note that in any case, for each job, the callback functions have to be called individually!
"""
for job in jobs:
self.run(
job,
callback=callback,
submit_callback=submit_callback,
error_callback=error_callback,
)
def run(self, job, callback=None, submit_callback=None, error_callback=None):
"""Run a specific job or group job."""
self._run(job)
callback(job)
@abstractmethod
def shutdown(self):
...
@abstractmethod
def cancel(self):
...
def _run(self, job):
job.check_protected_output()
self.printjob(job)
def rule_prefix(self, job):
return "local " if job.is_local else ""
def printjob(self, job):
job.log_info(skip_dynamic=True)
def print_job_error(self, job, msg=None, **kwargs):
job.log_error(msg, **kwargs)
def handle_job_success(self, job):
pass
def handle_job_error(self, job):
pass
class DryrunExecutor(AbstractExecutor):
def printjob(self, job):
super().printjob(job)
if job.is_group():
for j in job.jobs:
self.printcache(j)
else:
self.printcache(job)
def printcache(self, job):
cache_mode = self.workflow.get_cache_mode(job.rule)
if cache_mode:
if self.workflow.output_file_cache.exists(job, cache_mode):
logger.info(
"Output file {} will be obtained from global between-workflow cache.".format(
job.output[0]
)
)
else:
logger.info(
"Output file {} will be written to global between-workflow cache.".format(
job.output[0]
)
)
class RealExecutor(AbstractExecutor):
def __init__(
self,
workflow,
dag,
printreason=False,
quiet=False,
printshellcmds=False,
assume_shared_fs=True,
keepincomplete=False,
):
super().__init__(
workflow,
dag,
printreason=printreason,
quiet=quiet,
printshellcmds=printshellcmds,
keepincomplete=keepincomplete,
)
self.assume_shared_fs = assume_shared_fs
self.stats = Stats()
self.snakefile = workflow.main_snakefile
def register_job(self, job):
job.register()
def _run(self, job, callback=None, error_callback=None):
super()._run(job)
self.stats.report_job_start(job)
try:
self.register_job(job)
except IOError as e:
logger.info(
"Failed to set marker file for job started ({}). "
"Snakemake will work, but cannot ensure that output files "
"are complete in case of a kill signal or power loss. "
"Please ensure write permissions for the "
"directory {}".format(e, self.workflow.persistence.path)
)
def handle_job_success(
self,
job,
upload_remote=True,
handle_log=True,
handle_touch=True,
ignore_missing_output=False,
):
job.postprocess(
upload_remote=upload_remote,
handle_log=handle_log,
handle_touch=handle_touch,
ignore_missing_output=ignore_missing_output,
latency_wait=self.latency_wait,
assume_shared_fs=self.assume_shared_fs,
keep_metadata=self.workflow.keep_metadata,
)
self.stats.report_job_end(job)
def handle_job_error(self, job, upload_remote=True):
job.postprocess(
error=True,
assume_shared_fs=self.assume_shared_fs,
latency_wait=self.latency_wait,
)
def workflow_property_to_arg(
self, property, flag=None, quote=True, skip=False, invert=False, attr=None
):
if skip:
return ""
value = getattr(self.workflow, property)
if value is not None and attr is not None:
value = getattr(value, attr)
if flag is None:
flag = f"--{property.replace('_', '-')}"
if invert and isinstance(value, bool):
value = not value
return format_cli_arg(flag, value, quote=quote)
@lazy_property
def general_args(self):
"""Return a string to add to self.exec_job that includes additional
arguments from the command line. This is currently used in the
ClusterExecutor and CPUExecutor, as both were using the same
code. Both have base class of the RealExecutor.
"""
w2a = self.workflow_property_to_arg
return join_cli_args(
[
"--force",
"--keep-target-files",
"--keep-remote",
"--max-inventory-time 0",
"--nocolor",
"--notemp",
"--no-hooks",
"--nolock",
"--ignore-incomplete",
format_cli_arg("--keep-incomplete", self.keepincomplete),
w2a("rerun_triggers"),
w2a("cleanup_scripts", flag="--skip-script-cleanup"),
w2a("shadow_prefix"),
w2a("use_conda"),
w2a("conda_frontend"),
w2a("conda_prefix"),
w2a("conda_base_path", skip=not self.assume_shared_fs),
w2a("use_singularity"),
w2a("singularity_prefix"),
w2a("singularity_args"),
w2a("execute_subworkflows", flag="--no-subworkflows", invert=True),
w2a("max_threads"),
w2a("use_env_modules", flag="--use-envmodules"),
w2a("keep_metadata", flag="--drop-metadata", invert=True),
w2a("wrapper_prefix"),
w2a("overwrite_threads", flag="--set-threads"),
w2a("overwrite_scatter", flag="--set-scatter"),
w2a("local_groupid", skip=self.job_specific_local_groupid),
w2a("conda_not_block_search_path_envvars"),
w2a("overwrite_configfiles", flag="--configfiles"),
w2a("config_args", flag="--config"),
w2a("printshellcmds"),
w2a("latency_wait"),
w2a("scheduler_type", flag="--scheduler"),
format_cli_arg(
"--scheduler-solver-path",
os.path.dirname(sys.executable),
skip=not self.assume_shared_fs,
),
self.get_set_resources_args(),
self.get_default_remote_provider_args(),
self.get_default_resources_args(),
self.get_resource_scopes_args(),
self.get_workdir_arg(),
join_cli_args(self.additional_general_args()),
format_cli_arg("--mode", self.get_exec_mode()),
]
)
def additional_general_args(self):
"""Inherit this method to add stuff to the general args.
A list must be returned.
"""
return []
def get_workdir_arg(self):
return self.workflow_property_to_arg("overwrite_workdir", flag="--directory")
def get_job_args(self, job, **kwargs):
return join_cli_args(
[
format_cli_arg(
"--target-jobs", encode_target_jobs_cli_args(job.get_target_spec())
),
# Restrict considered rules for faster DAG computation.
# This does not work for updated jobs because they need
# to be updated in the spawned process as well.
format_cli_arg(
"--allowed-rules",
job.rules,
quote=False,
skip=job.is_branched or job.is_updated,
),
# Ensure that a group uses its proper local groupid.
format_cli_arg("--local-groupid", job.jobid, skip=not job.is_group()),
format_cli_arg("--cores", kwargs.get("cores", self.cores)),
format_cli_arg("--attempt", job.attempt),
format_cli_arg("--force-use-threads", not job.is_group()),
self.get_resource_declarations(job),
]
)
@property
def job_specific_local_groupid(self):
return True
def get_snakefile(self):
return self.snakefile
@abstractmethod
def get_python_executable(self):
...
@abstractmethod
def get_exec_mode(self):
...
@abstractmethod
def get_envvar_declarations(self):
...
def get_job_exec_prefix(self, job):
return ""
def get_job_exec_suffix(self, job):
return ""
def format_job_exec(self, job):
prefix = self.get_job_exec_prefix(job)
if prefix:
prefix += " &&"
suffix = self.get_job_exec_suffix(job)
if suffix:
suffix = f"&& {suffix}"
return join_cli_args(
[
prefix,
self.get_envvar_declarations(),
self.get_python_executable(),
"-m snakemake",
format_cli_arg("--snakefile", self.get_snakefile()),
self.get_job_args(job),
self.general_args,
suffix,
]
)
class TouchExecutor(RealExecutor):
def run(self, job, callback=None, submit_callback=None, error_callback=None):
super()._run(job)
try:
# Touching of output files will be done by handle_job_success
time.sleep(0.1)
callback(job)
except OSError as ex:
print_exception(ex, self.workflow.linemaps)
error_callback(job)
def handle_job_success(self, job):
super().handle_job_success(job, ignore_missing_output=True)
_ProcessPoolExceptions = (KeyboardInterrupt,)
try:
from concurrent.futures.process import BrokenProcessPool
_ProcessPoolExceptions = (KeyboardInterrupt, BrokenProcessPool)
except ImportError:
pass
class CPUExecutor(RealExecutor):
def __init__(
self,
workflow,
dag,
workers,
printreason=False,
quiet=False,
printshellcmds=False,
use_threads=False,
cores=1,
keepincomplete=False,
):
super().__init__(
workflow,
dag,
printreason=printreason,
quiet=quiet,
printshellcmds=printshellcmds,
keepincomplete=keepincomplete,
)
self.use_threads = use_threads
self.cores = cores
# Zero thread jobs do not need a thread, but they occupy additional workers.
# Hence we need to reserve additional workers for them.
workers = workers + 5 if workers is not None else 5
self.workers = workers
self.pool = concurrent.futures.ThreadPoolExecutor(max_workers=self.workers)
@property
def job_specific_local_groupid(self):
return False
def get_job_exec_prefix(self, job):
return f"cd {self.workflow.workdir_init}"
def get_exec_mode(self):
return Mode.subprocess
def get_python_executable(self):
return sys.executable
def get_envvar_declarations(self):
return ""
def get_job_args(self, job, **kwargs):
return f"{super().get_job_args(job, **kwargs)} --quiet"
def run(self, job, callback=None, submit_callback=None, error_callback=None):
super()._run(job)
if job.is_group():
# if we still don't have enough workers for this group, create a new pool here
missing_workers = max(len(job) - self.workers, 0)
if missing_workers:
self.workers += missing_workers
self.pool = concurrent.futures.ThreadPoolExecutor(
max_workers=self.workers
)
# the future waits for the entire group job
future = self.pool.submit(self.run_group_job, job)
else:
future = self.run_single_job(job)
future.add_done_callback(partial(self._callback, job, callback, error_callback))
def job_args_and_prepare(self, job):
job.prepare()
conda_env = (
job.conda_env.address if self.workflow.use_conda and job.conda_env else None
)
container_img = (
job.container_img_path if self.workflow.use_singularity else None
)
env_modules = job.env_modules if self.workflow.use_env_modules else None
benchmark = None
benchmark_repeats = job.benchmark_repeats or 1
if job.benchmark is not None:
benchmark = str(job.benchmark)
return (
job.rule,
job.input._plainstrings(),
job.output._plainstrings(),
job.params,
job.wildcards,
job.threads,
job.resources,
job.log._plainstrings(),
benchmark,
benchmark_repeats,
conda_env,
container_img,
self.workflow.singularity_args,
env_modules,
self.workflow.use_singularity,
self.workflow.linemaps,
self.workflow.debug,
self.workflow.cleanup_scripts,
job.shadow_dir,
job.jobid,
self.workflow.edit_notebook if self.dag.is_edit_notebook_job(job) else None,
self.workflow.conda_base_path,
job.rule.basedir,
self.workflow.sourcecache.runtime_cache_path,
)
def run_single_job(self, job):
if (
self.use_threads
or (not job.is_shadow and not job.is_run)
or job.is_template_engine
):
future = self.pool.submit(
self.cached_or_run, job, run_wrapper, *self.job_args_and_prepare(job)
)
else:
# run directive jobs are spawned into subprocesses
future = self.pool.submit(self.cached_or_run, job, self.spawn_job, job)
return future
def run_group_job(self, job):
"""Run a pipe or service group job.
This lets all items run simultaneously."""
# we only have to consider pipe or service groups because in local running mode,
# these are the only groups that will occur
futures = [self.run_single_job(j) for j in job]
n_non_service = sum(1 for j in job if not j.is_service)
while True:
n_finished = 0
for f in futures:
if f.done():
ex = f.exception()
if ex is not None:
# kill all shell commands of the other group jobs
# there can be only shell commands because the
# run directive is not allowed for pipe jobs
for j in job:
shell.kill(j.jobid)
raise ex
else:
n_finished += 1
if n_finished >= n_non_service:
# terminate all service jobs since all consumers are done
for j in job:
if j.is_service:
logger.info(
f"Terminating service job {j.jobid} since all consuming jobs are finished."
)
shell.terminate(j.jobid)
logger.info(
f"Service job {j.jobid} has been successfully terminated."
)
return
time.sleep(1)
def spawn_job(self, job):
cmd = self.format_job_exec(job)
try:
subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as e:
raise SpawnedJobError()
def cached_or_run(self, job, run_func, *args):
"""
Either retrieve result from cache, or run job with given function.
"""
cache_mode = self.workflow.get_cache_mode(job.rule)
try:
if cache_mode:
self.workflow.output_file_cache.fetch(job, cache_mode)
return
except CacheMissException:
pass
run_func(*args)
if cache_mode:
self.workflow.output_file_cache.store(job, cache_mode)
def shutdown(self):
self.pool.shutdown()
def cancel(self):
self.pool.shutdown()
def _callback(self, job, callback, error_callback, future):
try:
ex = future.exception()
if ex is not None:
raise ex
callback(job)
except _ProcessPoolExceptions:
self.handle_job_error(job)
# no error callback, just silently ignore the interrupt as the main scheduler is also killed
except SpawnedJobError:
# don't print error message, this is done by the spawned subprocess
error_callback(job)
except (Exception, BaseException) as ex:
self.print_job_error(job)
if self.workflow.verbose or (not job.is_group() and job.is_run):
print_exception(ex, self.workflow.linemaps)
error_callback(job)
def handle_job_success(self, job):
super().handle_job_success(job)
def handle_job_error(self, job):
super().handle_job_error(job)
if not self.keepincomplete:
job.cleanup()
self.workflow.persistence.cleanup(job)
class ClusterExecutor(RealExecutor):
"""Backend for distributed execution.
The key idea is that a job is converted into a script that invokes Snakemake again, in whatever environment is targeted. The script is submitted to some job management platform (e.g. a cluster scheduler like slurm).
This class can be specialized to generate more specific backends, also for the cloud.
"""
default_jobscript = "jobscript.sh"
def __init__(
self,
workflow,
dag,
cores,
jobname="snakejob.{name}.{jobid}.sh",
printreason=False,
quiet=False,
printshellcmds=False,
cluster_config=None,
local_input=None,
restart_times=None,
assume_shared_fs=True,
max_status_checks_per_second=1,
disable_default_remote_provider_args=False,
disable_default_resources_args=False,
disable_envvar_declarations=False,
keepincomplete=False,
):
from throttler import Throttler
local_input = local_input or []
super().__init__(
workflow,
dag,
printreason=printreason,
quiet=quiet,
printshellcmds=printshellcmds,
assume_shared_fs=assume_shared_fs,
keepincomplete=keepincomplete,
)
self.max_status_checks_per_second = max_status_checks_per_second
if not self.assume_shared_fs:
# use relative path to Snakefile
self.snakefile = os.path.relpath(workflow.main_snakefile)
self.is_default_jobscript = False
jobscript = workflow.jobscript
if jobscript is None:
jobscript = os.path.join(os.path.dirname(__file__), self.default_jobscript)
self.is_default_jobscript = True
try:
with open(jobscript) as f:
self.jobscript = f.read()
except IOError as e:
raise WorkflowError(e)
if not "jobid" in get_wildcard_names(jobname):
raise WorkflowError(
'Defined jobname ("{}") has to contain the wildcard {jobid}.'
)
self.jobname = jobname
self._tmpdir = None
self.cores = cores if cores else "all"
self.cluster_config = cluster_config if cluster_config else dict()
self.restart_times = restart_times
self.active_jobs = list()
self.lock = threading.Lock()
self.wait = True
self.wait_thread = threading.Thread(target=self._wait_thread)
self.wait_thread.daemon = True
self.wait_thread.start()
self.disable_default_remote_provider_args = disable_default_remote_provider_args
self.disable_default_resources_args = disable_default_resources_args
self.disable_envvar_declarations = disable_envvar_declarations
max_status_checks_frac = Fraction(
max_status_checks_per_second
).limit_denominator()
self.status_rate_limiter = Throttler(
rate_limit=max_status_checks_frac.numerator,
period=max_status_checks_frac.denominator,
)
def get_default_remote_provider_args(self):
if not self.disable_default_remote_provider_args:
return super().get_default_remote_provider_args()
else:
return ""
def get_default_resources_args(self, default_resources=None):
if not self.disable_default_resources_args:
return super().get_default_resources_args(default_resources)
else:
return ""
def get_workdir_arg(self):
if self.assume_shared_fs:
return super().get_workdir_arg()
return ""
def get_envvar_declarations(self):
if not self.disable_envvar_declarations:
return " ".join(
f"{var}={repr(os.environ[var])}" for var in self.workflow.envvars
)
else:
return ""
def get_python_executable(self):
return sys.executable if self.assume_shared_fs else "python"
def get_exec_mode(self):
return Mode.cluster
def get_job_args(self, job):
waitfiles_parameter = ""
if self.assume_shared_fs:
wait_for_files = []
wait_for_files.append(self.tmpdir)
wait_for_files.extend(job.get_wait_for_files())
# Only create extra file if we have more than 20 input files.
# This should not require the file creation in most cases.
if len(wait_for_files) > 20:
wait_for_files_file = self.get_jobscript(job) + ".waitforfilesfile.txt"
with open(wait_for_files_file, "w") as fd:
print(*wait_for_files, sep="\n", file=fd)
waitfiles_parameter = format_cli_arg(
"--wait-for-files-file", wait_for_files_file
)
else:
waitfiles_parameter = format_cli_arg("--wait-for-files", wait_for_files)
return f"{super().get_job_args(job)} {waitfiles_parameter}"
@abstractmethod
async def _wait_for_jobs(self):
...
def _wait_thread(self):
try:
asyncio.run(self._wait_for_jobs())
except Exception as e:
print(e)
self.workflow.scheduler.executor_error_callback(e)
def shutdown(self):
with self.lock:
self.wait = False
self.wait_thread.join()
if not self.workflow.immediate_submit:
# Only delete tmpdir (containing jobscripts) if not using
# immediate_submit. With immediate_submit, jobs can be scheduled
# after this method is completed. Hence we have to keep the
# directory.
shutil.rmtree(self.tmpdir)
def cancel(self):
self.shutdown()
def _run(self, job, callback=None, error_callback=None):
if self.assume_shared_fs:
job.remove_existing_output()
job.download_remote_input()
super()._run(job, callback=callback, error_callback=error_callback)
@property
def tmpdir(self):
if self._tmpdir is None:
self._tmpdir = tempfile.mkdtemp(dir=".snakemake", prefix="tmp.")
return os.path.abspath(self._tmpdir)
def get_jobname(self, job):
return job.format_wildcards(self.jobname, cluster=self.cluster_wildcards(job))
def get_jobscript(self, job):
f = self.get_jobname(job)
if os.path.sep in f:
raise WorkflowError(
"Path separator ({}) found in job name {}. "
"This is not supported.".format(os.path.sep, f)
)
return os.path.join(self.tmpdir, f)
def write_jobscript(self, job, jobscript):
exec_job = self.format_job_exec(job)
try:
content = self.jobscript.format(
properties=job.properties(cluster=self.cluster_params(job)),
exec_job=exec_job,
)
except KeyError as e:
if self.is_default_jobscript:
raise e
else:
raise WorkflowError(
f"Error formatting custom jobscript {self.workflow.jobscript}: value for {e} not found.\n"
"Make sure that your custom jobscript is defined as expected."
)
logger.debug("Jobscript:\n{}".format(content))
with open(jobscript, "w") as f:
print(content, file=f)
os.chmod(jobscript, os.stat(jobscript).st_mode | stat.S_IXUSR | stat.S_IRUSR)
def cluster_params(self, job):
"""Return wildcards object for job from cluster_config."""
cluster = self.cluster_config.get("__default__", dict()).copy()
cluster.update(self.cluster_config.get(job.name, dict()))
# Format values with available parameters from the job.
for key, value in list(cluster.items()):
if isinstance(value, str):
try:
cluster[key] = job.format_wildcards(value)
except NameError as e:
if job.is_group():
msg = (
"Failed to format cluster config for group job. "
"You have to ensure that your default entry "
"does not contain any items that group jobs "
"cannot provide, like {rule}, {wildcards}."
)
else:
msg = (
"Failed to format cluster config "
"entry for job {}.".format(job.rule.name)
)
raise WorkflowError(msg, e)
return cluster
def cluster_wildcards(self, job):
return Wildcards(fromdict=self.cluster_params(job))
def handle_job_success(self, job):
super().handle_job_success(
job, upload_remote=False, handle_log=False, handle_touch=False
)
def handle_job_error(self, job):
# TODO what about removing empty remote dirs?? This cannot be decided
# on the cluster node.
super().handle_job_error(job, upload_remote=False)
logger.debug("Cleanup job metadata.")
# We have to remove metadata here as well.
# It will be removed by the CPUExecutor in case of a shared FS,
# but we might not see the removal due to filesystem latency.
# By removing it again, we make sure that it is gone on the host FS.
if not self.keepincomplete:
self.workflow.persistence.cleanup(job)
# Also cleanup the jobs output files, in case the remote job
# was not able to, due to e.g. timeout.
logger.debug("Cleanup failed jobs output files.")
job.cleanup()
def print_cluster_job_error(self, job_info, jobid):
job = job_info.job
kind = (
"rule {}".format(job.rule.name)
if not job.is_group()
else "group job {}".format(job.groupid)
)
logger.error(
"Error executing {} on cluster (jobid: {}, external: "
"{}, jobscript: {}). For error details see the cluster "
"log and the log files of the involved rule(s).".format(
kind, jobid, job_info.jobid, job_info.jobscript
)
)
GenericClusterJob = namedtuple(
"GenericClusterJob",
"job jobid callback error_callback jobscript jobfinished jobfailed",
)
class GenericClusterExecutor(ClusterExecutor):
def __init__(
self,
workflow,
dag,
cores,
submitcmd="qsub",
statuscmd=None,
cancelcmd=None,
cancelnargs=None,
sidecarcmd=None,
cluster_config=None,
jobname="snakejob.{rulename}.{jobid}.sh",
printreason=False,
quiet=False,
printshellcmds=False,
restart_times=0,
assume_shared_fs=True,
max_status_checks_per_second=1,
keepincomplete=False,
):
self.submitcmd = submitcmd
if not assume_shared_fs and statuscmd is None:
raise WorkflowError(
"When no shared filesystem can be assumed, a "
"status command must be given."
)
self.statuscmd = statuscmd
self.cancelcmd = cancelcmd
self.sidecarcmd = sidecarcmd
self.cancelnargs = cancelnargs
self.external_jobid = dict()
# We need to collect all external ids so we can properly cancel even if
# the status update queue is running.