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/models.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Validated public request models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import asdict, dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Dict, Optional, Sequence
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
_SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$")
|
|
13
|
+
_OBSID = re.compile(r"^\d{11}$")
|
|
14
|
+
_WXT_ROLE_ALIASES = {
|
|
15
|
+
"pre_slew": "pre_pointed",
|
|
16
|
+
"post_slew": "post_pointed",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _is_blank(value: Any) -> bool:
|
|
21
|
+
return value is None or (isinstance(value, str) and not value.strip())
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _validate_name(value: str, field_name: str = "name") -> str:
|
|
25
|
+
if _is_blank(value):
|
|
26
|
+
raise ValueError(f"{field_name} is required")
|
|
27
|
+
value = str(value).strip()
|
|
28
|
+
if not _SAFE_NAME.fullmatch(value):
|
|
29
|
+
raise ValueError(
|
|
30
|
+
f"{field_name} must start with an alphanumeric character and only "
|
|
31
|
+
"contain letters, digits, '.', '_' or '-'."
|
|
32
|
+
)
|
|
33
|
+
return value
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _validate_coordinates(ra: float, dec: float) -> None:
|
|
37
|
+
if _is_blank(ra):
|
|
38
|
+
raise ValueError("ra is required")
|
|
39
|
+
if _is_blank(dec):
|
|
40
|
+
raise ValueError("dec is required")
|
|
41
|
+
ra = float(ra)
|
|
42
|
+
dec = float(dec)
|
|
43
|
+
if not math.isfinite(ra) or not 0.0 <= ra < 360.0:
|
|
44
|
+
raise ValueError("ra must be finite and in [0, 360) degrees")
|
|
45
|
+
if not math.isfinite(dec) or not -90.0 <= dec <= 90.0:
|
|
46
|
+
raise ValueError("dec must be finite and in [-90, 90] degrees")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class HostProfile:
|
|
51
|
+
"""SSH endpoint. Missing connection fields are loaded from ~/.ssh/config."""
|
|
52
|
+
|
|
53
|
+
alias: str
|
|
54
|
+
hostname: Optional[str] = None
|
|
55
|
+
port: Optional[int] = None
|
|
56
|
+
username: Optional[str] = None
|
|
57
|
+
key_filename: Optional[str] = None
|
|
58
|
+
password: Optional[str] = field(default=None, repr=False)
|
|
59
|
+
|
|
60
|
+
def __post_init__(self) -> None:
|
|
61
|
+
_validate_name(self.alias, "host alias")
|
|
62
|
+
if self.port is not None and not 1 <= self.port <= 65535:
|
|
63
|
+
raise ValueError("SSH port must be in [1, 65535]")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class WXTObservation:
|
|
68
|
+
obs_id: str
|
|
69
|
+
cmos_id: str
|
|
70
|
+
role: str = "pointed"
|
|
71
|
+
|
|
72
|
+
def __post_init__(self) -> None:
|
|
73
|
+
obs_id = str(self.obs_id).strip()
|
|
74
|
+
cmos_id = str(self.cmos_id).strip()
|
|
75
|
+
if not _OBSID.fullmatch(obs_id):
|
|
76
|
+
raise ValueError("WXT obs_id must contain exactly 11 digits")
|
|
77
|
+
if not cmos_id.isdigit() or not 1 <= int(cmos_id) <= 48:
|
|
78
|
+
raise ValueError("WXT cmos_id must be an integer from 1 to 48")
|
|
79
|
+
role = "pointed" if _is_blank(self.role) else _WXT_ROLE_ALIASES.get(self.role, self.role)
|
|
80
|
+
if role not in {"pointed", "pre_pointed", "post_pointed"}:
|
|
81
|
+
raise ValueError("Unsupported WXT observation role")
|
|
82
|
+
object.__setattr__(self, "obs_id", obs_id)
|
|
83
|
+
object.__setattr__(self, "cmos_id", cmos_id)
|
|
84
|
+
object.__setattr__(self, "role", role)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class WXTSource:
|
|
89
|
+
name: str
|
|
90
|
+
observations: Sequence[WXTObservation]
|
|
91
|
+
ra: float
|
|
92
|
+
dec: float
|
|
93
|
+
t0: str
|
|
94
|
+
auto_obs: bool = False
|
|
95
|
+
position_error: Optional[float] = None
|
|
96
|
+
nh_galactic: Optional[float] = None
|
|
97
|
+
redshift: Optional[float] = None
|
|
98
|
+
is_grb: Optional[bool] = False
|
|
99
|
+
gbm_cover: Optional[bool] = False
|
|
100
|
+
|
|
101
|
+
def __post_init__(self) -> None:
|
|
102
|
+
object.__setattr__(self, "name", _validate_name(self.name))
|
|
103
|
+
_validate_coordinates(self.ra, self.dec)
|
|
104
|
+
if not self.observations:
|
|
105
|
+
raise ValueError("At least one WXT observation is required")
|
|
106
|
+
roles = [item.role for item in self.observations]
|
|
107
|
+
if self.auto_obs:
|
|
108
|
+
pre = [item for item in self.observations if item.role == "pre_pointed"]
|
|
109
|
+
post = [item for item in self.observations if item.role == "post_pointed"]
|
|
110
|
+
if not pre or len(post) != 2 or len(pre) + len(post) != len(self.observations):
|
|
111
|
+
raise ValueError(
|
|
112
|
+
"The current auto_obs adapter requires one or more "
|
|
113
|
+
"pre_pointed entries and exactly two post_pointed entries"
|
|
114
|
+
)
|
|
115
|
+
if len({item.obs_id for item in pre}) != 1:
|
|
116
|
+
raise ValueError("All pre_pointed entries must use the same obs_id")
|
|
117
|
+
if len({item.obs_id for item in post}) != 1:
|
|
118
|
+
raise ValueError("Both post_pointed entries must use the same obs_id")
|
|
119
|
+
if {item.cmos_id for item in post} != {"14", "37"}:
|
|
120
|
+
raise ValueError(
|
|
121
|
+
"The current WXT auto_obs pipeline is limited to "
|
|
122
|
+
"post-pointed CMOS14 and CMOS37"
|
|
123
|
+
)
|
|
124
|
+
elif any(role != "pointed" for role in roles):
|
|
125
|
+
raise ValueError("Non-pointed roles require auto_obs=True")
|
|
126
|
+
elif len(self.observations) != 1:
|
|
127
|
+
raise ValueError("A normal pointed WXT job requires exactly one observation")
|
|
128
|
+
if _is_blank(self.t0):
|
|
129
|
+
raise ValueError("WXT t0 (T0_GCN) is required")
|
|
130
|
+
|
|
131
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
132
|
+
data = asdict(self)
|
|
133
|
+
data["observations"] = [asdict(item) for item in self.observations]
|
|
134
|
+
return data
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class FXTSource:
|
|
139
|
+
name: str
|
|
140
|
+
ra: float
|
|
141
|
+
dec: float
|
|
142
|
+
t0: str
|
|
143
|
+
nh_galactic: Optional[float] = None
|
|
144
|
+
redshift: Optional[float] = None
|
|
145
|
+
auto_obs: bool = False
|
|
146
|
+
|
|
147
|
+
def __post_init__(self) -> None:
|
|
148
|
+
object.__setattr__(self, "name", _validate_name(self.name))
|
|
149
|
+
_validate_coordinates(self.ra, self.dec)
|
|
150
|
+
if _is_blank(self.t0):
|
|
151
|
+
raise ValueError("FXT t0 (T0) is required for the archive query")
|
|
152
|
+
for field in ("nh_galactic", "redshift"):
|
|
153
|
+
value = getattr(self, field)
|
|
154
|
+
if _is_blank(value):
|
|
155
|
+
object.__setattr__(self, field, None)
|
|
156
|
+
else:
|
|
157
|
+
number = float(value)
|
|
158
|
+
if not math.isfinite(number) or number < 0:
|
|
159
|
+
raise ValueError(f"{field} must be finite and non-negative")
|
|
160
|
+
object.__setattr__(self, field, number)
|
|
161
|
+
|
|
162
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
163
|
+
return asdict(self)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def normalize_local_root(path: str) -> Path:
|
|
167
|
+
return Path(path).expanduser().resolve()
|
eptools/transport.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Paramiko-backed SSH/SFTP operations.
|
|
2
|
+
|
|
3
|
+
Paramiko is imported lazily so request validation and unit tests do not need a
|
|
4
|
+
live SSH dependency.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import io
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import posixpath
|
|
13
|
+
import stat
|
|
14
|
+
import getpass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Dict, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
from .models import HostProfile
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RemoteCommandError(RuntimeError):
|
|
22
|
+
def __init__(self, command: str, code: int, stdout: str, stderr: str):
|
|
23
|
+
super().__init__(f"Remote command failed with exit code {code}: {command}\n{stderr}")
|
|
24
|
+
self.command = command
|
|
25
|
+
self.code = code
|
|
26
|
+
self.stdout = stdout
|
|
27
|
+
self.stderr = stderr
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SSHTransport:
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
profile: HostProfile,
|
|
34
|
+
password: Optional[str] = None,
|
|
35
|
+
ssh_config: str = "~/.ssh/config",
|
|
36
|
+
) -> None:
|
|
37
|
+
self.profile = profile
|
|
38
|
+
self.password = password
|
|
39
|
+
self.ssh_config = str(Path(ssh_config).expanduser())
|
|
40
|
+
self._client = None
|
|
41
|
+
self._sftp = None
|
|
42
|
+
|
|
43
|
+
def _connection_fields(self) -> Dict[str, Any]:
|
|
44
|
+
fields: Dict[str, Any] = {}
|
|
45
|
+
try:
|
|
46
|
+
import paramiko
|
|
47
|
+
|
|
48
|
+
parser = paramiko.SSHConfig()
|
|
49
|
+
config_path = Path(self.ssh_config)
|
|
50
|
+
if config_path.exists():
|
|
51
|
+
with config_path.open("r", encoding="utf-8") as handle:
|
|
52
|
+
parser.parse(handle)
|
|
53
|
+
fields.update(parser.lookup(self.profile.alias))
|
|
54
|
+
except ImportError as exc:
|
|
55
|
+
raise RuntimeError(
|
|
56
|
+
"Paramiko is required for remote jobs. Install eptools with "
|
|
57
|
+
"`python -m pip install -e .`."
|
|
58
|
+
) from exc
|
|
59
|
+
|
|
60
|
+
fields["hostname"] = self.profile.hostname or fields.get("hostname") or self.profile.alias
|
|
61
|
+
fields["username"] = self.profile.username or fields.get("user")
|
|
62
|
+
fields["port"] = self.profile.port or int(fields.get("port", 22))
|
|
63
|
+
identity = self.profile.key_filename or fields.get("identityfile")
|
|
64
|
+
if isinstance(identity, (list, tuple)):
|
|
65
|
+
identity = identity[0] if identity else None
|
|
66
|
+
fields["key_filename"] = str(Path(identity).expanduser()) if identity else None
|
|
67
|
+
return fields
|
|
68
|
+
|
|
69
|
+
def connect(self) -> "SSHTransport":
|
|
70
|
+
if self._client is not None:
|
|
71
|
+
return self
|
|
72
|
+
import paramiko
|
|
73
|
+
|
|
74
|
+
fields = self._connection_fields()
|
|
75
|
+
client = paramiko.SSHClient()
|
|
76
|
+
client.load_system_host_keys()
|
|
77
|
+
client.set_missing_host_key_policy(paramiko.RejectPolicy())
|
|
78
|
+
client.connect(
|
|
79
|
+
hostname=fields["hostname"],
|
|
80
|
+
port=fields["port"],
|
|
81
|
+
username=fields["username"],
|
|
82
|
+
key_filename=fields["key_filename"],
|
|
83
|
+
password=self.password,
|
|
84
|
+
look_for_keys=True,
|
|
85
|
+
allow_agent=True,
|
|
86
|
+
timeout=30,
|
|
87
|
+
)
|
|
88
|
+
self._client = client
|
|
89
|
+
self._sftp = client.open_sftp()
|
|
90
|
+
return self
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def sftp(self):
|
|
94
|
+
self.connect()
|
|
95
|
+
return self._sftp
|
|
96
|
+
|
|
97
|
+
def close(self) -> None:
|
|
98
|
+
if self._sftp is not None:
|
|
99
|
+
self._sftp.close()
|
|
100
|
+
if self._client is not None:
|
|
101
|
+
self._client.close()
|
|
102
|
+
self._sftp = None
|
|
103
|
+
self._client = None
|
|
104
|
+
|
|
105
|
+
def __enter__(self) -> "SSHTransport":
|
|
106
|
+
return self.connect()
|
|
107
|
+
|
|
108
|
+
def __exit__(self, exc_type, exc, traceback) -> None:
|
|
109
|
+
self.close()
|
|
110
|
+
|
|
111
|
+
def home(self) -> str:
|
|
112
|
+
return self.sftp.normalize(".")
|
|
113
|
+
|
|
114
|
+
def username(self) -> str:
|
|
115
|
+
self.connect()
|
|
116
|
+
active = self._client.get_transport()
|
|
117
|
+
if active is not None and active.get_username():
|
|
118
|
+
return active.get_username()
|
|
119
|
+
return self._connection_fields().get("username") or getpass.getuser()
|
|
120
|
+
|
|
121
|
+
def run(self, command: str, check: bool = True) -> Tuple[int, str, str]:
|
|
122
|
+
"""Run a command on the remote server; callers pre-quote interpolated
|
|
123
|
+
values with shlex.quote before the string reaches this method."""
|
|
124
|
+
self.connect()
|
|
125
|
+
_stdin, stdout, stderr = self._client.exec_command(command)
|
|
126
|
+
out = stdout.read().decode("utf-8", errors="replace")
|
|
127
|
+
err = stderr.read().decode("utf-8", errors="replace")
|
|
128
|
+
code = stdout.channel.recv_exit_status()
|
|
129
|
+
if check and code != 0:
|
|
130
|
+
raise RemoteCommandError(command, code, out, err)
|
|
131
|
+
return code, out, err
|
|
132
|
+
|
|
133
|
+
def mkdir(self, remote_path: str, mode: Optional[int] = None) -> None:
|
|
134
|
+
current = "/" if remote_path.startswith("/") else ""
|
|
135
|
+
for part in remote_path.strip("/").split("/"):
|
|
136
|
+
if not part:
|
|
137
|
+
continue
|
|
138
|
+
current = posixpath.join(current, part)
|
|
139
|
+
try:
|
|
140
|
+
self.sftp.stat(current)
|
|
141
|
+
except OSError:
|
|
142
|
+
self.sftp.mkdir(current)
|
|
143
|
+
if mode is not None:
|
|
144
|
+
self.sftp.chmod(remote_path, mode)
|
|
145
|
+
|
|
146
|
+
def exists(self, remote_path: str) -> bool:
|
|
147
|
+
try:
|
|
148
|
+
self.sftp.stat(remote_path)
|
|
149
|
+
return True
|
|
150
|
+
except OSError:
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
def put_file(self, local_path: Path, remote_path: str, mode: Optional[int] = None) -> None:
|
|
154
|
+
self.mkdir(posixpath.dirname(remote_path))
|
|
155
|
+
self.sftp.put(str(local_path), remote_path)
|
|
156
|
+
if mode is not None:
|
|
157
|
+
self.sftp.chmod(remote_path, mode)
|
|
158
|
+
|
|
159
|
+
def put_bytes(self, data: bytes, remote_path: str, mode: Optional[int] = None) -> None:
|
|
160
|
+
self.mkdir(posixpath.dirname(remote_path))
|
|
161
|
+
with self.sftp.file(remote_path, "wb") as handle:
|
|
162
|
+
handle.write(data)
|
|
163
|
+
if mode is not None:
|
|
164
|
+
self.sftp.chmod(remote_path, mode)
|
|
165
|
+
|
|
166
|
+
def put_json(self, data: Dict[str, Any], remote_path: str, mode: int = 0o600) -> None:
|
|
167
|
+
payload = json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
|
|
168
|
+
self.put_bytes(payload, remote_path, mode=mode)
|
|
169
|
+
|
|
170
|
+
def get_bytes(self, remote_path: str) -> bytes:
|
|
171
|
+
with self.sftp.file(remote_path, "rb") as handle:
|
|
172
|
+
return handle.read()
|
|
173
|
+
|
|
174
|
+
def get_json(self, remote_path: str) -> Dict[str, Any]:
|
|
175
|
+
return json.loads(self.get_bytes(remote_path).decode("utf-8"))
|
|
176
|
+
|
|
177
|
+
def get_file(self, remote_path: str, local_path: Path) -> None:
|
|
178
|
+
local_path.parent.mkdir(parents=True, exist_ok=True)
|
|
179
|
+
self.sftp.get(remote_path, str(local_path))
|