snakemake-executor-plugin-aws-batch-flex 0.2.2__py3-none-any.whl → 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,6 +10,7 @@ import re
10
10
  import shlex
11
11
  import textwrap
12
12
  import zlib
13
+ from pathlib import Path
13
14
  from typing import Iterable, List, Optional
14
15
 
15
16
  MODES = ("auto", "always", "never", "host")
@@ -142,180 +143,53 @@ if ! python -c "import snakemake" >/dev/null 2>&1; then
142
143
  fi
143
144
  """
144
145
 
145
- # Python `script:` rules normally run with Snakemake's own interpreter. This launcher makes them
146
- # use the image's python (>= 3.10, which Snakemake's script header needs) when it has one, the
147
- # same way Snakemake treats conda envs. Anything else falls through to the original code.
148
- _LAUNCHER = r"""
149
- import os, runpy, shutil, subprocess, sys
150
- a = sys.argv[1:]
151
- if a[:2] != ["-m", "snakemake"]:
152
- os.execv(sys.executable, [sys.executable] + a)
153
- sys.argv = ["snakemake"] + a[2:]
154
- if "monitor" in globals() and "--deploy-sources" not in sys.argv:
155
- # the job tools came with this launcher, in the same file (job_tools_source)
156
- try:
157
- make_numpy_loadable()
158
- _why = parallel_s3_directories()
159
- if _why:
160
- print(f"[snakemake-batch] directory() outputs on S3 move one file at a time ({_why})", file=sys.stderr)
161
- if os.environ.get("SMK_FLEX_SAME_PATH") == "1":
162
- _why = plain_local_paths(sys.argv)
163
- if _why:
164
- print(f"[snakemake-batch] storage files' local copies stay under .snakemake/storage ({_why})",
165
- file=sys.stderr)
166
- monitor()
167
- _cc = os.environ.get("SMK_FLEX_CONDA_CACHE", "none")
168
- if _cc != "none":
169
- sys.argv = ["snakemake"] + install(sys.argv[1:], _cc)
170
- except Exception as e:
171
- print(f"[snakemake-batch] job tools off for this job (conda env cache, usage figures): {e!r}",
172
- file=sys.stderr)
173
- try:
174
- # Snakemake hands scripts their params in a form any environment can load: DataFrame, Series
175
- # and numpy arrays become lists. In pandas 3 a text column's .values is a pandas array
176
- # (StringArray), not a numpy one, so it went to the script as is, and a script environment
177
- # with pandas 2 can't load it. It goes as the numpy array pandas 2 gave.
178
- import inspect
179
- try:
180
- from snakemake.iocontainers import Snakemake as SmkData
181
- except ImportError: # earlier Snakemake 9 releases had it in snakemake.script
182
- from snakemake.script import Snakemake as SmkData
183
- orig_store = SmkData._safely_store_params
184
- if list(inspect.signature(orig_store).parameters) != ["self", "params"]:
185
- raise RuntimeError("this Snakemake's Snakemake._safely_store_params changed")
186
- def _safely_store_params(self, params):
187
- try:
188
- import numpy as np
189
- from pandas import StringDtype
190
- from pandas.api.extensions import ExtensionArray
191
- except ImportError:
192
- return orig_store(self, params)
193
- def text(v): # only text: other pandas arrays (Categorical...) were pandas objects in pandas 2 too
194
- return isinstance(v, ExtensionArray) and isinstance(v.dtype, StringDtype)
195
- if any(text(v) for v in params):
196
- params = params.__class__(toclone=params)
197
- for i, v in enumerate(params):
198
- if text(v):
199
- params[i] = np.asarray(v, dtype=object)
200
- return orig_store(self, params)
201
- SmkData._safely_store_params = _safely_store_params
202
- except Exception as e:
203
- print(f"[snakemake-batch] pandas arrays in params go to scripts unchanged ({e!r})", file=sys.stderr)
204
- if os.environ.get("SMK_FLEX_SCRIPT_PYTHON") == "host":
205
- runpy.run_module("snakemake", run_name="__main__", alter_sys=True)
206
- sys.exit()
207
- found = []
208
- def image_python():
209
- if not found:
210
- found.append(None)
211
- p = shutil.which("python") or shutil.which("python3")
212
- if p and os.path.realpath(p) != os.path.realpath(sys.executable):
213
- try:
214
- if subprocess.run([p, "-c", "import sys; sys.exit(sys.version_info < (3, 10))"]).returncode == 0:
215
- found[0] = p
216
- except OSError:
217
- pass
218
- return found[0]
219
- has = {}
220
- def image_lacks(params):
221
- # Snakemake hands a script its pandas, numpy and polars params as such (top-level values,
222
- # iocontainers._safely_store_params), so the script's python needs them just to start.
223
- # Locally such scripts usually run in Snakemake's own python, which has them.
224
- missing = []
225
- for v in params or []:
226
- m = type(v).__module__.split(".")[0]
227
- if m in ("pandas", "numpy", "polars") and m not in missing:
228
- if m not in has:
229
- has[m] = subprocess.run([image_python(), "-c", "import " + m], capture_output=True).returncode == 0
230
- if not has[m]:
231
- missing.append(m)
232
- return missing
233
- def own_packages():
234
- # Links to just this Snakemake's packages, put first on the script's path so that a
235
- # Snakemake installed in the image can't shadow them. Everything else: image first.
236
- import snakemake
237
- site = os.path.dirname(os.path.dirname(snakemake.__file__))
238
- d = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".smk-pkgs")
239
- if not os.path.isdir(d):
240
- # made whole under another name, then renamed: a group job runs scripts at once
241
- import tempfile
242
- tmp = tempfile.mkdtemp(dir=os.path.dirname(d))
243
- for n in os.listdir(site):
244
- if n.startswith("snakemake") and os.path.isdir(os.path.join(site, n)) and "." not in n:
245
- os.symlink(os.path.join(site, n), os.path.join(tmp, n))
246
- try:
247
- os.rename(tmp, d)
248
- except OSError: # another script's came first
249
- shutil.rmtree(tmp, ignore_errors=True)
250
- return d
251
- try:
252
- import inspect
253
- from snakemake import script as sm_script
254
- orig = sm_script.PythonScript.execute_script
255
- if list(inspect.signature(orig).parameters) != ["self", "fname", "edit"]:
256
- raise RuntimeError("this Snakemake's PythonScript.execute_script changed")
257
- def execute_script(self, fname, edit=False):
258
- if self.container_img is None and self.conda_env is None and self.env_modules is None and image_python():
259
- missing = image_lacks(self.params)
260
- if missing:
261
- print(f"[snakemake-batch] this script runs in Snakemake's python: its params are {', '.join(missing)} "
262
- "objects, which the image's python can't load", file=sys.stderr)
263
- return orig(self, fname, edit)
264
- return self._execute_cmd(
265
- "PYTHONPATH={pkgs:q}${{PYTHONPATH:+:$PYTHONPATH}} {py_exec:q} {fname:q}",
266
- pkgs=own_packages(), py_exec=image_python(), fname=fname, is_python_script=True)
267
- return orig(self, fname, edit)
268
- sm_script.PythonScript.execute_script = execute_script
269
- except Exception as e:
270
- print(f"[snakemake-batch] script: rules will use Snakemake's python ({e!r})", file=sys.stderr)
271
- runpy.run_module("snakemake", run_name="__main__", alter_sys=True)
272
- """
146
+ def _job_side(name: str) -> str:
147
+ """The source of a script that runs inside the job (launcher.py, loader.py)."""
148
+ return (Path(__file__).parent / name).read_text()
149
+
150
+
151
+ def compact_python(source: str) -> str:
152
+ """Python source without its docstring, its comment lines and blank lines, and with one
153
+ space per level of indentation instead of four: for code that goes into a job's command,
154
+ which ECS limits to 8192 characters. tests/test_units.py checks that the code is unchanged."""
155
+ import ast
156
+
157
+ lines = source.splitlines()
158
+ first = ast.parse(source).body[0]
159
+ if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant) and isinstance(first.value.value, str):
160
+ lines = lines[first.end_lineno:]
161
+ out = []
162
+ for line in lines:
163
+ code = line.lstrip(" ")
164
+ if code and not code.startswith("#"):
165
+ out.append(" " * ((len(line) - len(code)) // 4) + code)
166
+ return "\n".join(out) + "\n"
273
167
 
274
168
 
275
169
  def job_tools_source() -> str:
276
170
  """The file every job downloads and runs (launcher_snippet): condacache.py, jobmonitor.py and
277
171
  jobfixes.py, then the launcher. Too long to send with each job; uploaded once per run."""
278
- from pathlib import Path
279
-
280
- here = Path(__file__).parent
281
- tools = [(here / name).read_text() for name in ("condacache.py", "jobmonitor.py", "jobfixes.py")]
282
- # the launcher runs when the job's loader runs the file, not when the tools are only loaded
283
- launcher = 'if __name__ == "smkflex_launcher":\n' + textwrap.indent(_LAUNCHER, " ")
172
+ tools = [_job_side(name) for name in ("condacache.py", "jobmonitor.py", "jobfixes.py")]
173
+ # the launcher runs when the loader runs the file, not when the tools are only loaded
174
+ launcher = 'if __name__ == "smkflex_launcher":\n' + textwrap.indent(_job_side("launcher.py"), " ")
284
175
  return "\n\n".join(tools + [launcher])
285
176
 
286
177
 
287
- # Fetches the job tools (with the launcher) named in SMK_FLEX_JOB_CODE, checks them against the
288
- # sha256 in their name, and runs them; else plain Snakemake. In the job's command, so short.
289
- _LOADER = (
290
- "import hashlib,os,runpy,sys\n"
291
- "u=os.environ.get(\"SMK_FLEX_JOB_CODE\");a=sys.argv[1:];d=None\n"
292
- "if a[:2]!=[\"-m\",\"snakemake\"]:os.execv(sys.executable,[sys.executable]+a)\n"
293
- "if u and \"--deploy-sources\" not in a:\n"
294
- " try:\n"
295
- " if u.startswith(\"s3://\"):\n"
296
- " import boto3;b,_,k=u[5:].partition(\"/\");d=boto3.client(\"s3\").get_object(Bucket=b,Key=k)[\"Body\"].read()\n"
297
- " else:d=open(u,\"rb\").read()\n"
298
- " if not u.endswith(\"jobtools-%s.py\"%hashlib.sha256(d).hexdigest()):raise ValueError(u+\" does not match its checksum\")\n"
299
- " except Exception as e:\n"
300
- " d=None;print(\"[snakemake-batch] job tools off for this job (conda env cache, usage figures, image python for script:): %r\"%e,file=sys.stderr)\n"
301
- "if d:exec(compile(d,\"smkflex-jobtools.py\",\"exec\"),{\"__name__\":\"smkflex_launcher\",\"__file__\":os.path.join(os.getcwd(),\".smk-launch.py\")})\n"
302
- "else:sys.argv=[\"snakemake\"]+a[2:];runpy.run_module(\"snakemake\",run_name=\"__main__\",alter_sys=True)\n"
303
- )
304
-
305
-
306
178
  def launcher_snippet(job_code: bool) -> str:
307
- """Point the `python` function (if the prelude defined one) at the launcher: the short loader
308
- above when the job tools were uploaded (job_code), else the launcher itself, compressed (ECS
309
- allows only 8192 characters of overrides per job)."""
179
+ """Point the `python` function (if the prelude defined one) at the loader (loader.py) when
180
+ the job tools were uploaded (job_code), else at the launcher itself (image_python_snippet)."""
310
181
  if job_code:
311
- return 'if [ -n "${SMK_PY:-}" ]; then\n' f' python() {{ "$SMK_PY" -c {shlex.quote(_LOADER)} "$@"; }}\n' "fi\n"
182
+ loader = shlex.quote(compact_python(_job_side("loader.py")))
183
+ return 'if [ -n "${SMK_PY:-}" ]; then\n' f' python() {{ "$SMK_PY" -c {loader} "$@"; }}\n' "fi\n"
312
184
  return image_python_snippet()
313
185
 
314
186
 
315
187
  def image_python_snippet() -> str:
316
- """Point the `python` function at the launcher above (only if the prelude defined one).
317
- The launcher is sent compressed: ECS allows only 8192 characters of overrides per job."""
318
- packed = base64.b64encode(zlib.compress(_LAUNCHER.encode(), 9)).decode()
188
+ """Point the `python` function at the launcher (launcher.py; only if the prelude defined
189
+ one). It's sent compacted and compressed: ECS allows only 8192 characters of overrides per
190
+ job. The job writes it out to .smk-launch.py in its working folder and runs it from there."""
191
+ launcher = compact_python(_job_side("launcher.py"))
192
+ packed = base64.b64encode(zlib.compress(launcher.encode(), 9)).decode()
319
193
  unpack = "import base64,sys,zlib;open(sys.argv[1],'wb').write(zlib.decompress(base64.b64decode(sys.argv[2])))"
320
194
  return (
321
195
  'if [ -n "${SMK_PY:-}" ]; then\n'
@@ -30,6 +30,7 @@ _FETCH = (
30
30
  "t.extractall(d,**({'filter':'data'} if hasattr(tarfile,'data_filter') else {}))\n"
31
31
  )
32
32
 
33
+
33
34
  def added_files(paths, base="."):
34
35
  """{path in the bundle: local file} for --add: files, or every file in a folder, given
35
36
  relative to `base` (the current folder) and sent to the same place."""
@@ -51,6 +52,7 @@ def added_files(paths, base="."):
51
52
  raise Fail(f"--add {p}: no such file or folder here")
52
53
  return out
53
54
 
55
+
54
56
  def config_named_files(root, snakemake_args=()):
55
57
  """{path: local file} of the small files named in the config files the run reads: the YAML
56
58
  in config/ and --configfile's (sources.named_files; the Snakefile's own config isn't read
@@ -114,6 +116,7 @@ def make_bundle(root, profile_dir, max_mb, extra=None):
114
116
  t.add(headjob.__file__, arcname=".smkflex/head.py")
115
117
  return buf.getvalue()
116
118
 
119
+
117
120
  def head_command(profile, platform, bundle_url, state_url, snakemake_args, workdir=None):
118
121
  """The head job's command. With workdir (the project folder smkflex run was started in), it
119
122
  unpacks the workflow at that same path where it can, so that paths a Snakefile makes absolute
@@ -136,6 +139,7 @@ def head_command(profile, platform, bundle_url, state_url, snakemake_args, workd
136
139
  f'exec "$SMKFLEX_PY" .smkflex/head.py {shlex.quote(state_url)} {args}\n'
137
140
  )
138
141
 
142
+
139
143
  def _git(*args, cwd=None):
140
144
  try:
141
145
  return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True, check=True).stdout.strip()
@@ -144,6 +148,7 @@ def _git(*args, cwd=None):
144
148
  except subprocess.CalledProcessError as e:
145
149
  raise Fail(f"git {' '.join(args[:2])} failed: {(e.stderr or e.stdout).strip()}") from None
146
150
 
151
+
147
152
  def clone(url, rev, dest):
148
153
  """Shallow clone of `rev` (branch, tag; default: the default branch), or a full clone
149
154
  when it's a commit. Returns the commit."""
@@ -162,6 +167,7 @@ def clone(url, rev, dest):
162
167
  _git("submodule", "update", "--quiet", "--init", "--recursive", cwd=dest)
163
168
  return _git("rev-parse", "HEAD", cwd=dest)
164
169
 
170
+
165
171
  def local_commit(root):
166
172
  """The commit of a local git checkout, with -modified if it has uncommitted changes,
167
173
  including new files that aren't git-ignored (the bundle sends those too)."""
@@ -173,5 +179,6 @@ def local_commit(root):
173
179
  return None
174
180
  return sha[:12] + ("-modified" if dirty else "")
175
181
 
182
+
176
183
  def _tag(value):
177
184
  return re.sub(r"[^A-Za-z0-9 _.:/=+\-@]", "_", str(value))[:256]
@@ -1,5 +1,6 @@
1
1
  """smkflex check: the setup, checked from this machine, one line per check."""
2
2
 
3
+ import importlib.metadata as md
3
4
  import os
4
5
 
5
6
  import boto3
@@ -8,20 +9,32 @@ from botocore.exceptions import BotoCoreError, ClientError
8
9
 
9
10
  from . import headjob
10
11
  from .preflight import ami_snakemake_version, check_queue, check_role, queue_uses_spot, version_note
11
- from .profiles import Fail, _load_profile
12
+ from .profiles import Fail, load_profile
12
13
 
14
+ MARKS = {"ok": " ok ", "warn": " warn ", "fail": " FAIL "}
13
15
 
14
- def cmd_check(a):
15
- """Check the setup from this machine, one line per check, with what to do about failures."""
16
- results = []
17
16
 
18
- def report(level, what, fix=""):
19
- results.append(level)
20
- mark = {"ok": " ok ", "warn": " warn ", "fail": " FAIL "}[level]
21
- print(f"[{mark}] {what}" + (f"\n -> {fix}" if fix else ""))
17
+ class Report:
18
+ """Prints one line per check, with what to do about a problem, and counts them."""
19
+
20
+ def __init__(self):
21
+ self.levels = []
22
+
23
+ def __call__(self, level, what, fix=""):
24
+ self.levels.append(level)
25
+ print(f"[{MARKS[level]}] {what}" + (f"\n -> {fix}" if fix else ""))
26
+
27
+ def summary(self):
28
+ fails, warns = self.levels.count("fail"), self.levels.count("warn")
29
+ print(f"\n{fails} problem(s), {warns} warning(s)." if fails or warns else "\nAll good.")
30
+ return 1 if fails else 0
22
31
 
32
+
33
+ def cmd_check(a):
34
+ """Check the setup from this machine, one line per check, with what to do about failures."""
35
+ report = Report()
23
36
  try:
24
- profile_dir, profile = _load_profile(a.profile)
37
+ profile_dir, profile = load_profile(a.profile)
25
38
  except Fail as e:
26
39
  report("fail", f"profile: {e}", "run this in your workflow folder, or pass --profile DIR")
27
40
  return 1
@@ -30,56 +43,88 @@ def cmd_check(a):
30
43
  report("warn", f"the profile's executor is {profile.get('executor')!r}, not aws-batch-flex",
31
44
  "add `executor: aws-batch-flex`, or pass --executor aws-batch-flex to snakemake")
32
45
 
33
- import importlib.metadata as md
46
+ local = _check_installed(report, profile)
47
+ cfg = BotoConfig(region_name=profile.get("aws-batch-flex-region"), retries={"max_attempts": 3})
48
+ batch, region = _check_aws_login(report, cfg)
49
+ if batch is None:
50
+ return 1
51
+ queue, platform = _check_queue(report, profile, batch, region)
52
+ _check_roles(report, profile, cfg, platform)
53
+ _check_storage(report, profile)
54
+ if queue and platform == "ec2" and profile.get("aws-batch-flex-bootstrap") == "host" and local:
55
+ _check_ami(report, batch, cfg, queue, local)
56
+ return report.summary()
57
+
58
+
59
+ def _check_installed(report, profile):
60
+ """Snakemake and the storage plugin on this machine. Returns the Snakemake version, or None."""
34
61
  try:
35
62
  local = md.version("snakemake")
36
63
  report("ok", f"Snakemake {local} installed here")
37
64
  except md.PackageNotFoundError:
38
65
  local = None
39
66
  report("fail", "Snakemake isn't installed here", "pip install snakemake")
67
+ provider, prefix = _storage(profile)
68
+ if not provider:
69
+ report("fail", "no remote storage in the profile",
70
+ "set default-storage-provider: s3 and default-storage-prefix: s3://BUCKET/PREFIX")
71
+ return local
72
+ try:
73
+ md.version(f"snakemake-storage-plugin-{provider}")
74
+ report("ok", f"storage plugin {provider} installed here")
75
+ except md.PackageNotFoundError:
76
+ report("fail", f"snakemake-storage-plugin-{provider} isn't installed here",
77
+ f"pip install snakemake-storage-plugin-{provider}")
78
+ return local
79
+
80
+
81
+ def _storage(profile):
82
+ """(provider, prefix) of the profile's remote storage, or (None, None) if it has none."""
40
83
  provider = profile.get("default-storage-provider")
41
84
  prefix = str(profile.get("default-storage-prefix") or "").rstrip("/")
42
85
  if not provider or provider == "local" or not prefix:
43
- report("fail", "no remote storage in the profile",
44
- "set default-storage-provider: s3 and default-storage-prefix: s3://BUCKET/PREFIX")
45
- else:
46
- try:
47
- md.version(f"snakemake-storage-plugin-{provider}")
48
- report("ok", f"storage plugin {provider} installed here")
49
- except md.PackageNotFoundError:
50
- report("fail", f"snakemake-storage-plugin-{provider} isn't installed here",
51
- f"pip install snakemake-storage-plugin-{provider}")
52
-
53
- region = profile.get("aws-batch-flex-region")
54
- cfg = BotoConfig(region_name=region, retries={"max_attempts": 3})
86
+ return None, None
87
+ return provider, prefix
88
+
89
+
90
+ def _check_aws_login(report, cfg):
91
+ """The AWS login and region. Returns (Batch client, region), or (None, None) when nothing else
92
+ can be checked."""
55
93
  try:
56
94
  who = boto3.client("sts", config=cfg).get_caller_identity()["Arn"]
57
95
  report("ok", f"AWS login: {who}")
58
96
  except (ClientError, BotoCoreError) as e:
59
97
  report("fail", f"AWS login: {e}", "run `aws configure` (or `aws sso login`), or set AWS_PROFILE")
60
- return 1
98
+ return None, None
61
99
  batch = boto3.client("batch", config=cfg)
62
- region = batch.meta.region_name if hasattr(batch, "meta") else region
100
+ region = batch.meta.region_name if hasattr(batch, "meta") else cfg.region_name
63
101
  if not region:
64
102
  report("fail", "no AWS region", "set aws-batch-flex-region in the profile")
65
- return 1
103
+ return None, None
104
+ return batch, region
105
+
66
106
 
107
+ def _check_queue(report, profile, batch, region):
108
+ """The profile's queue. Returns (queue, platform), with queue None if it isn't usable."""
67
109
  queue = profile.get("aws-batch-flex-queue")
68
- platform, queue_ok = None, False
69
110
  if not queue:
70
111
  report("fail", "no queue in the profile", "set aws-batch-flex-queue (Terraform prints it as queue_name)")
71
- else:
72
- errors, warnings, detected = check_queue(batch, queue, profile.get("aws-batch-flex-platform"))
73
- platform = profile.get("aws-batch-flex-platform") or detected or "ec2"
74
- for e in errors:
75
- report("fail", f"queue: {e}")
76
- for w in warnings:
77
- report("warn", f"queue: {w}")
78
- queue_ok = not errors
79
- if not errors:
80
- spot = " (Spot)" if queue_uses_spot(batch, queue) else ""
81
- report("ok", f"queue {queue} in {region}: enabled, {platform.upper()}{spot}")
112
+ return None, None
113
+ errors, warnings, detected = check_queue(batch, queue, profile.get("aws-batch-flex-platform"))
114
+ platform = profile.get("aws-batch-flex-platform") or detected or "ec2"
115
+ for e in errors:
116
+ report("fail", f"queue: {e}")
117
+ for w in warnings:
118
+ report("warn", f"queue: {w}")
119
+ if errors:
120
+ return None, platform
121
+ spot = " (Spot)" if queue_uses_spot(batch, queue) else ""
122
+ report("ok", f"queue {queue} in {region}: enabled, {platform.upper()}{spot}")
123
+ return queue, platform
124
+
82
125
 
126
+ def _check_roles(report, profile, cfg, platform):
127
+ """The IAM roles the profile names, and the ones its platform needs."""
83
128
  iam = boto3.client("iam", config=cfg)
84
129
  for key, label in (("aws-batch-flex-job-role-arn", "job role"), ("aws-batch-flex-head-role-arn", "head role"),
85
130
  ("aws-batch-flex-execution-role-arn", "execution role")):
@@ -90,7 +135,7 @@ def cmd_check(a):
90
135
  report("fail", errors[0], f"check {key} in the profile (Terraform prints the right one)")
91
136
  else:
92
137
  report("ok", f"{label} {arn.rsplit('/', 1)[-1]}")
93
- if not profile.get("aws-batch-flex-job-role-arn") and platform == "fargate":
138
+ if platform == "fargate" and not profile.get("aws-batch-flex-job-role-arn"):
94
139
  report("fail", "Fargate jobs need a job role (there's no instance role to reach storage with)",
95
140
  "set aws-batch-flex-job-role-arn")
96
141
  if platform == "fargate" and not profile.get("aws-batch-flex-execution-role-arn"):
@@ -99,31 +144,30 @@ def cmd_check(a):
99
144
  report("warn", "no aws-batch-flex-head-role-arn: fine for snakemake, but smkflex run needs it",
100
145
  "add the head_role_arn that Terraform prints")
101
146
 
102
- if prefix and provider and provider != "local":
103
- probe = f"{prefix}/.smkflex/check-{os.getpid()}"
104
- try:
105
- headjob.put(probe, b"smkflex check")
106
- ok = headjob.get(probe) == b"smkflex check"
107
- if probe.startswith("s3://"):
108
- s3, bucket, key = headjob._s3(probe)
109
- s3.delete_object(Bucket=bucket, Key=key)
110
- else:
111
- os.remove(probe)
112
- report("ok" if ok else "fail", f"storage {prefix}: write, read, delete")
113
- except (ClientError, BotoCoreError, OSError) as e:
114
- report("fail", f"storage {prefix}: {e}",
115
- "check the bucket name and that your AWS login may read and write under the prefix")
116
-
117
- if queue_ok and platform == "ec2" and profile.get("aws-batch-flex-bootstrap") == "host" and local:
118
- ami = ami_snakemake_version(batch, boto3.client("ec2", config=cfg), queue)
119
- level, note = version_note(ami, local)
120
- if not ami:
121
- report("warn", "couldn't find the AMI's Snakemake version (an older AMI, or no ec2:Describe* permission)")
122
- elif level == "warning":
123
- report("warn", note, f"pip install snakemake=={ami}, or bake a new AMI")
124
- else:
125
- report("ok", f"the AMI has Snakemake {ami}" + (f" (here: {local}; known to work together)" if level else ""))
126
-
127
- fails, warns = results.count("fail"), results.count("warn")
128
- print(f"\n{fails} problem(s), {warns} warning(s)." if fails or warns else "\nAll good.")
129
- return 1 if fails else 0
147
+
148
+ def _check_storage(report, profile):
149
+ """Write, read and delete a small file under the storage prefix."""
150
+ _provider, prefix = _storage(profile)
151
+ if not prefix:
152
+ return
153
+ probe = f"{prefix}/.smkflex/check-{os.getpid()}"
154
+ try:
155
+ headjob.put(probe, b"smkflex check")
156
+ ok = headjob.get(probe) == b"smkflex check"
157
+ headjob.delete(probe)
158
+ report("ok" if ok else "fail", f"storage {prefix}: write, read, delete")
159
+ except (ClientError, BotoCoreError, OSError) as e:
160
+ report("fail", f"storage {prefix}: {e}",
161
+ "check the bucket name and that your AWS login may read and write under the prefix")
162
+
163
+
164
+ def _check_ami(report, batch, cfg, queue, local):
165
+ """Whether the AMI's Snakemake works with the one installed here."""
166
+ ami = ami_snakemake_version(batch, boto3.client("ec2", config=cfg), queue)
167
+ level, note = version_note(ami, local)
168
+ if not ami:
169
+ report("warn", "couldn't find the AMI's Snakemake version (an older AMI, or no ec2:Describe* permission)")
170
+ elif level == "warning":
171
+ report("warn", note, f"pip install snakemake=={ami}, or bake a new AMI")
172
+ else:
173
+ report("ok", f"the AMI has Snakemake {ami}" + (f" (here: {local}; known to work together)" if level else ""))