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.
- eptatools-0.4.0.dist-info/METADATA +82 -0
- eptatools-0.4.0.dist-info/RECORD +11 -0
- eptatools-0.4.0.dist-info/WHEEL +5 -0
- eptatools-0.4.0.dist-info/top_level.txt +1 -0
- eptools/__init__.py +16 -0
- eptools/_server_runner.py +501 -0
- eptools/_wxt_init.sh +9 -0
- eptools/client.py +487 -0
- eptools/job.py +95 -0
- eptools/models.py +167 -0
- eptools/transport.py +179 -0
eptools/client.py
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""High-level eptools client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import posixpath
|
|
10
|
+
import shlex
|
|
11
|
+
import subprocess
|
|
12
|
+
import tarfile
|
|
13
|
+
import tempfile
|
|
14
|
+
import uuid
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, Mapping, Optional, Sequence, Union
|
|
17
|
+
|
|
18
|
+
from .job import PipelineJob
|
|
19
|
+
from .models import (
|
|
20
|
+
FXTSource, HostProfile, WXTObservation, WXTSource, _is_blank, normalize_local_root,
|
|
21
|
+
)
|
|
22
|
+
from .transport import SSHTransport
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
DEFAULT_REMOTE_INSTALL_ROOTS = {
|
|
26
|
+
"wxt": "/mnt/eptools/software",
|
|
27
|
+
"fxt": "/NFS/ep-pipeline/software/eptools",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
DEFAULT_REMOTE_JOB_ROOTS = {
|
|
31
|
+
"wxt": "/mnt/eptools/jobs",
|
|
32
|
+
"fxt": "/NFS/ep-pipeline/jobs",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
_EFXT_COLUMNS = {
|
|
36
|
+
"wxt": {"T0_GCN": "t0", "pos_error": "position_error", "GRB": "is_grb", "GBM_cover": "gbm_cover"},
|
|
37
|
+
"fxt": {"T0": "t0", "best_ra": "ra", "best_dec": "dec"},
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class EPPipelineClient:
|
|
42
|
+
"""Submit isolated WXT/FXT jobs to the configured SSH servers."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
ssh_username: Optional[str] = None,
|
|
47
|
+
ssh_password: Optional[str] = None,
|
|
48
|
+
ssh_key: Optional[str] = None,
|
|
49
|
+
ep_username: Optional[str] = None,
|
|
50
|
+
ep_password: Optional[str] = None,
|
|
51
|
+
hosts: Optional[Mapping[str, Union[str, HostProfile]]] = None,
|
|
52
|
+
local_root: str = "~/research/eptools-results",
|
|
53
|
+
local_pipeline_roots: Optional[Mapping[str, str]] = None,
|
|
54
|
+
remote_base: Optional[str] = None,
|
|
55
|
+
auto_deploy: bool = False,
|
|
56
|
+
fxt_image: str = "ep-fxt-pipeline:v2.0",
|
|
57
|
+
remote_install_roots: Optional[Mapping[str, str]] = None,
|
|
58
|
+
remote_job_roots: Optional[Mapping[str, str]] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
if remote_base is not None:
|
|
61
|
+
raise ValueError(
|
|
62
|
+
"remote_base is no longer supported because it deploys into a personal home; "
|
|
63
|
+
"use remote_install_roots and remote_job_roots with absolute shared paths"
|
|
64
|
+
)
|
|
65
|
+
host_values = dict(hosts or {"wxt": "epserver", "fxt": "server"})
|
|
66
|
+
self.hosts: Dict[str, HostProfile] = {}
|
|
67
|
+
for pipeline in ("wxt", "fxt"):
|
|
68
|
+
value = host_values.get(pipeline)
|
|
69
|
+
if value is None:
|
|
70
|
+
raise ValueError(f"Missing host mapping for {pipeline}")
|
|
71
|
+
if isinstance(value, HostProfile):
|
|
72
|
+
profile = value
|
|
73
|
+
else:
|
|
74
|
+
profile = HostProfile(alias=str(value))
|
|
75
|
+
self.hosts[pipeline] = HostProfile(
|
|
76
|
+
alias=profile.alias,
|
|
77
|
+
hostname=profile.hostname,
|
|
78
|
+
port=profile.port,
|
|
79
|
+
username=profile.username or ssh_username,
|
|
80
|
+
key_filename=profile.key_filename or ssh_key,
|
|
81
|
+
password=profile.password,
|
|
82
|
+
)
|
|
83
|
+
self.ssh_password = ssh_password
|
|
84
|
+
self.ep_username = ep_username
|
|
85
|
+
self.ep_password = ep_password
|
|
86
|
+
self.local_root = normalize_local_root(local_root)
|
|
87
|
+
self.local_pipeline_roots = {
|
|
88
|
+
key: Path(value).expanduser().resolve()
|
|
89
|
+
for key, value in (local_pipeline_roots or {}).items()
|
|
90
|
+
}
|
|
91
|
+
self.remote_install_roots = _validate_remote_roots(
|
|
92
|
+
"remote_install_roots", remote_install_roots or DEFAULT_REMOTE_INSTALL_ROOTS
|
|
93
|
+
)
|
|
94
|
+
self.remote_job_roots = _validate_remote_roots(
|
|
95
|
+
"remote_job_roots", remote_job_roots or DEFAULT_REMOTE_JOB_ROOTS
|
|
96
|
+
)
|
|
97
|
+
self.auto_deploy = auto_deploy
|
|
98
|
+
self.fxt_image = fxt_image
|
|
99
|
+
|
|
100
|
+
def _transport(self, host_alias: str) -> SSHTransport:
|
|
101
|
+
profile = next(item for item in self.hosts.values() if item.alias == host_alias)
|
|
102
|
+
password = self.ssh_password if profile.password is None else profile.password
|
|
103
|
+
return SSHTransport(profile, password=password)
|
|
104
|
+
|
|
105
|
+
def submit_wxt(
|
|
106
|
+
self,
|
|
107
|
+
source: WXTSource,
|
|
108
|
+
*,
|
|
109
|
+
review_regions: bool = False,
|
|
110
|
+
clobber: bool = False,
|
|
111
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
112
|
+
) -> PipelineJob:
|
|
113
|
+
return self._submit(
|
|
114
|
+
"wxt",
|
|
115
|
+
source.to_dict(),
|
|
116
|
+
{"review_regions": review_regions, "clobber": clobber, **dict(options or {})},
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def submit_fxt(
|
|
120
|
+
self,
|
|
121
|
+
source: FXTSource,
|
|
122
|
+
*,
|
|
123
|
+
review_pileup: str = "if_bright",
|
|
124
|
+
options: Optional[Mapping[str, Any]] = None,
|
|
125
|
+
) -> PipelineJob:
|
|
126
|
+
if review_pileup not in {"if_bright", "always", "never"}:
|
|
127
|
+
raise ValueError("review_pileup must be if_bright, always, or never")
|
|
128
|
+
if not self.ep_username or not self.ep_password:
|
|
129
|
+
raise ValueError("EP data-center username and password are required for FXT download")
|
|
130
|
+
return self._submit(
|
|
131
|
+
"fxt",
|
|
132
|
+
source.to_dict(),
|
|
133
|
+
{"review_pileup": review_pileup, "fxt_image": self.fxt_image, **dict(options or {})},
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def parameters(pipeline: str, **values: Any) -> Union[WXTSource, FXTSource]:
|
|
138
|
+
"""Validate source parameters locally. Coordinates are in degrees and t0 is ISO UTC.
|
|
139
|
+
|
|
140
|
+
Accepts EFXT catalog columns or public model field names. Optional
|
|
141
|
+
metadata accepts None or a blank string. nH_Galactic is in 10^22 cm^-2.
|
|
142
|
+
"""
|
|
143
|
+
if pipeline not in _EFXT_COLUMNS:
|
|
144
|
+
raise ValueError("pipeline must be 'wxt' or 'fxt'")
|
|
145
|
+
aliases = {"nH_Galactic": "nh_galactic", "z": "redshift", **_EFXT_COLUMNS[pipeline]}
|
|
146
|
+
for column, field in aliases.items():
|
|
147
|
+
if column in values:
|
|
148
|
+
if field in values:
|
|
149
|
+
raise ValueError(f"Use either {column} or {field}")
|
|
150
|
+
values[field] = values.pop(column)
|
|
151
|
+
|
|
152
|
+
for field in ("position_error", "nh_galactic", "redshift"):
|
|
153
|
+
if field in values:
|
|
154
|
+
value = values[field]
|
|
155
|
+
values[field] = None if _is_blank(value) else float(value)
|
|
156
|
+
for field in ("auto_obs", "is_grb", "gbm_cover"):
|
|
157
|
+
if field in values:
|
|
158
|
+
values[field] = _catalog_flag(field, values[field])
|
|
159
|
+
|
|
160
|
+
if pipeline == "wxt":
|
|
161
|
+
observations = values.pop("observations", None)
|
|
162
|
+
if "obs_id" in values or "cmos_id" in values:
|
|
163
|
+
if not _is_blank(observations):
|
|
164
|
+
raise ValueError("Use either observations or obs_id and cmos_id")
|
|
165
|
+
obs_ids = _catalog_ids(values.pop("obs_id", None), "obs_id")
|
|
166
|
+
cmos_ids = _catalog_ids(values.pop("cmos_id", None), "cmos_id")
|
|
167
|
+
if len(obs_ids) != len(cmos_ids):
|
|
168
|
+
raise ValueError("obs_id and cmos_id must have the same length")
|
|
169
|
+
roles = ["pointed"] * len(obs_ids)
|
|
170
|
+
if values.get("auto_obs") and len(obs_ids) >= 3:
|
|
171
|
+
roles = ["pre_pointed"] * (len(obs_ids) - 2) + ["post_pointed"] * 2
|
|
172
|
+
observations = [
|
|
173
|
+
WXTObservation(obs_id, cmos_id, role)
|
|
174
|
+
for obs_id, cmos_id, role in zip(obs_ids, cmos_ids, roles)
|
|
175
|
+
]
|
|
176
|
+
return WXTSource(
|
|
177
|
+
observations=[
|
|
178
|
+
item if isinstance(item, WXTObservation) else WXTObservation(**item)
|
|
179
|
+
for item in (() if _is_blank(observations) else observations)
|
|
180
|
+
],
|
|
181
|
+
**values,
|
|
182
|
+
)
|
|
183
|
+
return FXTSource(**values)
|
|
184
|
+
|
|
185
|
+
def submit(
|
|
186
|
+
self,
|
|
187
|
+
pipeline: Union[str, WXTSource, FXTSource],
|
|
188
|
+
source: Optional[Union[WXTSource, FXTSource]] = None,
|
|
189
|
+
**kwargs,
|
|
190
|
+
) -> PipelineJob:
|
|
191
|
+
"""Submit prepared parameters, or pass an explicit pipeline and source."""
|
|
192
|
+
if source is None and isinstance(pipeline, (WXTSource, FXTSource)):
|
|
193
|
+
source = pipeline
|
|
194
|
+
pipeline = "wxt" if isinstance(source, WXTSource) else "fxt"
|
|
195
|
+
if source is None:
|
|
196
|
+
raise TypeError("submit requires prepared source parameters")
|
|
197
|
+
if pipeline == "wxt":
|
|
198
|
+
return self.submit_wxt(source, **kwargs)
|
|
199
|
+
if pipeline == "fxt":
|
|
200
|
+
return self.submit_fxt(source, **kwargs)
|
|
201
|
+
raise ValueError("pipeline must be 'wxt' or 'fxt'")
|
|
202
|
+
|
|
203
|
+
def status(
|
|
204
|
+
self, job: Union[PipelineJob, str], *, pipeline: Optional[str] = None
|
|
205
|
+
) -> Dict[str, Any]:
|
|
206
|
+
"""Return the current remote status. A job ID requires its pipeline name."""
|
|
207
|
+
return self._job_handle(job, pipeline).status()
|
|
208
|
+
|
|
209
|
+
def download(
|
|
210
|
+
self,
|
|
211
|
+
job: Union[PipelineJob, str],
|
|
212
|
+
destination: Optional[str] = None,
|
|
213
|
+
*,
|
|
214
|
+
pipeline: Optional[str] = None,
|
|
215
|
+
) -> Path:
|
|
216
|
+
"""Download the manifest's files and return the local directory."""
|
|
217
|
+
return self._job_handle(job, pipeline).download(destination)
|
|
218
|
+
|
|
219
|
+
def _job_handle(self, job: Union[PipelineJob, str], pipeline: Optional[str]) -> PipelineJob:
|
|
220
|
+
if isinstance(job, PipelineJob):
|
|
221
|
+
if pipeline is not None and pipeline != job.pipeline:
|
|
222
|
+
raise ValueError(f"Job {job.job_id} belongs to the {job.pipeline} pipeline")
|
|
223
|
+
return job
|
|
224
|
+
if pipeline is None:
|
|
225
|
+
raise ValueError("pipeline is required when using a job ID")
|
|
226
|
+
return self.attach(job, pipeline)
|
|
227
|
+
|
|
228
|
+
def deploy(self, pipelines: Sequence[str] = ("wxt", "fxt")) -> Dict[str, str]:
|
|
229
|
+
deployed: Dict[str, str] = {}
|
|
230
|
+
for pipeline in pipelines:
|
|
231
|
+
if pipeline not in self.hosts:
|
|
232
|
+
raise ValueError(f"Unknown pipeline: {pipeline}")
|
|
233
|
+
with self._transport(self.hosts[pipeline].alias) as transport:
|
|
234
|
+
context = self._ensure_remote_context(transport, pipeline, force=True)
|
|
235
|
+
deployed[pipeline] = context["pipeline_root"]
|
|
236
|
+
return deployed
|
|
237
|
+
|
|
238
|
+
def attach(self, job_id: str, pipeline: str) -> PipelineJob:
|
|
239
|
+
"""Reconnect to a previously submitted job."""
|
|
240
|
+
try:
|
|
241
|
+
uuid.UUID(job_id)
|
|
242
|
+
except ValueError as exc:
|
|
243
|
+
raise ValueError("job_id must be a UUID") from exc
|
|
244
|
+
if pipeline not in self.hosts:
|
|
245
|
+
raise ValueError("pipeline must be 'wxt' or 'fxt'")
|
|
246
|
+
host = self.hosts[pipeline]
|
|
247
|
+
with self._transport(host.alias) as transport:
|
|
248
|
+
remote_dir = posixpath.join(self._user_job_root(transport, pipeline), job_id)
|
|
249
|
+
if not transport.exists(posixpath.join(remote_dir, "request.json")):
|
|
250
|
+
raise FileNotFoundError(f"Remote job does not exist: {job_id}")
|
|
251
|
+
return PipelineJob(
|
|
252
|
+
self, job_id, pipeline, host.alias, remote_dir,
|
|
253
|
+
self.local_root / job_id,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
def _submit(self, pipeline: str, source: Dict[str, Any], options: Dict[str, Any]) -> PipelineJob:
|
|
257
|
+
job_id = str(uuid.uuid4())
|
|
258
|
+
host = self.hosts[pipeline]
|
|
259
|
+
with self._transport(host.alias) as transport:
|
|
260
|
+
context = self._ensure_remote_context(transport, pipeline, force=False)
|
|
261
|
+
transport.mkdir(context["user_job_root"], mode=0o700)
|
|
262
|
+
remote_dir = posixpath.join(context["user_job_root"], job_id)
|
|
263
|
+
transport.mkdir(remote_dir, mode=0o700)
|
|
264
|
+
transport.mkdir(posixpath.join(remote_dir, "control"), mode=0o700)
|
|
265
|
+
request = {
|
|
266
|
+
"schema_version": 1,
|
|
267
|
+
"job_id": job_id,
|
|
268
|
+
"pipeline": pipeline,
|
|
269
|
+
"source": source,
|
|
270
|
+
"options": options,
|
|
271
|
+
"deployment": {
|
|
272
|
+
"pipeline_root": context["pipeline_root"],
|
|
273
|
+
"pipeline_revision": context["revision"],
|
|
274
|
+
"wxt_init_script": context.get("wxt_init_script"),
|
|
275
|
+
},
|
|
276
|
+
}
|
|
277
|
+
transport.put_json(request, posixpath.join(remote_dir, "request.json"))
|
|
278
|
+
if pipeline == "fxt":
|
|
279
|
+
transport.mkdir(posixpath.join(remote_dir, "private"), mode=0o700)
|
|
280
|
+
transport.put_json(
|
|
281
|
+
{"ep_username": self.ep_username, "ep_password": self.ep_password},
|
|
282
|
+
posixpath.join(remote_dir, "private", "secrets.json"),
|
|
283
|
+
)
|
|
284
|
+
self._launch(transport, pipeline, remote_dir, resume=False)
|
|
285
|
+
|
|
286
|
+
local_dir = self.local_root / source["name"] / job_id
|
|
287
|
+
return PipelineJob(self, job_id, pipeline, host.alias, remote_dir, local_dir)
|
|
288
|
+
|
|
289
|
+
def _ensure_remote_context(self, transport: SSHTransport, pipeline: str, force: bool) -> Dict[str, str]:
|
|
290
|
+
can_deploy = force or self.auto_deploy
|
|
291
|
+
local_root = None
|
|
292
|
+
if can_deploy:
|
|
293
|
+
local_root = self.local_pipeline_roots.get(pipeline)
|
|
294
|
+
if local_root is None:
|
|
295
|
+
raise ValueError(f"Deployment requires local_pipeline_roots[{pipeline!r}]")
|
|
296
|
+
if not local_root.is_dir():
|
|
297
|
+
raise FileNotFoundError(f"Local {pipeline.upper()} pipeline directory is missing: {local_root}")
|
|
298
|
+
install_root = self.remote_install_roots[pipeline]
|
|
299
|
+
job_base = self.remote_job_roots[pipeline]
|
|
300
|
+
username = _safe_username(transport.username())
|
|
301
|
+
user_job_root = posixpath.join(job_base, username)
|
|
302
|
+
if not transport.exists(install_root):
|
|
303
|
+
raise RuntimeError(
|
|
304
|
+
f"Shared install root does not exist on {transport.profile.alias}: {install_root}"
|
|
305
|
+
)
|
|
306
|
+
if not transport.exists(job_base):
|
|
307
|
+
raise RuntimeError(
|
|
308
|
+
f"Shared job root does not exist on {transport.profile.alias}: {job_base}"
|
|
309
|
+
)
|
|
310
|
+
if can_deploy:
|
|
311
|
+
transport.mkdir(install_root, mode=0o2755)
|
|
312
|
+
transport.mkdir(posixpath.join(install_root, "bin"), mode=0o2755)
|
|
313
|
+
transport.mkdir(posixpath.join(install_root, "pipelines"), mode=0o2755)
|
|
314
|
+
transport.mkdir(posixpath.join(install_root, "pipelines", pipeline), mode=0o2755)
|
|
315
|
+
runner_local = Path(__file__).with_name("_server_runner.py")
|
|
316
|
+
runner_remote = posixpath.join(install_root, "bin", "runner.py")
|
|
317
|
+
local_runner_sha = _sha256_file(runner_local)
|
|
318
|
+
runner_marker = runner_remote + ".sha256"
|
|
319
|
+
remote_runner_sha = transport.get_bytes(runner_marker).decode().strip() if transport.exists(runner_marker) else ""
|
|
320
|
+
if force or remote_runner_sha != local_runner_sha:
|
|
321
|
+
if not self.auto_deploy and not force:
|
|
322
|
+
raise RuntimeError(
|
|
323
|
+
"The shared eptools runner is missing or outdated; ask the maintainer "
|
|
324
|
+
"to call client.deploy(), or use auto_deploy=True with maintainer access"
|
|
325
|
+
)
|
|
326
|
+
transport.put_file(runner_local, runner_remote, mode=0o755)
|
|
327
|
+
transport.put_bytes((local_runner_sha + "\n").encode(), runner_marker, mode=0o644)
|
|
328
|
+
|
|
329
|
+
wxt_init_script = ""
|
|
330
|
+
if pipeline == "wxt":
|
|
331
|
+
init_local = Path(__file__).with_name("_wxt_init.sh")
|
|
332
|
+
wxt_init_script = posixpath.join(install_root, "bin", "wxt-init.sh")
|
|
333
|
+
init_marker = wxt_init_script + ".sha256"
|
|
334
|
+
local_init_sha = _sha256_file(init_local)
|
|
335
|
+
remote_init_sha = transport.get_bytes(init_marker).decode().strip() if transport.exists(init_marker) else ""
|
|
336
|
+
if force or remote_init_sha != local_init_sha:
|
|
337
|
+
if not self.auto_deploy and not force:
|
|
338
|
+
raise RuntimeError(
|
|
339
|
+
"The shared WXT initialization script is missing or outdated; "
|
|
340
|
+
"ask the maintainer to call client.deploy()"
|
|
341
|
+
)
|
|
342
|
+
transport.put_file(init_local, wxt_init_script, mode=0o755)
|
|
343
|
+
transport.put_bytes((local_init_sha + "\n").encode(), init_marker, mode=0o644)
|
|
344
|
+
|
|
345
|
+
current_marker = posixpath.join(install_root, "pipelines", pipeline, "CURRENT")
|
|
346
|
+
if local_root is not None:
|
|
347
|
+
revision = _revision(local_root)
|
|
348
|
+
elif transport.exists(current_marker):
|
|
349
|
+
revision = transport.get_bytes(current_marker).decode().strip()
|
|
350
|
+
if not revision or "/" in revision or revision in {".", ".."}:
|
|
351
|
+
raise RuntimeError(f"Invalid shared {pipeline.upper()} CURRENT revision marker")
|
|
352
|
+
else:
|
|
353
|
+
raise RuntimeError(
|
|
354
|
+
f"No shared {pipeline.upper()} deployment is selected; "
|
|
355
|
+
"ask the maintainer to call client.deploy()"
|
|
356
|
+
)
|
|
357
|
+
pipeline_remote = posixpath.join(install_root, "pipelines", pipeline, revision)
|
|
358
|
+
marker = posixpath.join(pipeline_remote, ".eptools-deployed")
|
|
359
|
+
if force or not transport.exists(marker):
|
|
360
|
+
if local_root is None:
|
|
361
|
+
raise RuntimeError(
|
|
362
|
+
f"{pipeline.upper()} pipeline revision {revision} is not deployed; "
|
|
363
|
+
"call client.deploy() or set auto_deploy=True"
|
|
364
|
+
)
|
|
365
|
+
self._upload_pipeline(transport, local_root, pipeline_remote, revision)
|
|
366
|
+
return {
|
|
367
|
+
"install_root": install_root,
|
|
368
|
+
"user_job_root": user_job_root,
|
|
369
|
+
"runner": runner_remote,
|
|
370
|
+
"pipeline_root": pipeline_remote,
|
|
371
|
+
"revision": revision,
|
|
372
|
+
"wxt_init_script": wxt_init_script,
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
def _upload_pipeline(self, transport: SSHTransport, root: Path, remote_root: str, revision: str) -> None:
|
|
376
|
+
with tempfile.TemporaryDirectory(prefix="eptools-deploy-") as tmp:
|
|
377
|
+
archive = Path(tmp) / "pipeline.tar.gz"
|
|
378
|
+
with tarfile.open(archive, "w:gz") as tar:
|
|
379
|
+
for path in root.rglob("*"):
|
|
380
|
+
relative = path.relative_to(root)
|
|
381
|
+
if _excluded(relative):
|
|
382
|
+
continue
|
|
383
|
+
tar.add(path, arcname=str(relative), recursive=False)
|
|
384
|
+
remote_archive = remote_root + ".tar.gz"
|
|
385
|
+
transport.put_file(archive, remote_archive, mode=0o644)
|
|
386
|
+
command = (
|
|
387
|
+
f"mkdir -p {shlex.quote(remote_root)} && "
|
|
388
|
+
f"tar -xzf {shlex.quote(remote_archive)} -C {shlex.quote(remote_root)} && "
|
|
389
|
+
f"printf '%s\\n' {shlex.quote(revision)} > {shlex.quote(posixpath.join(remote_root, '.eptools-deployed'))} && "
|
|
390
|
+
f"printf '%s\\n' {shlex.quote(revision)} > {shlex.quote(posixpath.join(posixpath.dirname(remote_root), 'CURRENT'))} && "
|
|
391
|
+
f"chmod -R go-w,a+rX {shlex.quote(remote_root)} && "
|
|
392
|
+
f"chmod 644 {shlex.quote(posixpath.join(posixpath.dirname(remote_root), 'CURRENT'))} && "
|
|
393
|
+
f"rm -f {shlex.quote(remote_archive)}"
|
|
394
|
+
)
|
|
395
|
+
transport.run(command)
|
|
396
|
+
|
|
397
|
+
def _launch(self, transport: SSHTransport, pipeline: str, remote_dir: str, resume: bool) -> None:
|
|
398
|
+
runner = posixpath.join(self.remote_install_roots[pipeline], "bin", "runner.py")
|
|
399
|
+
mode = "resume" if resume else "run"
|
|
400
|
+
launch_log = posixpath.join(remote_dir, "runner-launch.log")
|
|
401
|
+
command = (
|
|
402
|
+
f"nohup python3 {shlex.quote(runner)} {mode} --job-dir {shlex.quote(remote_dir)} "
|
|
403
|
+
f"> {shlex.quote(launch_log)} 2>&1 < /dev/null &"
|
|
404
|
+
)
|
|
405
|
+
transport.run(command)
|
|
406
|
+
|
|
407
|
+
def _user_job_root(self, transport: SSHTransport, pipeline: str) -> str:
|
|
408
|
+
return posixpath.join(self.remote_job_roots[pipeline], _safe_username(transport.username()))
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _catalog_flag(field: str, value: Any) -> Optional[bool]:
|
|
412
|
+
if _is_blank(value):
|
|
413
|
+
return None
|
|
414
|
+
if isinstance(value, str):
|
|
415
|
+
value = value.strip()
|
|
416
|
+
if value in (0, "0"):
|
|
417
|
+
return False
|
|
418
|
+
if value in (1, "1"):
|
|
419
|
+
return True
|
|
420
|
+
raise ValueError(f"{field} must be 0, 1, or blank")
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _catalog_ids(value: Any, field: str) -> Sequence[Any]:
|
|
424
|
+
if _is_blank(value):
|
|
425
|
+
raise ValueError(f"{field} is required")
|
|
426
|
+
if isinstance(value, str) and value.strip().startswith(("[", "(")):
|
|
427
|
+
try:
|
|
428
|
+
value = ast.literal_eval(value.strip())
|
|
429
|
+
except (SyntaxError, ValueError) as exc:
|
|
430
|
+
raise ValueError(f"{field} must contain valid observation or detector IDs") from exc
|
|
431
|
+
return value if isinstance(value, (list, tuple)) else [value]
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _sha256_file(path: Path) -> str:
|
|
435
|
+
digest = hashlib.sha256()
|
|
436
|
+
with path.open("rb") as handle:
|
|
437
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
438
|
+
digest.update(chunk)
|
|
439
|
+
return digest.hexdigest()
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _revision(root: Path) -> str:
|
|
443
|
+
try:
|
|
444
|
+
commit = subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip()
|
|
445
|
+
dirty = subprocess.run(["git", "-C", str(root), "diff", "--quiet"]).returncode != 0
|
|
446
|
+
return commit[:12] + ("-dirty" if dirty else "")
|
|
447
|
+
except (OSError, subprocess.CalledProcessError):
|
|
448
|
+
return _tree_digest(root)[:12]
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def _tree_digest(root: Path) -> str:
|
|
452
|
+
digest = hashlib.sha256()
|
|
453
|
+
for path in sorted(item for item in root.rglob("*") if item.is_file()):
|
|
454
|
+
relative = path.relative_to(root)
|
|
455
|
+
if _excluded(relative):
|
|
456
|
+
continue
|
|
457
|
+
digest.update(str(relative).encode())
|
|
458
|
+
digest.update(_sha256_file(path).encode())
|
|
459
|
+
return digest.hexdigest()
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _excluded(relative: Path) -> bool:
|
|
463
|
+
blocked = {".git", "__pycache__", ".pytest_cache", "results", "data", "login_debug"}
|
|
464
|
+
return any(part in blocked for part in relative.parts) or relative.suffix in {".pyc", ".pyo"}
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _validate_remote_roots(name: str, roots: Mapping[str, str]) -> Dict[str, str]:
|
|
468
|
+
validated: Dict[str, str] = {}
|
|
469
|
+
for pipeline in ("wxt", "fxt"):
|
|
470
|
+
value = roots.get(pipeline)
|
|
471
|
+
if not value:
|
|
472
|
+
raise ValueError(f"Missing {name} mapping for {pipeline}")
|
|
473
|
+
value = str(value)
|
|
474
|
+
if not posixpath.isabs(value):
|
|
475
|
+
raise ValueError(f"{name}[{pipeline!r}] must be an absolute POSIX path")
|
|
476
|
+
normalized = posixpath.normpath(value)
|
|
477
|
+
if normalized == "/" or normalized.startswith("/home/"):
|
|
478
|
+
raise ValueError(f"{name}[{pipeline!r}] must be a shared non-home directory")
|
|
479
|
+
validated[pipeline] = normalized
|
|
480
|
+
return validated
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _safe_username(username: str) -> str:
|
|
484
|
+
value = str(username or "").strip()
|
|
485
|
+
if not value or value in {".", ".."} or "/" in value:
|
|
486
|
+
raise ValueError("SSH username cannot be used as a remote job-directory name")
|
|
487
|
+
return value
|
eptools/job.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Remote job handle returned by EPPipelineClient."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import posixpath
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Dict, Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_WAIT_RETURNS = {
|
|
13
|
+
"awaiting_captcha",
|
|
14
|
+
"needs_review",
|
|
15
|
+
"completed",
|
|
16
|
+
"failed",
|
|
17
|
+
"cancelled",
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class PipelineJob:
|
|
22
|
+
def __init__(self, client, job_id: str, pipeline: str, host_alias: str, remote_dir: str, local_dir: Path):
|
|
23
|
+
self._client = client
|
|
24
|
+
self.job_id = job_id
|
|
25
|
+
self.pipeline = pipeline
|
|
26
|
+
self.host_alias = host_alias
|
|
27
|
+
self.remote_dir = remote_dir
|
|
28
|
+
self.local_dir = local_dir
|
|
29
|
+
|
|
30
|
+
def status(self) -> Dict[str, Any]:
|
|
31
|
+
with self._client._transport(self.host_alias) as transport:
|
|
32
|
+
path = posixpath.join(self.remote_dir, "status.json")
|
|
33
|
+
if not transport.exists(path):
|
|
34
|
+
return {"job_id": self.job_id, "state": "queued"}
|
|
35
|
+
return transport.get_json(path)
|
|
36
|
+
|
|
37
|
+
def wait(self, poll_interval: float = 10.0, timeout: Optional[float] = None) -> Dict[str, Any]:
|
|
38
|
+
started = time.monotonic()
|
|
39
|
+
while True:
|
|
40
|
+
status = self.status()
|
|
41
|
+
if status.get("state") in _WAIT_RETURNS:
|
|
42
|
+
return status
|
|
43
|
+
if timeout is not None and time.monotonic() - started > timeout:
|
|
44
|
+
raise TimeoutError(f"Timed out waiting for job {self.job_id}")
|
|
45
|
+
time.sleep(poll_interval)
|
|
46
|
+
|
|
47
|
+
def provide_captcha(self, code: str) -> None:
|
|
48
|
+
code = str(code).strip()
|
|
49
|
+
if not code or len(code) > 32:
|
|
50
|
+
raise ValueError("Captcha code must contain 1-32 characters")
|
|
51
|
+
remote = posixpath.join(self.remote_dir, "control", "captcha.txt")
|
|
52
|
+
with self._client._transport(self.host_alias) as transport:
|
|
53
|
+
transport.put_bytes((code + "\n").encode("utf-8"), remote, mode=0o600)
|
|
54
|
+
|
|
55
|
+
def resume(self, review_file: Optional[str] = None) -> None:
|
|
56
|
+
with self._client._transport(self.host_alias) as transport:
|
|
57
|
+
if review_file:
|
|
58
|
+
local = Path(review_file).expanduser().resolve()
|
|
59
|
+
if not local.is_file():
|
|
60
|
+
raise FileNotFoundError(local)
|
|
61
|
+
transport.put_file(
|
|
62
|
+
local,
|
|
63
|
+
posixpath.join(self.remote_dir, "control", "review_file" + local.suffix),
|
|
64
|
+
mode=0o600,
|
|
65
|
+
)
|
|
66
|
+
transport.put_json(
|
|
67
|
+
{"resume": True},
|
|
68
|
+
posixpath.join(self.remote_dir, "control", "continue.json"),
|
|
69
|
+
)
|
|
70
|
+
self._client._launch(transport, self.pipeline, self.remote_dir, resume=True)
|
|
71
|
+
|
|
72
|
+
def download(self, destination: Optional[str] = None) -> Path:
|
|
73
|
+
target = Path(destination).expanduser().resolve() if destination else self.local_dir
|
|
74
|
+
manifest_path = posixpath.join(self.remote_dir, "manifest.json")
|
|
75
|
+
with self._client._transport(self.host_alias) as transport:
|
|
76
|
+
if not transport.exists(manifest_path):
|
|
77
|
+
raise RuntimeError("Result manifest is not available yet")
|
|
78
|
+
manifest = transport.get_json(manifest_path)
|
|
79
|
+
for item in manifest.get("files", []):
|
|
80
|
+
relative = item["path"]
|
|
81
|
+
local = target / relative
|
|
82
|
+
if local.exists() and _sha256(local) == item["sha256"]:
|
|
83
|
+
continue
|
|
84
|
+
transport.get_file(posixpath.join(self.remote_dir, relative), local)
|
|
85
|
+
if _sha256(local) != item["sha256"]:
|
|
86
|
+
raise IOError(f"Checksum mismatch after downloading {relative}")
|
|
87
|
+
return target
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _sha256(path: Path) -> str:
|
|
91
|
+
digest = hashlib.sha256()
|
|
92
|
+
with path.open("rb") as handle:
|
|
93
|
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
|
94
|
+
digest.update(chunk)
|
|
95
|
+
return digest.hexdigest()
|