/
workflow.py
2164 lines (1845 loc) · 74.5 KB
/
workflow.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 dataclasses import dataclass, field
import hashlib
import re
import os
import subprocess
import sys
from collections import OrderedDict, namedtuple
from collections.abc import Mapping
from itertools import filterfalse, chain
from functools import partial
import copy
from pathlib import Path
import tarfile
import tempfile
from typing import Dict, List, Optional, Set
from snakemake.common.workdir_handler import WorkdirHandler
from snakemake.settings import (
ConfigSettings,
DAGSettings,
DeploymentMethod,
DeploymentSettings,
ExecutionSettings,
GroupSettings,
OutputSettings,
RemoteExecutionSettings,
RerunTrigger,
ResourceSettings,
SchedulingSettings,
StorageSettings,
WorkflowSettings,
SharedFSUsage,
)
from snakemake_interface_executor_plugins.workflow import WorkflowExecutorInterface
from snakemake_interface_executor_plugins.cli import (
SpawnedJobArgsFactoryExecutorInterface,
)
from snakemake_interface_common.utils import lazy_property
from snakemake_interface_executor_plugins.settings import ExecutorSettingsBase
from snakemake_interface_executor_plugins.registry.plugin import (
Plugin as ExecutorPlugin,
)
from snakemake_interface_executor_plugins.settings import ExecMode
from snakemake_interface_common.plugin_registry.plugin import TaggedSettings
from snakemake.logging import logger, format_resources
from snakemake.rules import Rule, Ruleorder, RuleProxy
from snakemake.exceptions import (
CreateCondaEnvironmentException,
RuleException,
CreateRuleException,
UnknownRuleException,
NoRulesException,
WorkflowError,
update_lineno,
)
from snakemake.dag import DAG, ChangeType
from snakemake.scheduler import JobScheduler
from snakemake.parser import parse
import snakemake.io
from snakemake.io import (
protected,
temp,
temporary,
ancient,
directory,
expand,
glob_wildcards,
flag,
touch,
unpack,
local,
pipe,
service,
repeat,
report,
multiext,
ensure,
from_queue,
IOFile,
sourcecache_entry,
)
from snakemake.persistence import Persistence
from snakemake.utils import update_config
from snakemake.script import script
from snakemake.notebook import notebook
from snakemake.wrapper import wrapper
from snakemake.cwl import cwl
from snakemake.template_rendering import render_template
from snakemake_interface_common.utils import not_iterable
import snakemake.wrapper
from snakemake.common import (
ON_WINDOWS,
async_run,
get_appdirs,
is_local_file,
Rules,
Scatter,
Gather,
smart_join,
NOTHING_TO_BE_DONE_MSG,
)
from snakemake.utils import simplify_path
from snakemake.checkpoints import Checkpoints
from snakemake.resources import ParsedResource, ResourceScopes
from snakemake.caching.local import OutputFileCache as LocalOutputFileCache
from snakemake.caching.storage import OutputFileCache as StorageOutputFileCache
from snakemake.modules import ModuleInfo, WorkflowModifier, get_name_modifier_func
from snakemake.ruleinfo import InOutput, RuleInfo
from snakemake.sourcecache import (
LocalSourceFile,
SourceCache,
SourceFile,
infer_source_file,
)
from snakemake.deployment.conda import Conda
from snakemake import api, sourcecache
import snakemake.ioutils
SourceArchiveInfo = namedtuple("SourceArchiveInfo", ("query", "checksum"))
@dataclass
class Workflow(WorkflowExecutorInterface):
config_settings: ConfigSettings
resource_settings: ResourceSettings
workflow_settings: WorkflowSettings
storage_settings: Optional[StorageSettings] = None
dag_settings: Optional[DAGSettings] = None
execution_settings: Optional[ExecutionSettings] = None
deployment_settings: Optional[DeploymentSettings] = None
scheduling_settings: Optional[SchedulingSettings] = None
output_settings: Optional[OutputSettings] = None
remote_execution_settings: Optional[RemoteExecutionSettings] = None
group_settings: Optional[GroupSettings] = None
executor_settings: ExecutorSettingsBase = None
storage_provider_settings: Optional[Mapping[str, TaggedSettings]] = None
check_envvars: bool = True
cache_rules: Mapping[str, str] = field(default_factory=dict)
overwrite_workdir: Optional[str] = None
_workdir_handler: Optional[WorkdirHandler] = field(init=False, default=None)
injected_conda_envs: List = field(default_factory=list)
def __post_init__(self):
"""
Create the controller.
"""
from snakemake.storage import StorageRegistry
self.global_resources = dict(self.resource_settings.resources)
self.global_resources["_cores"] = self.resource_settings.cores
self.global_resources["_nodes"] = self.resource_settings.nodes
self._rules = OrderedDict()
self.default_target = None
self._workdir_init = os.path.abspath(os.curdir)
self._ruleorder = Ruleorder()
self._localrules = set()
self._linemaps = dict()
self.rule_count = 0
self.included = []
self.included_stack: list[SourceFile] = []
self._persistence: Optional[Persistence] = None
self._dag: Optional[DAG] = None
self._onsuccess = lambda log: None
self._onerror = lambda log: None
self._onstart = lambda log: None
self._rulecount = 0
self._parent_groupids = dict()
self.global_container_img = None
self.global_is_containerized = False
self.configfiles = list(self.config_settings.configfiles)
self.report_text = None
# environment variables to pass to jobs
# These are defined via the "envvars:" syntax in the Snakefile itself
self._envvars = set()
self._scatter = dict(self.resource_settings.overwrite_scatter)
self._resource_scopes = ResourceScopes.defaults()
self._resource_scopes.update(self.resource_settings.overwrite_resource_scopes)
self.modules = dict()
self._snakemake_tmp_dir = tempfile.TemporaryDirectory(prefix="snakemake")
self._sourcecache = SourceCache(self.source_cache_path)
self._scheduler = None
self._spawned_job_general_args = None
self._executor_plugin = None
self._storage_registry = StorageRegistry(self)
self._source_archive = None
_globals = globals()
from snakemake.shell import shell
_globals["shell"] = shell
_globals["workflow"] = self
_globals["checkpoints"] = Checkpoints()
_globals["scatter"] = Scatter()
_globals["gather"] = Gather()
_globals["github"] = sourcecache.GithubFile
_globals["gitlab"] = sourcecache.GitlabFile
_globals["gitfile"] = sourcecache.LocalGitFile
_globals["storage"] = self._storage_registry
snakemake.ioutils.register_in_globals(_globals)
_globals["from_queue"] = from_queue
self.vanilla_globals = dict(_globals)
self.modifier_stack = [WorkflowModifier(self, globals=_globals)]
self._output_file_cache = None
self.cache_rules = dict()
self.globals["config"] = copy.deepcopy(self.config_settings.overwrite_config)
@property
def parent_groupids(self):
return self._parent_groupids
def tear_down(self):
for conda_env in self.injected_conda_envs:
conda_env.deactivate()
if self._workdir_handler is not None:
self._workdir_handler.change_back()
self._snakemake_tmp_dir.cleanup()
@property
def is_main_process(self):
return self.exec_mode == ExecMode.DEFAULT
@property
def snakemake_tmp_dir(self) -> Path:
return Path(self._snakemake_tmp_dir.name)
@property
def source_cache_path(self) -> Path:
if SharedFSUsage.SOURCE_CACHE not in self.storage_settings.shared_fs_usage:
return self.snakemake_tmp_dir / "source-cache"
else:
return Path(
os.path.join(get_appdirs().user_cache_dir, "snakemake/source-cache")
)
@property
def storage_registry(self):
return self._storage_registry
@property
def source_archive(self):
assert self._source_archive is not None, (
"bug: source archive info accessed but source archive has not been "
"uploaded to default storage provider before"
)
return self._source_archive
def upload_sources(self):
with tempfile.NamedTemporaryFile(suffix="snakemake-sources.tar.xz") as f:
self.write_source_archive(Path(f.name))
f.flush()
with open(f.name, "rb") as f:
checksum = hashlib.file_digest(f, "sha256").hexdigest()
prefix = self.storage_settings.default_storage_prefix
if prefix:
prefix = f"{prefix}/"
query = f"{prefix}snakemake-workflow-sources.{checksum}.tar.xz"
self._source_archive = SourceArchiveInfo(query, checksum)
obj = self.storage_registry.default_storage_provider.object(query)
obj.set_local_path(Path(f.name))
logger.info("Uploading source archive to storage provider...")
async_run(obj.managed_store())
def write_source_archive(self, path: Path):
def get_files():
for f in self.dag.get_sources():
if f.startswith(".."):
logger.warning(
"Ignoring source file {}. Only files relative "
"to the working directory are allowed.".format(f)
)
continue
# The kubernetes API can't create secret files larger than 1MB.
source_file_size = os.path.getsize(f)
max_file_size = 10000000
if source_file_size > max_file_size:
logger.warning(
"Skipping the source file for upload {f}. Its size "
"{source_file_size} exceeds "
"the maximum file size (10MB). Consider to provide the file as "
"input file instead.".format(
f=f, source_file_size=source_file_size
)
)
continue
yield f
assert path.suffixes == [".tar", ".xz"]
with tarfile.open(path, "w:xz") as archive:
for f in get_files():
archive.add(f)
@property
def enable_cache(self):
return (
self.workflow_settings is not None
and self.workflow_settings.cache is not None
)
def check_cache_rules(self):
for rule in self.rules:
cache_mode = self.cache_rules.get(rule.name)
if cache_mode:
if len(rule.output) > 1:
if not all(out.is_multiext for out in rule.output):
raise WorkflowError(
"Rule is marked for between workflow caching but has multiple output files. "
"This is only allowed if multiext() is used to declare them (see docs on between "
"workflow caching).",
rule=rule,
)
if not self.enable_cache:
logger.warning(
f"Workflow defines that rule {rule.name} is eligible for caching between workflows "
"(use the --cache argument to enable this)."
)
if rule.benchmark:
raise WorkflowError(
"Rules with a benchmark directive may not be marked as eligible "
"for between-workflow caching at the same time. The reason is that "
"when the result is taken from cache, there is no way to fill the benchmark file with "
"any reasonable values. Either remove the benchmark directive or disable "
"between-workflow caching for this rule.",
rule=rule,
)
@property
def attempt(self):
if self.execution_settings is None:
# if not executing, we can safely set this to 1
return 1
return self.execution_settings.attempt
@property
def executor_plugin(self):
return self._executor_plugin
@property
def dryrun(self):
if self.executor_plugin is None:
return False
else:
return self.executor_plugin.common_settings.dryrun_exec
@property
def touch(self):
import snakemake.executors.touch
return issubclass(
self.executor_plugin.executor, snakemake.executors.touch.Executor
)
@property
def use_threads(self):
return (
self.execution_settings.use_threads
or (os.name not in ["posix", "nt"])
or not self.local_exec
)
@property
def local_exec(self):
if self.executor_plugin is not None:
return self.executor_plugin.common_settings.local_exec
else:
return True
@property
def non_local_exec(self):
return not self.local_exec
@property
def remote_exec(self):
return self.exec_mode == ExecMode.REMOTE
@property
def exec_mode(self):
return self.workflow_settings.exec_mode
@lazy_property
def spawned_job_args_factory(self) -> SpawnedJobArgsFactoryExecutorInterface:
from snakemake.spawn_jobs import SpawnedJobArgsFactory
return SpawnedJobArgsFactory(self)
@property
def basedir(self):
return os.path.dirname(self.main_snakefile)
@property
def scheduler(self):
return self._scheduler
@scheduler.setter
def scheduler(self, scheduler):
self._scheduler = scheduler
@property
def envvars(self):
return self._envvars
@property
def sourcecache(self):
return self._sourcecache
@property
def workdir_init(self):
return self._workdir_init
@property
def linemaps(self):
return self._linemaps
@property
def persistence(self):
return self._persistence
@property
def dag(self):
return self._dag
@property
def main_snakefile(self) -> str:
return self.included[0].get_path_or_uri()
@property
def output_file_cache(self):
return self._output_file_cache
@property
def resource_scopes(self):
return self._resource_scopes
@property
def overwrite_configfiles(self):
return self.config_settings.configfiles
@property
def rerun_triggers(self) -> Set[RerunTrigger]:
return self.dag_settings.rerun_triggers
@property
def conda_base_path(self):
if self.deployment_settings.conda_base_path:
return self.deployment_settings.conda_base_path
if DeploymentMethod.CONDA in self.deployment_settings.deployment_method:
try:
return Conda().prefix_path
except CreateCondaEnvironmentException:
# Return no preset conda base path now and report error later in jobs.
return None
else:
return None
@property
def modifier(self):
return self.modifier_stack[-1]
@property
def wildcard_constraints(self):
return self.modifier.wildcard_constraints
@property
def globals(self):
return self.modifier.globals
def lint(self, json=False):
from snakemake.linting.rules import RuleLinter
from snakemake.linting.snakefiles import SnakefileLinter
json_snakefile_lints, snakefile_linted = SnakefileLinter(
self, self.included
).lint(json=json)
json_rule_lints, rules_linted = RuleLinter(self, self.rules).lint(json=json)
linted = snakefile_linted or rules_linted
if json:
import json
print(
json.dumps(
{"snakefiles": json_snakefile_lints, "rules": json_rule_lints},
indent=2,
)
)
else:
if not linted:
logger.info("Congratulations, your workflow is in a good condition!")
return linted
def get_cache_mode(self, rule: Rule):
if self.workflow_settings.cache is None:
return None
else:
return self.cache_rules.get(rule.name)
@property
def rules(self):
return self._rules.values()
@property
def cores(self):
if self._cores is None:
raise WorkflowError(
"Workflow requires a total number of cores to be defined (e.g. because a "
"rule defines its number of threads as a fraction of a total number of cores). "
"Please set it with --cores N with N being the desired number of cores. "
"Consider to use this in combination with --max-threads to avoid "
"jobs with too many threads for your setup. Also make sure to perform "
"a dryrun first."
)
return self._cores
@property
def _cores(self):
return self.global_resources["_cores"]
@property
def nodes(self):
return self.global_resources["_nodes"]
@property
def concrete_files(self):
return (
file
for rule in self.rules
for file in chain(rule.input, rule.output)
if not callable(file) and not file.contains_wildcard()
)
def check(self):
for clause in self._ruleorder:
for rulename in clause:
if not self.is_rule(rulename):
raise UnknownRuleException(
rulename, prefix="Error in ruleorder definition."
)
self.check_cache_rules()
self.check_localrules()
def add_rule(
self,
name=None,
lineno=None,
snakefile=None,
checkpoint=False,
allow_overwrite=False,
):
"""
Add a rule.
"""
is_overwrite = self.is_rule(name)
if not allow_overwrite and is_overwrite:
raise CreateRuleException(
f"The name {name} is already used by another rule",
lineno=lineno,
snakefile=snakefile,
)
rule = Rule(name, self, lineno=lineno, snakefile=snakefile)
self._rules[rule.name] = rule
self.modifier.rules.add(rule)
if not is_overwrite:
self.rule_count += 1
if not self.default_target:
self.default_target = rule.name
return name
def is_rule(self, name):
"""
Return True if name is the name of a rule.
Arguments
name -- a name
"""
return name in self._rules
def get_rule(self, name):
"""
Get rule by name.
Arguments
name -- the name of the rule
"""
if not self._rules:
raise NoRulesException()
if name not in self._rules:
raise UnknownRuleException(name)
return self._rules[name]
def list_rules(self, only_targets=False):
rules = self.rules
if only_targets:
rules = filterfalse(Rule.has_wildcards, rules)
for rule in sorted(rules, key=lambda r: r.name):
docstring = f" ({rule.docstring})" if rule.docstring else ""
print(rule.name + docstring)
def list_resources(self):
for resource in set(
resource for rule in self.rules for resource in rule.resources
):
if resource not in "_cores _nodes".split():
logger.info(resource)
def is_local(self, rule):
return self.local_exec or (
rule.group is None
and (rule.name in self._localrules or rule.norun or rule.is_template_engine)
)
def check_localrules(self):
undefined = self._localrules - set(rule.name for rule in self.rules)
if undefined:
logger.warning(
"localrules directive specifies rules that are not "
"present in the Snakefile:\n{}\n".format(
"\n".join(map("\t{}".format, undefined))
)
)
def inputfile(self, path):
"""Mark file as being an input file of the workflow.
This also means that eventual --default-remote-provider/prefix settings
will be applied to this file. The file is returned as _IOFile object,
such that it can e.g. be transparently opened with _IOFile.open().
"""
if isinstance(path, Path):
path = str(path)
if self.storage_settings.default_storage_provider is not None:
path = self.modifier.modify_path(path)
return IOFile(path)
def _prepare_dag(
self,
forceall: bool,
ignore_incomplete: bool,
lock_warn_only: bool,
nolock: bool = False,
shadow_prefix: Optional[str] = None,
) -> DAG:
if self.workflow_settings.cache is not None:
self.cache_rules.update(
{rulename: "all" for rulename in self.workflow_settings.cache}
)
if self.storage_settings.default_storage_provider is not None:
self._output_file_cache = StorageOutputFileCache(
self.storage_registry.default_storage_provider
)
else:
self._output_file_cache = LocalOutputFileCache()
def rules(items):
return map(self._rules.__getitem__, filter(self.is_rule, items))
if self.dag_settings.target_files_omit_workdir_adjustment:
def files(items):
return map(
self.modifier.path_modifier.apply_default_storage,
filterfalse(self.is_rule, items),
)
else:
def files(items):
relpath = (
lambda f: f
if os.path.isabs(f) or f.startswith("root://")
else os.path.relpath(f)
)
return map(
self.modifier.path_modifier.apply_default_storage,
map(relpath, filterfalse(self.is_rule, items)),
)
self.iocache = snakemake.io.IOCache(self.dag_settings.max_inventory_wait_time)
if not self.dag_settings.targets and not self.dag_settings.target_jobs:
targets = (
[self.default_target] if self.default_target is not None else list()
)
else:
targets = self.dag_settings.targets
prioritytargets = set()
if self.scheduling_settings is not None:
prioritytargets = self.scheduling_settings.prioritytargets
priorityrules = set(rules(prioritytargets))
priorityfiles = set(files(prioritytargets))
forcerules = set(rules(self.dag_settings.forcerun))
forcefiles = set(files(self.dag_settings.forcerun))
untilrules = set(rules(self.dag_settings.until))
untilfiles = set(files(self.dag_settings.until))
omitrules = set(rules(self.dag_settings.omit_from))
omitfiles = set(files(self.dag_settings.omit_from))
targetrules = set(
chain(
rules(targets),
filterfalse(Rule.has_wildcards, priorityrules),
filterfalse(Rule.has_wildcards, forcerules),
filterfalse(Rule.has_wildcards, untilrules),
)
)
targetfiles = set(chain(files(targets), priorityfiles, forcefiles, untilfiles))
if ON_WINDOWS:
targetfiles = set(tf.replace(os.sep, os.altsep) for tf in targetfiles)
if self.dag_settings.forcetargets:
forcefiles.update(targetfiles)
forcerules.update(targetrules)
rules = self.rules
if self.dag_settings.allowed_rules:
rules = [
rule for rule in rules if rule.name in self.dag_settings.allowed_rules
]
self._dag = DAG(
self,
rules,
targetfiles=targetfiles,
targetrules=targetrules,
# when cleaning up conda or containers, we should enforce all possible jobs
# since their envs shall not be deleted
forceall=forceall,
forcefiles=forcefiles,
forcerules=forcerules,
priorityfiles=priorityfiles,
priorityrules=priorityrules,
untilfiles=untilfiles,
untilrules=untilrules,
omitfiles=omitfiles,
omitrules=omitrules,
ignore_incomplete=ignore_incomplete,
)
persistence_path = (
self.snakemake_tmp_dir / "persistence"
if SharedFSUsage.PERSISTENCE not in self.storage_settings.shared_fs_usage
else None
)
self._persistence = Persistence(
nolock=nolock,
dag=self._dag,
conda_prefix=self.deployment_settings.conda_prefix,
singularity_prefix=self.deployment_settings.apptainer_prefix,
shadow_prefix=shadow_prefix,
warn_only=lock_warn_only,
path=persistence_path,
)
def generate_unit_tests(self, path: Path):
"""Generate unit tests for the workflow.
Arguments
path -- Path to the directory where the unit tests shall be generated.
"""
from snakemake import unit_tests
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=False,
lock_warn_only=False,
)
self._build_dag()
deploy = []
if DeploymentMethod.CONDA in self.deployment_settings.deployment_method:
deploy.append("conda")
if DeploymentMethod.APPTAINER in self.deployment_settings.deployment_method:
deploy.append("singularity")
unit_tests.generate(
self.dag, path, deploy, configfiles=self.overwrite_configfiles
)
def cleanup_metadata(self, paths: List[Path]):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=False,
)
failed = []
for path in paths:
success = self.persistence.cleanup_metadata(path)
if not success:
failed.append(path)
if failed:
raise WorkflowError(
"Failed to clean up metadata for the following files because the metadata was not present.\n"
"If this is expected, there is nothing to do.\nOtherwise, the reason might be file system latency "
"or still running jobs.\nConsider running metadata cleanup again.\nFiles:\n"
+ "\n".join(failed)
)
def unlock(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=False,
)
self._build_dag()
try:
self.persistence.cleanup_locks()
logger.info("Unlocked working directory.")
except IOError as e:
raise WorkflowError(
f"Error: Unlocking the directory {os.getcwd()} failed. Maybe "
"you don't have the permissions?",
e,
)
def cleanup_shadow(self):
self._prepare_dag(forceall=False, ignore_incomplete=False, lock_warn_only=False)
self._build_dag()
with self.persistence.lock():
self.persistence.cleanup_shadow()
def delete_output(self, only_temp: bool = False, dryrun: bool = False):
self._prepare_dag(forceall=False, ignore_incomplete=False, lock_warn_only=True)
self._build_dag()
async_run(self.dag.clean(only_temp=only_temp, dryrun=dryrun))
def list_untracked(self):
self._prepare_dag(forceall=False, ignore_incomplete=False, lock_warn_only=True)
self._build_dag()
self.dag.list_untracked()
def list_changes(self, change_type: ChangeType):
self._prepare_dag(forceall=False, ignore_incomplete=False, lock_warn_only=True)
self._build_dag()
items = async_run(self.dag.get_outputs_with_changes(change_type))
if items:
print(*items, sep="\n")
def archive(self, path: Path):
"""Archive the workflow.
Arguments
path -- Path to the archive file.
"""
self._prepare_dag(forceall=False, ignore_incomplete=False, lock_warn_only=True)
self._build_dag()
self.dag.archive(path)
def summary(self, detailed: bool = False):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=True,
)
self._build_dag()
print("\n".join(async_run(self.dag.summary(detailed=detailed))))
def conda_cleanup_envs(self):
self._prepare_dag(forceall=True, ignore_incomplete=True, lock_warn_only=False)
self._build_dag()
self.persistence.conda_cleanup_envs()
def printdag(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=True,
)
self._build_dag()
print(self.dag)
def printrulegraph(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=True,
)
self._build_dag()
print(self.dag.rule_dot())
def printfilegraph(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=True,
)
self._build_dag()
print(self.dag.filegraph_dot())
def printd3dag(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=True,
)
self._build_dag()
self.dag.d3dag()
def containerize(self):
from snakemake.deployment.containerize import containerize
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=False,
lock_warn_only=False,
)
self._build_dag()
with self.persistence.lock():
containerize(self, self.dag)
def export_cwl(self, path: Path):
"""Export the workflow as CWL document.
Arguments
path -- the path to the CWL document to be created.
"""
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=False,
)
self._build_dag()
from snakemake.cwl import dag_to_cwl
import json
with open(path, "w") as cwl:
json.dump(dag_to_cwl(self.dag), cwl, indent=4)
def create_report(self, path: Path, stylesheet: Optional[Path] = None):
from snakemake.report import auto_report
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=False,
lock_warn_only=False,
)
self._build_dag()
async_run(auto_report(self.dag, path, stylesheet=stylesheet))
def conda_list_envs(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=False,
lock_warn_only=False,
)
self._build_dag()
self.dag.create_conda_envs(
dryrun=True,
quiet=True,
)
print("environment", "container", "location", sep="\t")
for env in set(job.conda_env for job in self.dag.jobs):
if env and not env.is_named:
print(
env.file.simplify_path(),
env.container_img_url or "",
simplify_path(env.address),
sep="\t",
)
return True
def conda_create_envs(self):
self._prepare_dag(
forceall=self.dag_settings.forceall,
ignore_incomplete=True,
lock_warn_only=False,
)
self._build_dag()
if DeploymentMethod.APPTAINER in self.deployment_settings.deployment_method:
self.dag.pull_container_imgs()
self.dag.create_conda_envs()
def conda_cleanup_envs(self):