forked from snakemake/snakemake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dag.py
executable file
·2196 lines (1940 loc) · 79.9 KB
/
dag.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 2021, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
import html
import os
import sys
import shutil
import textwrap
import time
import tarfile
from collections import defaultdict, Counter, deque, namedtuple
from itertools import chain, filterfalse, groupby
from functools import partial
from pathlib import Path
import uuid
import math
from snakemake.io import PeriodicityDetector, wait_for_files, is_flagged, IOFile
from snakemake.jobs import Reason, JobFactory, GroupJobFactory, Job
from snakemake.exceptions import MissingInputException
from snakemake.exceptions import MissingRuleException, AmbiguousRuleException
from snakemake.exceptions import CyclicGraphException, MissingOutputException
from snakemake.exceptions import IncompleteFilesException, ImproperOutputException
from snakemake.exceptions import PeriodicWildcardError
from snakemake.exceptions import RemoteFileException, WorkflowError, ChildIOException
from snakemake.exceptions import InputFunctionException
from snakemake.logging import logger
from snakemake.common import DYNAMIC_FILL, group_into_chunks
from snakemake.deployment import conda, singularity
from snakemake.output_index import OutputIndex
from snakemake import workflow
PotentialDependency = namedtuple("PotentialDependency", ["file", "jobs", "known"])
class Batch:
"""Definition of a batch for calculating only a partial DAG."""
def __init__(self, rulename: str, idx: int, batches: int):
assert idx <= batches
assert idx > 0
self.rulename = rulename
self.idx = idx
self.batches = batches
def get_batch(self, items: list):
"""Return the defined batch of the given items.
Items are usually input files."""
# make sure that we always consider items in the same order
if len(items) < self.batches:
raise WorkflowError(
"Batching rule {} has less input files than batches. "
"Please choose a smaller number of batches.".format(self.rulename)
)
items = sorted(items)
batch_len = math.floor(len(items) / self.batches)
# self.batch is one-based, hence we have to subtract 1
idx = self.idx - 1
i = idx * batch_len
if self.is_final:
# extend the last batch to cover rest of list
return items[i:]
else:
return items[i : i + batch_len]
@property
def is_final(self):
return self.idx == self.batches
def __str__(self):
return "{}/{} (rule {})".format(self.idx, self.batches, self.rulename)
class DAG:
"""Directed acyclic graph of jobs."""
def __init__(
self,
workflow,
rules=None,
dryrun=False,
targetfiles=None,
targetrules=None,
forceall=False,
forcerules=None,
forcefiles=None,
priorityfiles=None,
priorityrules=None,
untilfiles=None,
untilrules=None,
omitfiles=None,
omitrules=None,
ignore_ambiguity=False,
force_incomplete=False,
force_params_changed=False,
ignore_incomplete=False,
notemp=False,
keep_remote_local=False,
batch=None,
):
self.dryrun = dryrun
self.dependencies = defaultdict(partial(defaultdict, set))
self.depending = defaultdict(partial(defaultdict, set))
self._needrun = set()
self._priority = dict()
self._reason = defaultdict(Reason)
self._finished = set()
self._dynamic = set()
self._len = 0
self.workflow = workflow
self.rules = set(rules)
self.ignore_ambiguity = ignore_ambiguity
self.targetfiles = targetfiles
self.targetrules = targetrules
self.priorityfiles = priorityfiles
self.priorityrules = priorityrules
self.targetjobs = set()
self.prioritytargetjobs = set()
self._ready_jobs = set()
self.notemp = notemp
self.keep_remote_local = keep_remote_local
self._jobid = dict()
self.job_cache = dict()
self.conda_envs = dict()
self.container_imgs = dict()
self._progress = 0
self._group = dict()
self._n_until_ready = defaultdict(int)
self._running = set()
self.job_factory = JobFactory()
self.group_job_factory = GroupJobFactory()
self.forcerules = set()
self.forcefiles = set()
self.untilrules = set()
self.untilfiles = set()
self.omitrules = set()
self.omitfiles = set()
self.updated_subworkflow_files = set()
if forceall:
self.forcerules.update(self.rules)
elif forcerules:
self.forcerules.update(forcerules)
if forcefiles:
self.forcefiles.update(forcefiles)
if untilrules:
self.untilrules.update(set(rule.name for rule in untilrules))
if untilfiles:
self.untilfiles.update(untilfiles)
if omitrules:
self.omitrules.update(set(rule.name for rule in omitrules))
if omitfiles:
self.omitfiles.update(omitfiles)
self.has_dynamic_rules = any(rule.dynamic_output for rule in self.rules)
self.omitforce = set()
self.batch = batch
if batch is not None and not batch.is_final:
# Since not all input files of a batching rule are considered, we cannot run
# beyond that rule.
# For the final batch, we do not need to omit anything.
self.omitrules.add(batch.rulename)
self.force_incomplete = force_incomplete
self.force_params_changed = force_params_changed
self.ignore_incomplete = ignore_incomplete
self.periodic_wildcard_detector = PeriodicityDetector()
self.update_output_index()
def init(self, progress=False):
"""Initialise the DAG."""
for job in map(self.rule2job, self.targetrules):
job = self.update([job], progress=progress, create_inventory=True)
self.targetjobs.add(job)
for file in self.targetfiles:
job = self.update(
self.file2jobs(file),
file=file,
progress=progress,
create_inventory=True,
)
self.targetjobs.add(job)
self.cleanup()
self.check_incomplete()
if self.force_params_changed:
self.rerun_params_changed()
self.update_needrun(create_inventory=True)
self.set_until_jobs()
self.delete_omitfrom_jobs()
self.update_jobids()
self.check_directory_outputs()
# check if remaining jobs are valid
for i, job in enumerate(self.jobs):
job.is_valid()
def check_directory_outputs(self):
"""Check that no output file is contained in a directory output of the same or another rule."""
outputs = sorted(
{(os.path.abspath(f), job) for job in self.jobs for f in job.output}
)
for i in range(len(outputs) - 1):
(a, job_a), (b, job_b) = outputs[i : i + 2]
try:
common = os.path.commonpath([a, b])
except ValueError:
# commonpath raises error if windows drives are different.
continue
if a != b and common == os.path.commonpath([a]) and job_a != job_b:
raise ChildIOException(parent=outputs[i], child=outputs[i + 1])
@property
def checkpoint_jobs(self):
for job in self.needrun_jobs:
if job.is_checkpoint:
yield job
def update_checkpoint_outputs(self):
workflow.checkpoints.future_output = set(
f for job in self.checkpoint_jobs for f in job.output
)
def update_jobids(self):
for job in self.jobs:
if job not in self._jobid:
self._jobid[job] = len(self._jobid)
def cleanup_workdir(self):
for io_dir in set(
os.path.dirname(io_file)
for job in self.jobs
for io_file in chain(job.output, job.input)
if not os.path.exists(io_file)
):
if os.path.exists(io_dir) and not len(os.listdir(io_dir)):
os.removedirs(io_dir)
def cleanup(self):
self.job_cache.clear()
final_jobs = set(self.bfs(self.dependencies, *self.targetjobs))
todelete = [job for job in self.dependencies if job not in final_jobs]
for job in todelete:
try:
self._needrun.remove(job)
except KeyError:
pass
# delete all pointers from dependencies to this job
for dep in self.dependencies[job]:
try:
del self.depending[dep][job]
except KeyError:
# In case the pointer has been deleted before or
# never created, we can simply continue.
pass
# delete all dependencies
del self.dependencies[job]
try:
# delete all pointers to downstream dependencies
del self.depending[job]
except KeyError:
pass
def create_conda_envs(
self, dryrun=False, forceall=False, init_only=False, quiet=False
):
# First deduplicate based on job.conda_env_file
jobs = self.jobs if forceall else self.needrun_jobs
env_set = {
(job.conda_env_file, job.container_img_url)
for job in jobs
if job.conda_env_file
}
# Then based on md5sum values
self.conda_envs = dict()
for (env_file, simg_url) in env_set:
simg = None
if simg_url and self.workflow.use_singularity:
assert (
simg_url in self.container_imgs
), "bug: must first pull singularity images"
simg = self.container_imgs[simg_url]
env = conda.Env(
env_file,
self.workflow,
container_img=simg,
cleanup=self.workflow.conda_cleanup_pkgs,
)
self.conda_envs[(env_file, simg_url)] = env
if not init_only:
for env in self.conda_envs.values():
if not dryrun or not quiet:
env.create(dryrun)
def pull_container_imgs(self, dryrun=False, forceall=False, quiet=False):
# First deduplicate based on job.conda_env_file
jobs = self.jobs if forceall else self.needrun_jobs
img_set = {
(job.container_img_url, job.is_containerized)
for job in jobs
if job.container_img_url
}
for img_url, is_containerized in img_set:
img = singularity.Image(img_url, self, is_containerized)
if not dryrun or not quiet:
img.pull(dryrun)
self.container_imgs[img_url] = img
def update_output_index(self):
"""Update the OutputIndex."""
self.output_index = OutputIndex(self.rules)
def check_incomplete(self):
"""Check if any output files are incomplete. This is done by looking up
markers in the persistence module."""
if not self.ignore_incomplete:
incomplete = self.incomplete_files
if incomplete:
if self.force_incomplete:
logger.debug("Forcing incomplete files:")
logger.debug("\t" + "\n\t".join(incomplete))
self.forcefiles.update(incomplete)
else:
raise IncompleteFilesException(incomplete)
def rerun_params_changed(self):
"""Force rerun of files for which parameters changed."""
files = self.params_changed_files
if files:
logger.debug("Forcing files for which parameters changed:")
logger.debug("\t" + "\n\t".join(files))
self.forcefiles.update(files)
def incomplete_external_jobid(self, job):
"""Return the external jobid of the job if it is marked as incomplete.
Returns None, if job is not incomplete, or if no external jobid has been
registered or if force_incomplete is True.
"""
if self.force_incomplete:
return None
jobids = self.workflow.persistence.external_jobids(job)
if len(jobids) == 1:
return jobids[0]
elif len(jobids) > 1:
raise WorkflowError(
"Multiple different external jobids registered "
"for output files of incomplete job {} ({}). This job "
"cannot be resumed. Execute Snakemake with --rerun-incomplete "
"to fix this issue.".format(job.jobid, jobids)
)
def check_dynamic(self):
"""Check dynamic output and update downstream rules if necessary."""
if self.has_dynamic_rules:
for job in filter(
lambda job: (job.dynamic_output and not self.needrun(job)),
list(self.jobs),
):
self.update_dynamic(job)
self.postprocess()
def is_edit_notebook_job(self, job):
return self.workflow.edit_notebook and job.targetfile in self.targetfiles
@property
def dynamic_output_jobs(self):
"""Iterate over all jobs with dynamic output files."""
return (job for job in self.jobs if job.dynamic_output)
@property
def jobs(self):
"""All jobs in the DAG."""
return self.dependencies.keys()
@property
def needrun_jobs(self):
"""Jobs that need to be executed."""
return filterfalse(self.finished, self._needrun)
@property
def local_needrun_jobs(self):
"""Iterate over all jobs that need to be run and are marked as local."""
return filter(lambda job: job.is_local, self.needrun_jobs)
@property
def finished_jobs(self):
"""Iterate over all jobs that have been finished."""
return filter(self.finished, self.jobs)
@property
def ready_jobs(self):
"""Jobs that are ready to execute."""
return self._ready_jobs
def needrun(self, job):
"""Return whether a given job needs to be executed."""
return job in self._needrun
def priority(self, job):
"""Return priority of given job."""
return self._priority[job]
def noneedrun_finished(self, job):
"""
Return whether a given job is finished or was not
required to run at all.
"""
return not self.needrun(job) or self.finished(job)
def reason(self, job):
"""Return the reason of the job execution."""
return self._reason[job]
def finished(self, job):
"""Return whether a job is finished."""
return job in self._finished
def dynamic(self, job):
"""
Return whether a job is dynamic (i.e. it is only a placeholder
for those that are created after the job with dynamic output has
finished.
"""
if job.is_group():
for j in job:
if j in self._dynamic:
return True
else:
return job in self._dynamic
def requested_files(self, job):
"""Return the files a job requests."""
return set(*self.depending[job].values())
@property
def incomplete_files(self):
"""Return list of incomplete files."""
return list(
chain(
*(
job.output
for job in filter(
self.workflow.persistence.incomplete,
filterfalse(self.needrun, self.jobs),
)
)
)
)
@property
def params_changed_files(self):
"""Return list of files for which parameters changed."""
return list(
chain(
*(
job.output
for job in filter(
self.workflow.persistence.params_changed,
filterfalse(self.needrun, self.jobs),
)
)
)
)
@property
def newversion_files(self):
"""Return list of files where the current version is newer than the
recorded version.
"""
return list(
chain(
*(
job.output
for job in filter(self.workflow.persistence.newversion, self.jobs)
)
)
)
def missing_temp(self, job):
"""
Return whether a temp file that is input of the given job is missing.
"""
for job_, files in self.depending[job].items():
if self.needrun(job_) and any(not f.exists for f in files):
return True
return False
def check_and_touch_output(
self,
job,
wait=3,
ignore_missing_output=False,
no_touch=False,
force_stay_on_remote=False,
):
"""Raise exception if output files of job are missing."""
expanded_output = [job.shadowed_path(path) for path in job.expanded_output]
if job.benchmark:
expanded_output.append(job.benchmark)
if not ignore_missing_output:
try:
wait_for_files(
expanded_output,
latency_wait=wait,
force_stay_on_remote=force_stay_on_remote,
ignore_pipe=True,
)
except IOError as e:
raise MissingOutputException(
str(e) + "\nThis might be due to "
"filesystem latency. If that is the case, consider to increase the "
"wait time with --latency-wait."
+ "\nJob id: {jobid}".format(jobid=job.jobid),
rule=job.rule,
jobid=self.jobid(job),
)
# Ensure that outputs are of the correct type (those flagged with directory()
# are directories and not files and vice versa). We can't check for remote objects
for f in expanded_output:
if (f.is_directory and not f.remote_object and not os.path.isdir(f)) or (
not f.remote_object and os.path.isdir(f) and not f.is_directory
):
raise ImproperOutputException(job.rule, [f])
# It is possible, due to archive expansion or cluster clock skew, that
# the files appear older than the input. But we know they must be new,
# so touch them to update timestamps. This also serves to touch outputs
# when using the --touch flag.
# Note that if the input files somehow have a future date then this will
# not currently be spotted and the job will always be re-run.
if not no_touch:
for f in expanded_output:
# This won't create normal files if missing, but will create
# the flag file for directories.
if f.exists_local:
f.touch()
def unshadow_output(self, job, only_log=False):
"""Move files from shadow directory to real output paths."""
if not job.shadow_dir or not job.expanded_output:
return
files = job.log if only_log else chain(job.expanded_output, job.log)
for real_output in files:
shadow_output = job.shadowed_path(real_output).file
# Remake absolute symlinks as relative
if os.path.islink(shadow_output):
dest = os.readlink(shadow_output)
if os.path.isabs(dest):
rel_dest = os.path.relpath(dest, job.shadow_dir)
os.remove(shadow_output)
os.symlink(rel_dest, shadow_output)
if os.path.realpath(shadow_output) == os.path.realpath(real_output):
continue
logger.debug(
"Moving shadow output {} to destination {}".format(
shadow_output, real_output
)
)
shutil.move(shadow_output, real_output)
shutil.rmtree(job.shadow_dir)
def check_periodic_wildcards(self, job):
"""Raise an exception if a wildcard of the given job appears to be periodic,
indicating a cyclic dependency."""
for wildcard, value in job.wildcards_dict.items():
periodic_substring = self.periodic_wildcard_detector.is_periodic(value)
if periodic_substring is not None:
raise PeriodicWildcardError(
"The value {} in wildcard {} is periodically repeated ({}). "
"This would lead to an infinite recursion. "
"To avoid this, e.g. restrict the wildcards in this rule to certain values.".format(
periodic_substring, wildcard, value
),
rule=job.rule,
)
def handle_protected(self, job):
"""Write-protect output files that are marked with protected()."""
for f in job.expanded_output:
if f in job.protected_output:
logger.info("Write-protecting output file {}.".format(f))
f.protect()
def handle_touch(self, job):
"""Touches those output files that are marked for touching."""
for f in job.expanded_output:
if f in job.touch_output:
f = job.shadowed_path(f)
logger.info("Touching output file {}.".format(f))
f.touch_or_create()
assert os.path.exists(f)
def temp_input(self, job):
for job_, files in self.dependencies[job].items():
for f in filter(job_.temp_output.__contains__, files):
yield f
def temp_size(self, job):
"""Return the total size of temporary input files of the job.
If none, return 0.
"""
return sum(f.size for f in self.temp_input(job))
def handle_temp(self, job):
"""Remove temp files if they are no longer needed. Update temp_mtimes."""
if self.notemp:
return
is_temp = lambda f: is_flagged(f, "temp")
# handle temp input
needed = lambda job_, f: any(
f in files
for j, files in self.depending[job_].items()
if not self.finished(j) and self.needrun(j) and j != job
)
def unneeded_files():
# temp input
for job_, files in self.dependencies[job].items():
tempfiles = set(f for f in job_.expanded_output if is_temp(f))
yield from filterfalse(partial(needed, job_), tempfiles & files)
# temp output
if not job.dynamic_output and (
job not in self.targetjobs or job.rule.name == self.workflow.first_rule
):
tempfiles = (
f
for f in job.expanded_output
if is_temp(f) and f not in self.targetfiles
)
yield from filterfalse(partial(needed, job), tempfiles)
for f in unneeded_files():
logger.info("Removing temporary output file {}.".format(f))
f.remove(remove_non_empty_dir=True)
def handle_log(self, job, upload_remote=True):
for f in job.log:
if not f.exists_local:
# If log file was not created during job, create an empty one.
f.touch_or_create()
if upload_remote and f.is_remote and not f.should_stay_on_remote:
f.upload_to_remote()
if not f.exists_remote:
raise RemoteFileException(
"The file upload was attempted, but it does not "
"exist on remote. Check that your credentials have "
"read AND write permissions."
)
def handle_remote(self, job, upload=True):
"""Remove local files if they are no longer needed and upload."""
if upload:
# handle output files
files = job.expanded_output
if job.benchmark:
files = chain(job.expanded_output, (job.benchmark,))
for f in files:
if f.is_remote and not f.should_stay_on_remote:
f.upload_to_remote()
remote_mtime = f.mtime.remote()
# immediately force local mtime to match remote,
# since conversions from S3 headers are not 100% reliable
# without this, newness comparisons may fail down the line
f.touch(times=(remote_mtime, remote_mtime))
if not f.exists_remote:
raise RemoteFileException(
"The file upload was attempted, but it does not "
"exist on remote. Check that your credentials have "
"read AND write permissions."
)
if not self.keep_remote_local:
if not any(f.is_remote for f in job.input):
return
# handle input files
needed = lambda job_, f: any(
f in files
for j, files in self.depending[job_].items()
if not self.finished(j) and self.needrun(j) and j != job
)
def unneeded_files():
putative = (
lambda f: f.is_remote
and not f.protected
and not f.should_keep_local
)
generated_input = set()
for job_, files in self.dependencies[job].items():
generated_input |= files
for f in filter(putative, files):
if not needed(job_, f):
yield f
for f, f_ in zip(job.output, job.rule.output):
if putative(f) and not needed(job, f) and not f in self.targetfiles:
if f in job.dynamic_output:
for f_ in job.expand_dynamic(f_):
yield f_
else:
yield f
for f in filter(putative, job.input):
# TODO what about remote inputs that are used by multiple jobs?
if f not in generated_input:
yield f
for f in unneeded_files():
if f.exists_local:
logger.info("Removing local copy of remote file: {}".format(f))
f.remove()
def jobid(self, job):
"""Return job id of given job."""
if job.is_group():
return job.jobid
else:
return self._jobid[job]
def update(
self,
jobs,
file=None,
visited=None,
known_producers=None,
skip_until_dynamic=False,
progress=False,
create_inventory=False,
):
"""Update the DAG by adding given jobs and their dependencies."""
if visited is None:
visited = set()
if known_producers is None:
known_producers = dict()
producer = None
exceptions = list()
jobs = sorted(jobs, reverse=not self.ignore_ambiguity)
cycles = list()
for job in jobs:
logger.dag_debug(dict(status="candidate", job=job))
if file in job.input:
cycles.append(job)
continue
if job in visited:
cycles.append(job)
continue
try:
self.check_periodic_wildcards(job)
self.update_(
job,
visited=set(visited),
known_producers=known_producers,
skip_until_dynamic=skip_until_dynamic,
progress=progress,
create_inventory=create_inventory,
)
# TODO this might fail if a rule discarded here is needed
# elsewhere
if producer:
if job < producer or self.ignore_ambiguity:
break
elif producer is not None:
raise AmbiguousRuleException(file, job, producer)
producer = job
except (
MissingInputException,
CyclicGraphException,
PeriodicWildcardError,
WorkflowError,
) as ex:
exceptions.append(ex)
except RecursionError as e:
raise WorkflowError(
e,
"If building the DAG exceeds the recursion limit, "
"this is likely due to a cyclic dependency."
"E.g. you might have a sequence of rules that "
"can generate their own input. Try to make "
"the output files more specific. "
"A common pattern is to have different prefixes "
"in the output files of different rules."
+ "\nProblematic file pattern: {}".format(file)
if file
else "",
)
if producer is None:
if cycles:
job = cycles[0]
raise CyclicGraphException(job.rule, file, rule=job.rule)
if len(exceptions) > 1:
raise WorkflowError(*exceptions)
elif len(exceptions) == 1:
raise exceptions[0]
else:
logger.dag_debug(dict(status="selected", job=producer))
logger.dag_debug(
dict(
file=file,
msg="Producer found, hence exceptions are ignored.",
exception=WorkflowError(*exceptions),
)
)
n = len(self.dependencies)
if progress and n % 1000 == 0 and n and self._progress != n:
logger.info("Processed {} potential jobs.".format(n))
self._progress = n
return producer
def update_(
self,
job,
visited=None,
known_producers=None,
skip_until_dynamic=False,
progress=False,
create_inventory=False,
):
"""Update the DAG by adding the given job and its dependencies."""
if job in self.dependencies:
return
if visited is None:
visited = set()
if known_producers is None:
known_producers = dict()
visited.add(job)
dependencies = self.dependencies[job]
potential_dependencies = self.collect_potential_dependencies(
job, known_producers=known_producers
)
skip_until_dynamic = skip_until_dynamic and not job.dynamic_output
missing_input = set()
producer = dict()
exceptions = dict()
for res in potential_dependencies:
if create_inventory:
# If possible, obtain inventory information starting from
# given file and store it in the IOCache.
# This should provide faster access to existence and mtime information
# than querying file by file. If the file type does not support inventory
# information, this call is a no-op.
res.file.inventory()
if not res.jobs:
# no producing job found
if not res.file.exists:
# file not found, hence missing input
missing_input.add(res.file)
known_producers[res.file] = None
# file found, no problem
continue
if res.known:
producer[res.file] = res.jobs[0]
else:
try:
selected_job = self.update(
res.jobs,
file=res.file,
visited=visited,
known_producers=known_producers,
skip_until_dynamic=skip_until_dynamic
or res.file in job.dynamic_input,
progress=progress,
)
producer[res.file] = selected_job
except (
MissingInputException,
CyclicGraphException,
PeriodicWildcardError,
WorkflowError,
) as ex:
if not res.file.exists:
self.delete_job(job, recursive=False) # delete job from tree
raise ex
else:
logger.dag_debug(
dict(
file=res.file,
msg="No producers found, but file is present on disk.",
exception=ex,
)
)
known_producers[res.file] = None
for file, job_ in producer.items():
dependencies[job_].add(file)
self.depending[job_][job].add(file)
if self.is_batch_rule(job.rule) and self.batch.is_final:
# For the final batch, ensure that all input files from
# previous batches are present on disk.
if any((f not in producer and not f.exists) for f in job.input):
raise WorkflowError(
"Unable to execute batch {} because not all previous batches "
"have been completed before or files have been deleted.".format(
self.batch
)
)
if missing_input:
self.delete_job(job, recursive=False) # delete job from tree
raise MissingInputException(job.rule, missing_input)
if skip_until_dynamic:
self._dynamic.add(job)
def update_needrun(self, create_inventory=False):
"""Update the information whether a job needs to be executed."""
if create_inventory:
# Concurrently collect mtimes of all existing files.
self.workflow.iocache.mtime_inventory(self.jobs)
output_mintime = dict()
def update_output_mintime(job):
try:
return output_mintime[job]
except KeyError:
for job_ in chain([job], self.depending[job]):
try:
t = output_mintime[job_]
except KeyError:
t = job_.output_mintime
if t is not None:
output_mintime[job] = t
return
output_mintime[job] = None
def update_needrun(job):
reason = self.reason(job)
noinitreason = not reason
updated_subworkflow_input = self.updated_subworkflow_files.intersection(
job.input
)
if (
job not in self.omitforce
and job.rule in self.forcerules
or not self.forcefiles.isdisjoint(job.output)
):
reason.forced = True
elif updated_subworkflow_input:
reason.updated_input.update(updated_subworkflow_input)
elif job in self.targetjobs:
# TODO find a way to handle added/removed input files here?
if not job.output and not job.benchmark:
if job.input:
if job.rule.norun:
reason.updated_input_run.update(
f for f in job.input if not f.exists
)
else:
reason.nooutput = True
else:
reason.noio = True
else:
if job.rule in self.targetrules:
files = set(job.output)
if job.benchmark:
files.add(job.benchmark)
else:
files = set(chain(*self.depending[job].values()))
if self.targetfiles:
files.update(
f
for f in chain(job.output, job.log)
if f in self.targetfiles
)