eptatools 0.4.0__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.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: eptatools
3
+ Version: 0.4.0
4
+ Summary: Local Python client for remote Einstein Probe WXT and FXT pipelines
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: paramiko>=3.4
8
+ Provides-Extra: test
9
+ Requires-Dist: pytest>=7; extra == "test"
10
+
11
+ # eptools
12
+
13
+ `eptools` is a local Python client for submitting Einstein Probe WXT and FXT
14
+ processing jobs over SSH. The scientific pipeline code remains unchanged: a
15
+ small, Python-3.6-compatible runner creates an isolated workspace on the
16
+ server and invokes the existing entrypoints.
17
+
18
+ The server-side installation is shared, not stored in any user's home:
19
+
20
+ - WXT: `/mnt/eptools/software`
21
+ - FXT: `/NFS/ep-pipeline/software/eptools`
22
+
23
+ Jobs remain private under a username-specific directory in the shared job
24
+ area. The default client reuses the deployed `CURRENT` pipeline revision and
25
+ does not update shared code automatically.
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ python -m pip install eptatools
31
+ ```
32
+
33
+ The Python import name is `eptools`. To install from a local checkout, run
34
+ `python -m pip install -e .` from the repository root.
35
+
36
+ See [docs/USAGE.md](docs/USAGE.md) for SSH configuration, all supported WXT
37
+ and FXT input cases, interactive review states, recovery, and result download.
38
+
39
+ ## Example
40
+
41
+ ```python
42
+ from getpass import getpass
43
+ from eptools import EPPipelineClient
44
+
45
+ client = EPPipelineClient(input("SSH username: "), getpass("SSH password: "))
46
+ params = client.parameters(
47
+ "wxt",
48
+ name="EP260809a",
49
+ obs_id=["06800001692"], cmos_id=["32"],
50
+ ra=328.573, dec=17.607, T0_GCN="2026-08-09T00:38:21.800",
51
+ nH_Galactic=None, z=None,
52
+ )
53
+ job = client.submit(params)
54
+ print(job.job_id)
55
+ state = client.status(job)
56
+ print(state)
57
+ if state["state"] == "completed":
58
+ print(client.download(job))
59
+ ```
60
+
61
+ A maintainer deploys a new runner and pipeline snapshot explicitly:
62
+
63
+ ```python
64
+ maintainer = EPPipelineClient(
65
+ local_pipeline_roots={
66
+ "wxt": input("Local WXT checkout: "),
67
+ "fxt": input("Local FXT checkout: "),
68
+ },
69
+ )
70
+ print(maintainer.deploy(("wxt", "fxt")))
71
+ ```
72
+
73
+ By default WXT is routed to the SSH alias `epserver`, while FXT is routed to
74
+ `server`. The client uploads a versioned snapshot of the selected pipeline,
75
+ submits one source per job, and downloads only files listed in the server-side
76
+ result manifest. Credentials are kept out of request files and result
77
+ manifests.
78
+
79
+ For FXT, build `ep-fxt-pipeline:v2.0` on `server` from
80
+ `docker/fxt-pipeline.Dockerfile`. The image extends `fxtsoft:v2.0`, initializes
81
+ HEASoft on startup and uses the matching FXT CALDB v2.0. MultiNest is built from
82
+ a pinned upstream commit. See the [deployment instructions](docs/USAGE.md#10-部署失败和安全检查).
@@ -0,0 +1,11 @@
1
+ eptools/__init__.py,sha256=DmYg8NXKxMtNd1QpYbIhltcHPIOSanxihPuoe5chbtQ,323
2
+ eptools/_server_runner.py,sha256=0-MvIuJbNBrUH6iWKqoNjCWdXl7Ktlp31hdLP2azPT0,20040
3
+ eptools/_wxt_init.sh,sha256=RPHrOKcEo36RZo66zioNReAF59bMQNHOOLGuidtRjz8,426
4
+ eptools/client.py,sha256=HXz5HeLUgFiXz6Boo9DKcHIFkYWzb477gYon_BaiJJc,22016
5
+ eptools/job.py,sha256=xe5to6RdYKtXlDtR8SZjyvUN1cfo2aLdHNkGG04Te8Q,3830
6
+ eptools/models.py,sha256=JFG8ZXOJ94FQTtU-IAf9RHjeYse6kSMcq12uVYSW1QI,6116
7
+ eptools/transport.py,sha256=4L2KI5PyQrXjSRXmyHXUqGpup0Qhzgenq_7v2xWf39A,6343
8
+ eptatools-0.4.0.dist-info/METADATA,sha256=j2I2HVtPlhmx9gmgwFf_F7FY-h1c1hL37EaT39IMxt0,2703
9
+ eptatools-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ eptatools-0.4.0.dist-info/top_level.txt,sha256=M7WwTsaV2kNsSmW0NI4Fj4OstPgWIBmhMNaj36YSihg,8
11
+ eptatools-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ eptools
eptools/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Public API for eptools."""
2
+
3
+ from .client import EPPipelineClient
4
+ from .job import PipelineJob
5
+ from .models import FXTSource, HostProfile, WXTObservation, WXTSource
6
+
7
+ __all__ = [
8
+ "EPPipelineClient",
9
+ "PipelineJob",
10
+ "FXTSource",
11
+ "HostProfile",
12
+ "WXTObservation",
13
+ "WXTSource",
14
+ ]
15
+
16
+ __version__ = "0.4.0"
@@ -0,0 +1,501 @@
1
+ #!/usr/bin/env python3
2
+ """Python-3.6-compatible remote runner deployed as a standalone file."""
3
+
4
+ from __future__ import print_function
5
+
6
+ import argparse
7
+ import csv
8
+ import datetime
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import sys
15
+ import time
16
+
17
+
18
+ STATES = {
19
+ "queued", "staging", "awaiting_captcha", "downloading", "running",
20
+ "needs_review", "completed", "failed", "cancelled",
21
+ }
22
+
23
+
24
+ def utc_now_iso():
25
+ # datetime.UTC is a 3.11+ alias of timezone.utc; this runner must stay
26
+ # 3.6-compatible, and now(timezone.utc) is the documented replacement
27
+ # for the utcnow() deprecation (3.12+). Works on Python 3.2 through 3.14+.
28
+ return datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")
29
+
30
+
31
+ def read_json(path):
32
+ with open(path, "r") as handle:
33
+ return json.load(handle)
34
+
35
+
36
+ def write_json(path, value, mode=None):
37
+ parent = os.path.dirname(path)
38
+ if parent and not os.path.isdir(parent):
39
+ os.makedirs(parent)
40
+ temporary = path + ".tmp.%s" % os.getpid()
41
+ with open(temporary, "w") as handle:
42
+ json.dump(value, handle, indent=2, sort_keys=True)
43
+ handle.write("\n")
44
+ if mode is not None:
45
+ os.chmod(temporary, mode)
46
+ os.rename(temporary, path)
47
+
48
+
49
+ def safe_component(value, field):
50
+ # request.json fields must never contribute "..", separators or absolute
51
+ # paths to filesystem writes; treat them as untrusted on a shared server.
52
+ text = str(value)
53
+ if not text or text in (".", "..") or "/" in text or "\\" in text or "\x00" in text:
54
+ raise ValueError("Unsafe path component in %s: %r" % (field, text))
55
+ return text
56
+
57
+
58
+ def within(base, *parts):
59
+ target = os.path.join(base, *parts)
60
+ real_base = os.path.realpath(base)
61
+ real_target = os.path.realpath(target)
62
+ if real_target != real_base and not real_target.startswith(real_base + os.sep):
63
+ raise ValueError("Refusing to touch path outside %s: %s" % (base, target))
64
+ return target
65
+
66
+
67
+ def update_status(job_dir, state, stage=None, message=None, **extra):
68
+ if state not in STATES:
69
+ raise ValueError("Unknown state: %s" % state)
70
+ path = os.path.join(job_dir, "status.json")
71
+ value = read_json(path) if os.path.isfile(path) else {}
72
+ value.update({
73
+ "job_id": read_json(os.path.join(job_dir, "request.json"))["job_id"],
74
+ "state": state,
75
+ "stage": stage,
76
+ "updated_at": utc_now_iso(),
77
+ })
78
+ if message is not None:
79
+ value["message"] = message
80
+ value.update(extra)
81
+ write_json(path, value, 0o600)
82
+
83
+
84
+ def run_logged(command, cwd, log_path, env=None):
85
+ parent = os.path.dirname(log_path)
86
+ if not os.path.isdir(parent):
87
+ os.makedirs(parent)
88
+ with open(log_path, "a") as log:
89
+ log.write("\n[%s] command: %s\n" % (utc_now_iso(), " ".join(command)))
90
+ log.flush()
91
+ result = subprocess.call(command, cwd=cwd, stdout=log, stderr=subprocess.STDOUT, env=env)
92
+ if result != 0:
93
+ raise RuntimeError("Command failed with exit code %s; see %s" % (result, log_path))
94
+
95
+
96
+ def copy_pipeline(source, destination):
97
+ if os.path.isdir(destination):
98
+ return
99
+ shutil.copytree(source, destination, ignore=shutil.ignore_patterns(".git", "results", "data", "__pycache__", "*.pyc"))
100
+
101
+
102
+ def run_wxt(job_dir, request, resume):
103
+ source = request["source"]
104
+ name = safe_component(source.get("name"), "source.name")
105
+ work = os.path.join(job_dir, "work")
106
+ pipeline = os.path.join(work, "pipeline")
107
+ artifacts = os.path.join(job_dir, "artifacts")
108
+ copy_pipeline(request["deployment"]["pipeline_root"], pipeline)
109
+ if not os.path.isdir(artifacts):
110
+ os.makedirs(artifacts)
111
+
112
+ catalog = os.path.join(work, "source.csv")
113
+ observations = ordered_wxt_observations(source)
114
+ with open(catalog, "w") as handle:
115
+ writer = csv.DictWriter(handle, fieldnames=[
116
+ "name", "obs_id", "cmos_id", "ra", "dec", "pos_error", "T0_GCN",
117
+ "GRB", "GBM_cover", "nH_Galactic", "auto_obs", "z",
118
+ ])
119
+ writer.writeheader()
120
+ writer.writerow({
121
+ "name": name,
122
+ "obs_id": repr([item["obs_id"] for item in observations]),
123
+ "cmos_id": repr([item["cmos_id"] for item in observations]),
124
+ "ra": source["ra"], "dec": source["dec"],
125
+ "pos_error": source.get("position_error"), "T0_GCN": source["t0"],
126
+ "GRB": None if source.get("is_grb") is None else int(bool(source["is_grb"])),
127
+ "GBM_cover": None if source.get("gbm_cover") is None else int(bool(source["gbm_cover"])),
128
+ "nH_Galactic": source.get("nh_galactic"),
129
+ "auto_obs": int(bool(source.get("auto_obs"))), "z": source.get("redshift"),
130
+ })
131
+
132
+ with open(os.path.join(pipeline, "config.json"), "r") as handle:
133
+ config = json.load(handle)
134
+ # EFXT WXT analysis appends relative paths directly to results_dir.
135
+ config["paths"]["results_dir"] = os.path.join(artifacts, "results", "")
136
+ config["paths"]["data_csv"] = catalog
137
+ config["execution"]["num_procs"] = 1
138
+ config["execution"]["max_procs_rerun"] = 1
139
+ review = bool(request.get("options", {}).get("review_regions")) and not resume
140
+ config["region"]["to_check_images"] = review
141
+ config_path = os.path.join(work, "wxt.config.json")
142
+ write_json(config_path, config, 0o600)
143
+
144
+ if resume:
145
+ review_file = find_review_file(job_dir)
146
+ if review_file:
147
+ destination = within(artifacts, "results", name + "_back_user.reg")
148
+ ensure_parent(destination)
149
+ shutil.copy2(review_file, destination)
150
+
151
+ update_status(job_dir, "running", "wxt_pipeline")
152
+ clobber = " --clobber" if request.get("options", {}).get("clobber") else ""
153
+ init_script = request.get("deployment", {}).get("wxt_init_script")
154
+ if not init_script or not os.path.isfile(init_script):
155
+ raise RuntimeError("Shared WXT initialization script is unavailable: %s" % init_script)
156
+ python_site = os.path.join(os.path.dirname(os.path.dirname(init_script)), "python")
157
+ script = (
158
+ "source {init_script} >/dev/null && cd {pipeline} && "
159
+ "export PYTHONPATH={python_site}${{PYTHONPATH:+:$PYTHONPATH}} && "
160
+ "python3 run_pipeline.py -n {name} -c {config}{clobber} && "
161
+ "python3 run_analysis.py -n {name} -c {config}"
162
+ ).format(
163
+ init_script=shell_quote(init_script), python_site=shell_quote(python_site),
164
+ pipeline=shell_quote(pipeline), name=shell_quote(name),
165
+ config=shell_quote(config_path), clobber=clobber,
166
+ )
167
+ run_logged(["bash", "-lc", script], pipeline, os.path.join(job_dir, "logs", "wxt.log"))
168
+ if review:
169
+ update_status(job_dir, "needs_review", "wxt_regions", "Upload the selected DS9 background region and resume.")
170
+ return False
171
+ return True
172
+
173
+
174
+ def ordered_wxt_observations(source):
175
+ observations = list(source["observations"])
176
+ if not source.get("auto_obs"):
177
+ return observations
178
+ pre = [item for item in observations if item.get("role") in ("pre_pointed", "pre_slew")]
179
+ post = [item for item in observations if item.get("role") in ("post_pointed", "post_slew")]
180
+ by_cmos = dict((item["cmos_id"], item) for item in post)
181
+ if not pre or set(by_cmos) != {"14", "37"} or len(post) != 2:
182
+ raise ValueError(
183
+ "Legacy WXT auto_obs requires pre-pointed entries plus "
184
+ "post-pointed CMOS14 and CMOS37"
185
+ )
186
+ if len(set(item["obs_id"] for item in pre)) != 1:
187
+ raise ValueError("All pre-pointed entries must share one obs_id")
188
+ if len(set(item["obs_id"] for item in post)) != 1:
189
+ raise ValueError("Both post-pointed entries must share one obs_id")
190
+ return pre + [by_cmos["14"], by_cmos["37"]]
191
+
192
+
193
+ def docker_command(job_dir, image, command):
194
+ uid = str(os.getuid())
195
+ gid = str(os.getgid())
196
+ caldb_version = "v1.30" if image.endswith(":v1.30") else "v2.0"
197
+ shell_mode = "-lc" if caldb_version == "v1.30" else "-c"
198
+ container_home = "/job/work/home"
199
+ container_workdir = container_home + "/eptatools"
200
+ pipeline_mount = os.path.join(job_dir, "work", "pipeline") + ":" + container_workdir
201
+ return [
202
+ "docker", "run", "--rm", "--user", uid + ":" + gid,
203
+ "-e", "HOME=" + container_home, "-e", "MPLCONFIGDIR=/job/work/matplotlib",
204
+ "-e", "FXT_CONFIG=/job/work/fxt.config.json",
205
+ "-v", job_dir + ":/job", "-v", "/NFS/fxtdata:/root/fxtdata",
206
+ "-v", pipeline_mount,
207
+ "--mount", "type=bind,src=/NFS/CALDB/FXT_CALDB_%s,dst=/caldb,readonly" % caldb_version,
208
+ "-w", container_workdir, image, "bash", shell_mode, command,
209
+ ]
210
+
211
+
212
+ def run_fxt(job_dir, request, resume):
213
+ source = request["source"]
214
+ name = safe_component(source.get("name"), "source.name")
215
+ options = request.get("options", {})
216
+ image = options.get("fxt_image", "ep-fxt-pipeline:v2.0")
217
+ work = os.path.join(job_dir, "work")
218
+ pipeline = os.path.join(work, "pipeline")
219
+ artifacts = os.path.join(job_dir, "artifacts")
220
+ copy_pipeline(request["deployment"]["pipeline_root"], pipeline)
221
+ for path in (artifacts, os.path.join(work, "home"), os.path.join(work, "matplotlib")):
222
+ if not os.path.isdir(path):
223
+ os.makedirs(path)
224
+
225
+ sources_csv = os.path.join(work, "sources_info.csv")
226
+ with open(sources_csv, "w") as handle:
227
+ writer = csv.DictWriter(handle, fieldnames=["name", "best_ra", "best_dec", "T0", "nH_Galactic", "z", "auto_obs"])
228
+ writer.writeheader()
229
+ writer.writerow({
230
+ "name": name, "best_ra": source["ra"], "best_dec": source["dec"],
231
+ "T0": source["t0"], "nH_Galactic": source.get("nh_galactic"),
232
+ "z": source.get("redshift"), "auto_obs": int(bool(source.get("auto_obs"))),
233
+ })
234
+
235
+ base_config = read_json(os.path.join(pipeline, "config.json"))
236
+ base_config["common"]["SOURCES_CSV"] = "/job/work/sources_info.csv"
237
+ base_config["common"]["DATA_ROOT"] = "/job/artifacts/data"
238
+ secrets_path = os.path.join(job_dir, "private", "secrets.json")
239
+ if not resume:
240
+ secrets = read_json(secrets_path)
241
+ base_config["download_level1"]["EP_USERNAME"] = secrets["ep_username"]
242
+ base_config["download_level1"]["EP_PASSWORD"] = secrets["ep_password"]
243
+ config_path = os.path.join(work, "fxt.config.json")
244
+ write_json(config_path, base_config, 0o600)
245
+
246
+ if resume:
247
+ review_file = find_review_file(job_dir)
248
+ if review_file:
249
+ shutil.copy2(review_file, os.path.join(pipeline, "obs_with_bright_source.csv"))
250
+ stages = [
251
+ "get_regions_bright.py", "run_round2_bright.py", "get_ctrt_lc.py",
252
+ "get_pha.py", "fit_all.py", "get_flux_lc.py",
253
+ ]
254
+ else:
255
+ update_status(job_dir, "downloading", "fxt_download")
256
+ wrapper = os.path.join(work, "fxt_download_wrapper.py")
257
+ write_download_wrapper(wrapper)
258
+ run_logged(
259
+ docker_command(job_dir, image, "python /job/work/fxt_download_wrapper.py -n %s" % shell_quote(name)),
260
+ pipeline, os.path.join(job_dir, "logs", "fxt-download.log"),
261
+ )
262
+ redact_and_remove_secrets(config_path, secrets_path)
263
+ stages = [
264
+ "run_round1.py", "get_regions.py", "run_round2.py", "check_pileup.py",
265
+ "get_regions_bright.py", "run_round2_bright.py", "get_ctrt_lc.py",
266
+ "get_pha.py", "fit_all.py", "get_flux_lc.py",
267
+ ]
268
+
269
+ for script in stages:
270
+ label = os.path.splitext(script)[0]
271
+ update_status(job_dir, "running", label)
272
+ command = "python %s -n %s" % (shell_quote(script), shell_quote(name))
273
+ run_logged(
274
+ docker_command(job_dir, image, command), pipeline,
275
+ os.path.join(job_dir, "logs", "fxt-%s.log" % label),
276
+ )
277
+ if script == "check_pileup.py" and should_pause_for_pileup(pipeline, options):
278
+ copy_review_artifacts(pipeline, artifacts)
279
+ update_status(job_dir, "needs_review", "fxt_pileup", "Review obs_with_bright_source.csv and resume.")
280
+ return False
281
+ return True
282
+
283
+
284
+ def write_download_wrapper(path):
285
+ content = r'''from __future__ import print_function
286
+ import builtins
287
+ import hashlib
288
+ import json
289
+ import os
290
+ import runpy
291
+ import sys
292
+ import time
293
+
294
+ JOB = "/job"
295
+ PIPELINE = os.getcwd()
296
+
297
+ def write_status(state, stage, message=None):
298
+ status_path = os.path.join(JOB, "status.json")
299
+ with open(status_path) as handle:
300
+ value = json.load(handle)
301
+ value.update({"state": state, "stage": stage, "updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
302
+ if message:
303
+ value["message"] = message
304
+ temporary = status_path + ".tmp"
305
+ with open(temporary, "w") as handle:
306
+ json.dump(value, handle, indent=2, sort_keys=True)
307
+ os.replace(temporary, status_path)
308
+
309
+ def remote_input(prompt=""):
310
+ debug = os.path.join(PIPELINE, "login_debug")
311
+ captcha_dir = os.path.join(JOB, "artifacts", "captcha")
312
+ os.makedirs(captcha_dir, exist_ok=True)
313
+ if os.path.isdir(debug):
314
+ for name in os.listdir(debug):
315
+ if name.lower().endswith((".png", ".html")):
316
+ source = os.path.join(debug, name)
317
+ target = os.path.join(captcha_dir, name)
318
+ if os.path.isfile(source):
319
+ import shutil
320
+ shutil.copy2(source, target)
321
+ files = []
322
+ for current, _dirs, names in os.walk(os.path.join(JOB, "artifacts")):
323
+ for name in names:
324
+ path = os.path.join(current, name)
325
+ digest = hashlib.sha256()
326
+ with open(path, "rb") as handle:
327
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
328
+ digest.update(chunk)
329
+ files.append({
330
+ "path": os.path.relpath(path, JOB).replace(os.sep, "/"),
331
+ "size": os.path.getsize(path),
332
+ "sha256": digest.hexdigest(),
333
+ })
334
+ manifest_path = os.path.join(JOB, "manifest.json")
335
+ with open(manifest_path + ".tmp", "w") as handle:
336
+ json.dump({"schema_version": 1, "partial": True, "files": files}, handle, indent=2, sort_keys=True)
337
+ os.replace(manifest_path + ".tmp", manifest_path)
338
+ write_status("awaiting_captcha", "fxt_login", "Download the captcha image and call provide_captcha(code).")
339
+ code_path = os.path.join(JOB, "control", "captcha.txt")
340
+ while not os.path.isfile(code_path):
341
+ time.sleep(1)
342
+ with open(code_path) as handle:
343
+ code = handle.read().strip()
344
+ os.remove(code_path)
345
+ write_status("downloading", "fxt_download")
346
+ return code
347
+
348
+ builtins.input = remote_input
349
+ sys.path.insert(0, PIPELINE)
350
+ runpy.run_path(os.path.join(PIPELINE, "download_level1.py"), run_name="__main__")
351
+ '''
352
+ with open(path, "w") as handle:
353
+ handle.write(content)
354
+ os.chmod(path, 0o700)
355
+
356
+
357
+ def redact_and_remove_secrets(config_path, secrets_path):
358
+ config = read_json(config_path)
359
+ config["download_level1"]["EP_USERNAME"] = "REDACTED"
360
+ config["download_level1"]["EP_PASSWORD"] = "REDACTED"
361
+ write_json(config_path, config, 0o600)
362
+ if os.path.isfile(secrets_path):
363
+ os.remove(secrets_path)
364
+
365
+
366
+ def should_pause_for_pileup(pipeline, options):
367
+ policy = options.get("review_pileup", "if_bright")
368
+ if policy == "never":
369
+ return False
370
+ if policy == "always":
371
+ return True
372
+ path = os.path.join(pipeline, "obs_with_bright_source.csv")
373
+ if not os.path.isfile(path):
374
+ return False
375
+ with open(path, "r") as handle:
376
+ return sum(1 for _line in handle) > 1
377
+
378
+
379
+ def copy_review_artifacts(pipeline, artifacts):
380
+ review = os.path.join(artifacts, "review")
381
+ if not os.path.isdir(review):
382
+ os.makedirs(review)
383
+ csv_path = os.path.join(pipeline, "obs_with_bright_source.csv")
384
+ if os.path.isfile(csv_path):
385
+ shutil.copy2(csv_path, review)
386
+ source = os.path.join(artifacts, "data", "pileup_check")
387
+ if os.path.isdir(source):
388
+ target = os.path.join(review, "pileup_check")
389
+ if os.path.isdir(target):
390
+ shutil.rmtree(target)
391
+ shutil.copytree(source, target)
392
+
393
+
394
+ def find_review_file(job_dir):
395
+ control = os.path.join(job_dir, "control")
396
+ if not os.path.isdir(control):
397
+ return None
398
+ for name in sorted(os.listdir(control)):
399
+ if name.startswith("review_file"):
400
+ return os.path.join(control, name)
401
+ return None
402
+
403
+
404
+ def create_manifest(job_dir, request):
405
+ files = []
406
+ include_raw = bool(request.get("options", {}).get("include_raw"))
407
+ for top in ("artifacts", "logs"):
408
+ root = os.path.join(job_dir, top)
409
+ if not os.path.isdir(root):
410
+ continue
411
+ for current, dirs, names in os.walk(root):
412
+ relative_current = os.path.relpath(current, job_dir)
413
+ if not include_raw and relative_current.startswith(os.path.join("artifacts", "data", "l1")):
414
+ dirs[:] = []
415
+ continue
416
+ for name in names:
417
+ path = os.path.join(current, name)
418
+ relative = os.path.relpath(path, job_dir).replace(os.sep, "/")
419
+ files.append({"path": relative, "size": os.path.getsize(path), "sha256": sha256(path)})
420
+ provenance = os.path.join(job_dir, "artifacts", "provenance")
421
+ if not os.path.isdir(provenance):
422
+ os.makedirs(provenance)
423
+ sanitized = dict(request)
424
+ write_json(os.path.join(provenance, "request.json"), sanitized, 0o600)
425
+ path = os.path.join(provenance, "request.json")
426
+ files.append({"path": os.path.relpath(path, job_dir).replace(os.sep, "/"), "size": os.path.getsize(path), "sha256": sha256(path)})
427
+ manifest = {
428
+ "schema_version": 1, "job_id": request["job_id"], "pipeline": request["pipeline"],
429
+ "created_at": utc_now_iso(), "files": sorted(files, key=lambda item: item["path"]),
430
+ }
431
+ write_json(os.path.join(job_dir, "manifest.json"), manifest, 0o600)
432
+
433
+
434
+ def sha256(path):
435
+ digest = hashlib.sha256()
436
+ with open(path, "rb") as handle:
437
+ while True:
438
+ chunk = handle.read(1024 * 1024)
439
+ if not chunk:
440
+ break
441
+ digest.update(chunk)
442
+ return digest.hexdigest()
443
+
444
+
445
+ def ensure_parent(path):
446
+ parent = os.path.dirname(path)
447
+ if parent and not os.path.isdir(parent):
448
+ os.makedirs(parent)
449
+
450
+
451
+ def shell_quote(value):
452
+ try:
453
+ from shlex import quote
454
+ return quote(str(value))
455
+ except ImportError:
456
+ import pipes
457
+ return pipes.quote(str(value))
458
+
459
+
460
+ def main():
461
+ parser = argparse.ArgumentParser()
462
+ parser.add_argument("mode", choices=["run", "resume"])
463
+ parser.add_argument("--job-dir", required=True)
464
+ args = parser.parse_args()
465
+ job_dir = os.path.realpath(args.job_dir)
466
+ request = read_json(os.path.join(job_dir, "request.json"))
467
+ if request.get("schema_version") != 1:
468
+ raise ValueError("Unsupported request schema")
469
+ update_status(job_dir, "staging", "prepare")
470
+ try:
471
+ if request["pipeline"] == "wxt":
472
+ finished = run_wxt(job_dir, request, args.mode == "resume")
473
+ elif request["pipeline"] == "fxt":
474
+ finished = run_fxt(job_dir, request, args.mode == "resume")
475
+ else:
476
+ raise ValueError("Unsupported pipeline")
477
+ if finished:
478
+ create_manifest(job_dir, request)
479
+ update_status(job_dir, "completed", "complete")
480
+ else:
481
+ create_manifest(job_dir, request)
482
+ except Exception as exc:
483
+ private = os.path.join(job_dir, "private", "secrets.json")
484
+ config = os.path.join(job_dir, "work", "fxt.config.json")
485
+ if os.path.isfile(config):
486
+ try:
487
+ redact_and_remove_secrets(config, private)
488
+ except Exception:
489
+ pass
490
+ elif os.path.isfile(private):
491
+ os.remove(private)
492
+ try:
493
+ create_manifest(job_dir, request)
494
+ except Exception:
495
+ pass
496
+ update_status(job_dir, "failed", "runner", str(exc), error_type=type(exc).__name__)
497
+ raise
498
+
499
+
500
+ if __name__ == "__main__":
501
+ main()
eptools/_wxt_init.sh ADDED
@@ -0,0 +1,9 @@
1
+ #!/bin/bash
2
+
3
+ # Shared WXTDAS environment for epserver. This is intentionally independent
4
+ # of any user's shell aliases or home-directory startup files.
5
+ export HEADAS=/mnt/soft/epwxtdas/x86_64-pc-linux-gnu-libc2.17
6
+ . "${HEADAS}/headas-init.sh"
7
+ export CALDB=/mnt/wxt_fm_caldb/caldb
8
+ export CALDBCONFIG=/mnt/wxt_fm_caldb/caldb/software/tools/caldb.config
9
+ export CALDBALIAS=/mnt/wxt_fm_caldb/caldb/software/tools/alias_config.fits