Fix OpenEnv sessions and scoped runtime cleanup (part 2)
Browse files
components/tmax/runtime/native_shell/backend.py
CHANGED
|
@@ -17,7 +17,7 @@ import time
|
|
| 17 |
from uuid import uuid4
|
| 18 |
|
| 19 |
from common.contracts import ACTION_SCHEMA, observation_payload
|
| 20 |
-
from .guard import Guard, GuardError, Policy, ordinary
|
| 21 |
|
| 22 |
_lease = Lock()
|
| 23 |
|
|
@@ -142,8 +142,6 @@ class ShellBackend:
|
|
| 142 |
shutil.copyfile(pristine,target)
|
| 143 |
clear_contents('/logs/verifier')
|
| 144 |
clear_contents(self._private_root()/'episode')
|
| 145 |
-
clear_contents('/tmp')
|
| 146 |
-
os.chown('/tmp',0,0);os.chmod('/tmp',0o1777)
|
| 147 |
os.chown(self.config_path.parent,0,0);os.chmod(self.config_path.parent,0o700)
|
| 148 |
policy=Policy(workspace=work,
|
| 149 |
inputs=tuple(Path(p) for p in task['inputs']),
|
|
@@ -210,7 +208,7 @@ class ShellBackend:
|
|
| 210 |
def _finish_impl(self):
|
| 211 |
try:
|
| 212 |
self.guard.freeze()
|
| 213 |
-
except
|
| 214 |
self.guard.stop_actor()
|
| 215 |
self.final=observation_payload(self.task['id'],'Output violates the published regular-file boundary.',
|
| 216 |
{'status':'invalid_output'},reward=0.0,done=True)
|
|
@@ -218,7 +216,6 @@ class ShellBackend:
|
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
-
clear_contents('/tmp');os.chown('/tmp',0,0);os.chmod('/tmp',0o700)
|
| 222 |
grader=self.task['grader']
|
| 223 |
python=self.task['python']
|
| 224 |
private=self._private_root()/'episode'
|
|
|
|
| 17 |
from uuid import uuid4
|
| 18 |
|
| 19 |
from common.contracts import ACTION_SCHEMA, observation_payload
|
| 20 |
+
from .guard import Guard, GuardError, InvalidOutput, Policy, ordinary
|
| 21 |
|
| 22 |
_lease = Lock()
|
| 23 |
|
|
|
|
| 142 |
shutil.copyfile(pristine,target)
|
| 143 |
clear_contents('/logs/verifier')
|
| 144 |
clear_contents(self._private_root()/'episode')
|
|
|
|
|
|
|
| 145 |
os.chown(self.config_path.parent,0,0);os.chmod(self.config_path.parent,0o700)
|
| 146 |
policy=Policy(workspace=work,
|
| 147 |
inputs=tuple(Path(p) for p in task['inputs']),
|
|
|
|
| 208 |
def _finish_impl(self):
|
| 209 |
try:
|
| 210 |
self.guard.freeze()
|
| 211 |
+
except InvalidOutput:
|
| 212 |
self.guard.stop_actor()
|
| 213 |
self.final=observation_payload(self.task['id'],'Output violates the published regular-file boundary.',
|
| 214 |
{'status':'invalid_output'},reward=0.0,done=True)
|
|
|
|
| 216 |
|
| 217 |
|
| 218 |
|
|
|
|
| 219 |
grader=self.task['grader']
|
| 220 |
python=self.task['python']
|
| 221 |
private=self._private_root()/'episode'
|
components/tmax/runtime/native_shell/guard.py
CHANGED
|
@@ -16,10 +16,20 @@ import sys
|
|
| 16 |
import time
|
| 17 |
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
class GuardError(RuntimeError):
|
| 20 |
pass
|
| 21 |
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def ordinary(path):
|
| 24 |
path = Path(path)
|
| 25 |
for current in [path, *path.parents]:
|
|
@@ -84,6 +94,7 @@ class Guard:
|
|
| 84 |
if sys.platform != "linux" or os.geteuid() != 0:
|
| 85 |
raise GuardError("Guard requires a dedicated Linux root supervisor")
|
| 86 |
self.policy = policy
|
|
|
|
| 87 |
self.records = {}
|
| 88 |
self.closed_trees = {}
|
| 89 |
self.phase = "new"
|
|
@@ -104,7 +115,8 @@ class Guard:
|
|
| 104 |
|
| 105 |
for parent in [Path(path).parent, *Path(path).parent.parents]:
|
| 106 |
st = ordinary(parent)
|
| 107 |
-
|
|
|
|
| 108 |
mode = stat.S_IMODE(st.st_mode)
|
| 109 |
if mode & 0o022:
|
| 110 |
os.chmod(parent, mode | stat.S_ISVTX)
|
|
@@ -181,29 +193,7 @@ class Guard:
|
|
| 181 |
raise GuardError(f"Protected directory membership changed: {root}")
|
| 182 |
|
| 183 |
def stop_actor(self):
|
| 184 |
-
|
| 185 |
-
deadline = time.monotonic() + 3
|
| 186 |
-
while True:
|
| 187 |
-
live = []
|
| 188 |
-
for entry in Path("/proc").iterdir():
|
| 189 |
-
if not entry.name.isdigit():
|
| 190 |
-
continue
|
| 191 |
-
try:
|
| 192 |
-
fields = dict(line.split(":", 1) for line in (entry / "status").read_text().splitlines() if ":" in line)
|
| 193 |
-
if self.policy.uid in map(int, fields["Uid"].split()) and not fields["State"].strip().startswith("Z"):
|
| 194 |
-
live.append(int(entry.name))
|
| 195 |
-
except (FileNotFoundError, ProcessLookupError, PermissionError):
|
| 196 |
-
continue
|
| 197 |
-
if not live:
|
| 198 |
-
return
|
| 199 |
-
for pid in live:
|
| 200 |
-
try:
|
| 201 |
-
os.kill(pid, signal.SIGKILL)
|
| 202 |
-
except ProcessLookupError:
|
| 203 |
-
pass
|
| 204 |
-
if time.monotonic() > deadline:
|
| 205 |
-
raise GuardError("Could not stop all actor processes")
|
| 206 |
-
time.sleep(0.02)
|
| 207 |
|
| 208 |
def run_actor(self, command, timeout=10, output_limit=65536):
|
| 209 |
if self.phase != "actor":
|
|
@@ -219,6 +209,7 @@ class Guard:
|
|
| 219 |
process = subprocess.Popen(argv, env={"PATH": "/usr/local/bin:/usr/bin:/bin"},
|
| 220 |
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
| 221 |
pass_fds=(write_fd,), start_new_session=True)
|
|
|
|
| 222 |
os.close(write_fd)
|
| 223 |
selector = selectors.DefaultSelector()
|
| 224 |
for stream in [process.stdout, process.stderr]:
|
|
@@ -229,16 +220,7 @@ class Guard:
|
|
| 229 |
deadline = time.monotonic() + timeout
|
| 230 |
try:
|
| 231 |
while selector.get_map():
|
| 232 |
-
rss_kib =
|
| 233 |
-
for entry in Path('/proc').iterdir():
|
| 234 |
-
if not entry.name.isdigit():
|
| 235 |
-
continue
|
| 236 |
-
try:
|
| 237 |
-
fields = dict(line.split(':',1) for line in (entry/'status').read_text().splitlines() if ':' in line)
|
| 238 |
-
if self.policy.uid in map(int,fields['Uid'].split()):
|
| 239 |
-
rss_kib += int(fields.get('VmRSS','0').split()[0])
|
| 240 |
-
except (FileNotFoundError,ProcessLookupError,PermissionError):
|
| 241 |
-
continue
|
| 242 |
if rss_kib > self.policy.memory_mb * 1024:
|
| 243 |
reason = 'aggregate_rss_limit'
|
| 244 |
self.stop_actor()
|
|
@@ -276,6 +258,8 @@ class Guard:
|
|
| 276 |
self.stop_actor()
|
| 277 |
process.kill()
|
| 278 |
process.wait()
|
|
|
|
|
|
|
| 279 |
self.check_integrity()
|
| 280 |
return {"return_code": process.returncode, "reason": reason,
|
| 281 |
"stdout": output[process.stdout].decode(errors="replace"),
|
|
@@ -286,20 +270,23 @@ class Guard:
|
|
| 286 |
raise GuardError("Can only freeze an active actor phase")
|
| 287 |
self.stop_actor()
|
| 288 |
self.check_integrity()
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
| 303 |
self.phase = "frozen"
|
| 304 |
|
| 305 |
def run_verifier(self, script, timeout=30):
|
|
|
|
| 16 |
import time
|
| 17 |
|
| 18 |
|
| 19 |
+
try:
|
| 20 |
+
from .process_scope import current_scope
|
| 21 |
+
except ImportError:
|
| 22 |
+
from process_scope import current_scope
|
| 23 |
+
|
| 24 |
+
|
| 25 |
class GuardError(RuntimeError):
|
| 26 |
pass
|
| 27 |
|
| 28 |
|
| 29 |
+
class InvalidOutput(GuardError):
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
|
| 33 |
def ordinary(path):
|
| 34 |
path = Path(path)
|
| 35 |
for current in [path, *path.parents]:
|
|
|
|
| 94 |
if sys.platform != "linux" or os.geteuid() != 0:
|
| 95 |
raise GuardError("Guard requires a dedicated Linux root supervisor")
|
| 96 |
self.policy = policy
|
| 97 |
+
self.scope = current_scope()
|
| 98 |
self.records = {}
|
| 99 |
self.closed_trees = {}
|
| 100 |
self.phase = "new"
|
|
|
|
| 115 |
|
| 116 |
for parent in [Path(path).parent, *Path(path).parent.parents]:
|
| 117 |
st = ordinary(parent)
|
| 118 |
+
if st.st_uid != 0 or st.st_gid != 0:
|
| 119 |
+
os.chown(parent, 0, 0)
|
| 120 |
mode = stat.S_IMODE(st.st_mode)
|
| 121 |
if mode & 0o022:
|
| 122 |
os.chmod(parent, mode | stat.S_ISVTX)
|
|
|
|
| 193 |
raise GuardError(f"Protected directory membership changed: {root}")
|
| 194 |
|
| 195 |
def stop_actor(self):
|
| 196 |
+
return self.scope.stop_uid(self.policy.uid)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
def run_actor(self, command, timeout=10, output_limit=65536):
|
| 199 |
if self.phase != "actor":
|
|
|
|
| 209 |
process = subprocess.Popen(argv, env={"PATH": "/usr/local/bin:/usr/bin:/bin"},
|
| 210 |
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
| 211 |
pass_fds=(write_fd,), start_new_session=True)
|
| 212 |
+
identity = self.scope.track_child(process.pid)
|
| 213 |
os.close(write_fd)
|
| 214 |
selector = selectors.DefaultSelector()
|
| 215 |
for stream in [process.stdout, process.stderr]:
|
|
|
|
| 220 |
deadline = time.monotonic() + timeout
|
| 221 |
try:
|
| 222 |
while selector.get_map():
|
| 223 |
+
rss_kib = self.scope.rss_kib(self.policy.uid)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
if rss_kib > self.policy.memory_mb * 1024:
|
| 225 |
reason = 'aggregate_rss_limit'
|
| 226 |
self.stop_actor()
|
|
|
|
| 258 |
self.stop_actor()
|
| 259 |
process.kill()
|
| 260 |
process.wait()
|
| 261 |
+
self.scope.untrack_child(identity)
|
| 262 |
+
self.scope.reap_uid(self.policy.uid)
|
| 263 |
self.check_integrity()
|
| 264 |
return {"return_code": process.returncode, "reason": reason,
|
| 265 |
"stdout": output[process.stdout].decode(errors="replace"),
|
|
|
|
| 270 |
raise GuardError("Can only freeze an active actor phase")
|
| 271 |
self.stop_actor()
|
| 272 |
self.check_integrity()
|
| 273 |
+
try:
|
| 274 |
+
total = 0
|
| 275 |
+
for path in self.policy.output_paths:
|
| 276 |
+
if not path.is_relative_to(self.policy.workspace):
|
| 277 |
+
raise GuardError("Output path is outside workspace")
|
| 278 |
+
if not os.path.lexists(path):
|
| 279 |
+
continue
|
| 280 |
+
for item in descendants(path):
|
| 281 |
+
st = ordinary(item)
|
| 282 |
+
if stat.S_ISREG(st.st_mode):
|
| 283 |
+
total += st.st_size
|
| 284 |
+
if st.st_size > 16 * 1024 * 1024 or total > 64 * 1024 * 1024:
|
| 285 |
+
raise GuardError("Output artifact exceeds prototype limits")
|
| 286 |
+
os.chown(item, 0, 0)
|
| 287 |
+
os.chmod(item, 0o555 if stat.S_ISDIR(st.st_mode) else 0o444)
|
| 288 |
+
except GuardError as exc:
|
| 289 |
+
raise InvalidOutput(str(exc)) from exc
|
| 290 |
self.phase = "frozen"
|
| 291 |
|
| 292 |
def run_verifier(self, script, timeout=30):
|
components/tmax/runtime/native_shell/process_scope.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ctypes
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
import errno
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import signal
|
| 7 |
+
import sys
|
| 8 |
+
import threading
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ProcessScopeError(RuntimeError):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@dataclass(frozen=True)
|
| 17 |
+
class ProcessIdentity:
|
| 18 |
+
pid: int
|
| 19 |
+
start_ticks: int
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class ProcessRecord:
|
| 24 |
+
identity: ProcessIdentity
|
| 25 |
+
ppid: int
|
| 26 |
+
state: str
|
| 27 |
+
uids: tuple[int, ...]
|
| 28 |
+
rss_kib: int
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _read_record(pid):
|
| 32 |
+
path = Path('/proc') / str(pid)
|
| 33 |
+
raw = (path / 'stat').read_text()
|
| 34 |
+
fields = raw[raw.rfind(')') + 2:].split()
|
| 35 |
+
if len(fields) < 22:
|
| 36 |
+
raise ProcessScopeError('Incomplete process stat')
|
| 37 |
+
status = {}
|
| 38 |
+
for line in (path / 'status').read_text().splitlines():
|
| 39 |
+
if ':' in line:
|
| 40 |
+
key, value = line.split(':', 1)
|
| 41 |
+
status[key] = value
|
| 42 |
+
uids = tuple(map(int, status['Uid'].split()))
|
| 43 |
+
if len(uids) != 4:
|
| 44 |
+
raise ProcessScopeError('Incomplete process identity')
|
| 45 |
+
record = ProcessRecord(
|
| 46 |
+
ProcessIdentity(pid, int(fields[19])), int(fields[1]), fields[0],
|
| 47 |
+
uids, int(status.get('VmRSS', '0 kB').split()[0]),
|
| 48 |
+
)
|
| 49 |
+
raw_after = (path / 'stat').read_text()
|
| 50 |
+
fields_after = raw_after[raw_after.rfind(')') + 2:].split()
|
| 51 |
+
if int(fields_after[19]) != record.identity.start_ticks:
|
| 52 |
+
raise ProcessLookupError(pid)
|
| 53 |
+
return record
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _read_if_present(pid):
|
| 57 |
+
try:
|
| 58 |
+
return _read_record(pid)
|
| 59 |
+
except (FileNotFoundError, ProcessLookupError):
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _enable_subreaper():
|
| 64 |
+
if sys.platform != 'linux':
|
| 65 |
+
raise ProcessScopeError('Process scoping requires Linux')
|
| 66 |
+
if not hasattr(os, 'pidfd_open') or not hasattr(signal, 'pidfd_send_signal'):
|
| 67 |
+
raise ProcessScopeError('Process scoping requires pidfd signal support')
|
| 68 |
+
if not hasattr(os, 'P_PIDFD'):
|
| 69 |
+
raise ProcessScopeError('Process scoping requires pidfd wait support')
|
| 70 |
+
libc = ctypes.CDLL(None, use_errno=True)
|
| 71 |
+
if libc.prctl(36, 1, 0, 0, 0):
|
| 72 |
+
raise ProcessScopeError('Could not enable child subreaper: ' + str(ctypes.get_errno()))
|
| 73 |
+
value = ctypes.c_int()
|
| 74 |
+
if libc.prctl(37, ctypes.byref(value), 0, 0, 0) or value.value != 1:
|
| 75 |
+
raise ProcessScopeError('Child subreaper verification failed')
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class ProcessScope:
|
| 79 |
+
def __init__(self):
|
| 80 |
+
_enable_subreaper()
|
| 81 |
+
self.owner = _read_record(os.getpid()).identity
|
| 82 |
+
self._tracked = set()
|
| 83 |
+
self._lock = threading.RLock()
|
| 84 |
+
|
| 85 |
+
def _check_owner(self):
|
| 86 |
+
if os.getpid() != self.owner.pid or _read_record(os.getpid()).identity != self.owner:
|
| 87 |
+
raise ProcessScopeError('Process scope used by a different supervisor')
|
| 88 |
+
|
| 89 |
+
def track_child(self, pid):
|
| 90 |
+
self._check_owner()
|
| 91 |
+
record = _read_if_present(pid)
|
| 92 |
+
if record is None or not self._is_descendant(record):
|
| 93 |
+
raise ProcessScopeError('Cannot track a process outside this supervisor')
|
| 94 |
+
with self._lock:
|
| 95 |
+
self._tracked.add(record.identity)
|
| 96 |
+
return record.identity
|
| 97 |
+
|
| 98 |
+
def untrack_child(self, identity):
|
| 99 |
+
self._check_owner()
|
| 100 |
+
with self._lock:
|
| 101 |
+
self._tracked.discard(identity)
|
| 102 |
+
|
| 103 |
+
def _is_descendant(self, candidate):
|
| 104 |
+
if candidate.identity == self.owner:
|
| 105 |
+
return False
|
| 106 |
+
visited = set()
|
| 107 |
+
current = candidate
|
| 108 |
+
while current.ppid != self.owner.pid:
|
| 109 |
+
if current.ppid <= 1 or current.ppid in visited:
|
| 110 |
+
return False
|
| 111 |
+
visited.add(current.ppid)
|
| 112 |
+
parent = _read_if_present(current.ppid)
|
| 113 |
+
if parent is None:
|
| 114 |
+
return False
|
| 115 |
+
after = _read_if_present(current.identity.pid)
|
| 116 |
+
if after is None or after.identity != current.identity or after.ppid != parent.identity.pid:
|
| 117 |
+
return False
|
| 118 |
+
current = parent
|
| 119 |
+
owner = _read_if_present(self.owner.pid)
|
| 120 |
+
if owner is None or owner.identity != self.owner:
|
| 121 |
+
raise ProcessScopeError('Supervisor identity changed')
|
| 122 |
+
after = _read_if_present(current.identity.pid)
|
| 123 |
+
return after is not None and after.identity == current.identity and after.ppid == self.owner.pid
|
| 124 |
+
|
| 125 |
+
def records(self, uid, include_zombies=False):
|
| 126 |
+
self._check_owner()
|
| 127 |
+
if not isinstance(uid, int) or uid <= 0:
|
| 128 |
+
raise ProcessScopeError('Only non-root learner UIDs can be targeted')
|
| 129 |
+
records = []
|
| 130 |
+
for entry in Path('/proc').iterdir():
|
| 131 |
+
if not entry.name.isdigit():
|
| 132 |
+
continue
|
| 133 |
+
record = _read_if_present(int(entry.name))
|
| 134 |
+
if record is None or uid not in record.uids:
|
| 135 |
+
continue
|
| 136 |
+
if not include_zombies and record.state == 'Z':
|
| 137 |
+
continue
|
| 138 |
+
if self._is_descendant(record):
|
| 139 |
+
records.append(record)
|
| 140 |
+
return records
|
| 141 |
+
|
| 142 |
+
def rss_kib(self, uid):
|
| 143 |
+
return sum(record.rss_kib for record in self.records(uid))
|
| 144 |
+
|
| 145 |
+
def _open_checked_pidfd(self, record, uid):
|
| 146 |
+
current = _read_if_present(record.identity.pid)
|
| 147 |
+
if current is None or current.identity != record.identity or uid not in current.uids:
|
| 148 |
+
return None
|
| 149 |
+
if not self._is_descendant(current):
|
| 150 |
+
return None
|
| 151 |
+
try:
|
| 152 |
+
fd = os.pidfd_open(record.identity.pid, 0)
|
| 153 |
+
except ProcessLookupError:
|
| 154 |
+
return None
|
| 155 |
+
except OSError as error:
|
| 156 |
+
raise ProcessScopeError('Could not open a safe process handle') from error
|
| 157 |
+
try:
|
| 158 |
+
after = _read_if_present(record.identity.pid)
|
| 159 |
+
if after is None or after.identity != record.identity or uid not in after.uids:
|
| 160 |
+
os.close(fd)
|
| 161 |
+
return None
|
| 162 |
+
if not self._is_descendant(after):
|
| 163 |
+
os.close(fd)
|
| 164 |
+
return None
|
| 165 |
+
except BaseException:
|
| 166 |
+
os.close(fd)
|
| 167 |
+
raise
|
| 168 |
+
return fd
|
| 169 |
+
|
| 170 |
+
def reap_uid(self, uid):
|
| 171 |
+
reaped = 0
|
| 172 |
+
for record in self.records(uid, include_zombies=True):
|
| 173 |
+
with self._lock:
|
| 174 |
+
tracked = record.identity in self._tracked
|
| 175 |
+
if record.state != 'Z' or record.ppid != self.owner.pid or tracked:
|
| 176 |
+
continue
|
| 177 |
+
fd = self._open_checked_pidfd(record, uid)
|
| 178 |
+
if fd is None:
|
| 179 |
+
continue
|
| 180 |
+
try:
|
| 181 |
+
try:
|
| 182 |
+
result = os.waitid(os.P_PIDFD, fd, os.WEXITED | os.WNOHANG)
|
| 183 |
+
reaped += int(result is not None)
|
| 184 |
+
except ChildProcessError:
|
| 185 |
+
pass
|
| 186 |
+
finally:
|
| 187 |
+
os.close(fd)
|
| 188 |
+
return reaped
|
| 189 |
+
|
| 190 |
+
def stop_uid(self, uid, timeout=3.0):
|
| 191 |
+
if timeout <= 0:
|
| 192 |
+
raise ValueError('A positive cleanup timeout is required')
|
| 193 |
+
deadline = time.monotonic() + timeout
|
| 194 |
+
quiet = 0
|
| 195 |
+
signaled = set()
|
| 196 |
+
reaped = 0
|
| 197 |
+
while True:
|
| 198 |
+
live = self.records(uid)
|
| 199 |
+
if not live:
|
| 200 |
+
reaped += self.reap_uid(uid)
|
| 201 |
+
quiet += 1
|
| 202 |
+
if quiet >= 2:
|
| 203 |
+
return {'signaled': len(signaled), 'reaped': reaped}
|
| 204 |
+
else:
|
| 205 |
+
quiet = 0
|
| 206 |
+
for record in live:
|
| 207 |
+
fd = self._open_checked_pidfd(record, uid)
|
| 208 |
+
if fd is None:
|
| 209 |
+
continue
|
| 210 |
+
try:
|
| 211 |
+
try:
|
| 212 |
+
signal.pidfd_send_signal(fd, signal.SIGKILL, None, 0)
|
| 213 |
+
signaled.add(record.identity)
|
| 214 |
+
except ProcessLookupError:
|
| 215 |
+
pass
|
| 216 |
+
except OSError as error:
|
| 217 |
+
raise ProcessScopeError('Could not stop a learner process') from error
|
| 218 |
+
finally:
|
| 219 |
+
os.close(fd)
|
| 220 |
+
reaped += self.reap_uid(uid)
|
| 221 |
+
if time.monotonic() >= deadline:
|
| 222 |
+
raise ProcessScopeError('Could not stop all scoped learner processes')
|
| 223 |
+
time.sleep(0.02)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
_current_scope = None
|
| 227 |
+
_current_lock = threading.Lock()
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def current_scope():
|
| 231 |
+
global _current_scope
|
| 232 |
+
with _current_lock:
|
| 233 |
+
if _current_scope is None or _current_scope.owner.pid != os.getpid():
|
| 234 |
+
_current_scope = ProcessScope()
|
| 235 |
+
return _current_scope
|
components/tmax/runtime/native_shell/server.py
CHANGED
|
@@ -1,13 +1,9 @@
|
|
| 1 |
|
| 2 |
from openenv.core.env_server.http_server import create_app
|
| 3 |
from common.models import ArenaAction, ArenaObservation
|
| 4 |
-
from common.http_routes import install_persistent_http_routes
|
| 5 |
from .environment import NativeHarborEnvironment
|
| 6 |
-
from .backend import RuntimeUnavailable
|
| 7 |
|
| 8 |
app=create_app(NativeHarborEnvironment,ArenaAction,ArenaObservation,env_name='native_harbor',max_concurrent_envs=1)
|
| 9 |
-
http_env=NativeHarborEnvironment()
|
| 10 |
-
http_lock=install_persistent_http_routes(app,http_env,conflict_error=RuntimeUnavailable)
|
| 11 |
|
| 12 |
|
| 13 |
def main():
|
|
|
|
| 1 |
|
| 2 |
from openenv.core.env_server.http_server import create_app
|
| 3 |
from common.models import ArenaAction, ArenaObservation
|
|
|
|
| 4 |
from .environment import NativeHarborEnvironment
|
|
|
|
| 5 |
|
| 6 |
app=create_app(NativeHarborEnvironment,ArenaAction,ArenaObservation,env_name='native_harbor',max_concurrent_envs=1)
|
|
|
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
def main():
|
components/tmax/runtime/native_shell/wire_client.py
CHANGED
|
@@ -71,48 +71,75 @@ class WireClient:
|
|
| 71 |
raise PermissionError('Wire client is reserved for the trusted supervisor')
|
| 72 |
url=urllib.parse.urlsplit(base_url)
|
| 73 |
if url.scheme!='http' or url.hostname not in ('127.0.0.1','localhost','::1') or url.username or url.password or url.query or url.fragment or url.path not in ('','/'):
|
| 74 |
-
raise ValueError('Only an unauthenticated local
|
| 75 |
-
self.
|
| 76 |
self.timeout=timeout
|
| 77 |
-
self.
|
| 78 |
-
|
| 79 |
-
def
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def reset(self,**kwargs):
|
| 92 |
-
return self.
|
| 93 |
|
| 94 |
def step(self,action):
|
| 95 |
-
return self.
|
| 96 |
|
| 97 |
def finish(self):
|
| 98 |
return validate_envelope(self.step({'op':'finish'}),require_done=True)
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
def main():
|
| 102 |
parser=argparse.ArgumentParser()
|
| 103 |
-
parser.add_argument('operation',choices=['
|
| 104 |
-
parser.add_argument('--payload-base64')
|
| 105 |
parser.add_argument('--url',default='http://127.0.0.1:8000')
|
| 106 |
parser.add_argument('--timeout',type=float,default=330)
|
| 107 |
args=parser.parse_args()
|
| 108 |
-
payload=
|
| 109 |
-
if not isinstance(payload,dict)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
| 116 |
print(json.dumps(result,ensure_ascii=False,allow_nan=False,separators=(',',':')))
|
| 117 |
|
| 118 |
|
|
|
|
| 71 |
raise PermissionError('Wire client is reserved for the trusted supervisor')
|
| 72 |
url=urllib.parse.urlsplit(base_url)
|
| 73 |
if url.scheme!='http' or url.hostname not in ('127.0.0.1','localhost','::1') or url.username or url.password or url.query or url.fragment or url.path not in ('','/'):
|
| 74 |
+
raise ValueError('Only an unauthenticated local server is allowed')
|
| 75 |
+
self.ws_url='ws://'+url.netloc+'/ws'
|
| 76 |
self.timeout=timeout
|
| 77 |
+
self.connection=None
|
| 78 |
+
|
| 79 |
+
def close(self):
|
| 80 |
+
if self.connection is not None:
|
| 81 |
+
from websockets.exceptions import ConnectionClosedOK
|
| 82 |
+
connection,self.connection=self.connection,None
|
| 83 |
+
try:
|
| 84 |
+
connection.send('{"type":"close"}')
|
| 85 |
+
connection.recv(timeout=min(self.timeout,10))
|
| 86 |
+
raise WireProtocolError('OpenEnv session did not close')
|
| 87 |
+
except ConnectionClosedOK:
|
| 88 |
+
pass
|
| 89 |
+
finally:
|
| 90 |
+
connection.close()
|
| 91 |
+
|
| 92 |
+
def _request(self,kind,payload):
|
| 93 |
+
from websockets.sync.client import connect
|
| 94 |
+
if self.connection is None:
|
| 95 |
+
if kind!='reset':raise WireProtocolError('Reset before stepping')
|
| 96 |
+
self.connection=connect(self.ws_url,proxy=None,open_timeout=min(self.timeout,30),max_size=2*1024*1024)
|
| 97 |
+
body=json.dumps({'type':kind,'data':payload},ensure_ascii=False,allow_nan=False,separators=(',',':'))
|
| 98 |
try:
|
| 99 |
+
self.connection.send(body)
|
| 100 |
+
response=loads(self.connection.recv(timeout=self.timeout))
|
| 101 |
+
if response.get('type')!='observation':
|
| 102 |
+
raise WireProtocolError('OpenEnv error: '+json.dumps(response.get('data',{}),ensure_ascii=False))
|
| 103 |
+
result=validate_envelope(response['data'])
|
| 104 |
+
return result
|
| 105 |
+
except BaseException:
|
| 106 |
+
self.close()
|
| 107 |
+
raise
|
| 108 |
|
| 109 |
def reset(self,**kwargs):
|
| 110 |
+
return self._request('reset',kwargs)
|
| 111 |
|
| 112 |
def step(self,action):
|
| 113 |
+
return self._request('step',action)
|
| 114 |
|
| 115 |
def finish(self):
|
| 116 |
return validate_envelope(self.step({'op':'finish'}),require_done=True)
|
| 117 |
|
| 118 |
+
def __enter__(self):
|
| 119 |
+
return self
|
| 120 |
+
|
| 121 |
+
def __exit__(self,*args):
|
| 122 |
+
self.close()
|
| 123 |
+
|
| 124 |
|
| 125 |
def main():
|
| 126 |
parser=argparse.ArgumentParser()
|
| 127 |
+
parser.add_argument('operation',choices=['episode'])
|
| 128 |
+
parser.add_argument('--payload-base64',required=True)
|
| 129 |
parser.add_argument('--url',default='http://127.0.0.1:8000')
|
| 130 |
parser.add_argument('--timeout',type=float,default=330)
|
| 131 |
args=parser.parse_args()
|
| 132 |
+
payload=loads(base64.b64decode(args.payload_base64,validate=True))
|
| 133 |
+
if not isinstance(payload,dict) or set(payload)-{'reset','actions'}:
|
| 134 |
+
raise WireProtocolError('Expected reset and actions')
|
| 135 |
+
actions=payload.get('actions',[])
|
| 136 |
+
if not isinstance(actions,list):raise WireProtocolError('Actions must be a list')
|
| 137 |
+
with WireClient(args.url,args.timeout) as client:
|
| 138 |
+
result=client.reset(**payload.get('reset',{}))
|
| 139 |
+
for action in actions:
|
| 140 |
+
if result['done']:break
|
| 141 |
+
result=client.step(action)
|
| 142 |
+
if not result['done']:result=client.finish()
|
| 143 |
print(json.dumps(result,ensure_ascii=False,allow_nan=False,separators=(',',':')))
|
| 144 |
|
| 145 |
|