Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: jiuwenbox bg-exec and exec process use the same pidns

zhaozixuan0b4039a23366
diff --git a/jiuwenbox/docs/jiuwenbox_server_api.md b/jiuwenbox/docs/jiuwenbox_server_api.md
index 257d8490de..b26138e98a 100644
--- a/jiuwenbox/docs/jiuwenbox_server_api.md
+++ b/jiuwenbox/docs/jiuwenbox_server_api.md
@@ -512,9 +512,11 @@ print(resp.json())
接口:`POST /api/v1/sandboxes/{sandbox_id}/exec_background`
-用途:在沙箱内启动后台进程,进程创建后立即返回。`Popen` 成功即 `started=true`;**不**区分长任务与瞬时任务。
+用途:在沙箱内启动后台进程,进程创建后立即返回。与 ``exec`` 相同,命令由沙箱 daemon 在**同一 PID 命名空间**内 ``fork+exec``,不再为每次后台任务单独 spawn bubblewrap。
-`running`、`exit_code` 为**返回时刻的快照**:服务端在 spawn 后对跟踪的 bwrap 监控进程调用一次 `poll()`。命令本身可能很快结束,但 bwrap 清理/回收可能尚未完成,因此 `python3 --version` 这类瞬时命令在 `exec_background` 响应里 **`running` 仍常为 `true`**。要可靠判断结束并读取输出,请轮询 `GET .../background/{job_id}`。
+`running`、`exit_code` 为**返回时刻的快照**(daemon 在 spawn 后立即响应)。瞬时命令可能在 `exec_background` 响应里已显示 `running=false`;长任务则 `running=true`。要可靠判断结束并读取输出,请轮询 `GET .../background/{job_id}`。
+
+`pid` 为**沙箱 PID 命名空间内**的用户进程 pid(与 ``sandbox exec ps`` 中看到的 pid 一致),不是 host 上的 bwrap 监控进程 pid。
请求体(`BackgroundExecRequest`):
@@ -526,7 +528,7 @@ print(resp.json())
| `env` | object | 否 | 额外环境变量 |
| `stdin` | string | 否 | 标准输入文本 |
| `timeout_seconds` | int | 否 | 预留字段 |
-| `capture_output` | bool | 否 | 默认 `true`;为 `true` 时将 stdout/stderr 写入 host `{control_dir}/bg-logs/{job_id}.out\|.err` |
+| `capture_output` | bool | 否 | 默认 `true`;为 `true` 时将 stdout/stderr 写入沙箱内 `/tmp/.jiuwenbox-bg/{job_id}.out\|.err`,由 daemon 在 `bg-get` 时经 IPC 读回 |
错误码:`job_id` 格式非法 → **400**;同 sandbox 内 `job_id` 已占用 → **409**;沙箱非 ready → **409**。
diff --git a/jiuwenbox/src/jiuwenbox/server/runtime/process.py b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
index d3c4fcd5c6..f0bfc6efbc 100644
--- a/jiuwenbox/src/jiuwenbox/server/runtime/process.py
+++ b/jiuwenbox/src/jiuwenbox/server/runtime/process.py
@@ -1,13 +1,10 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
"""Process-based runtime adapter (bare-metal mode).
-Spawns bubblewrap directly for each sandbox lifecycle process and for each
-``exec`` request. Setup runs in-process and reuses the expensive artifacts
-(seccomp BPF program, encoded Landlock payload, copies of the in-sandbox
-launcher scripts) for the lifetime of the sandbox: bubblewrap still applies
-all namespace/mount/seccomp/Landlock isolation, the sandbox still runs
-through the dedicated launcher script, and the seccomp memfd still flows
-through ``pass_fds`` so it cannot be observed by sandboxed code.
+Spawns bubblewrap once per sandbox lifecycle to start the in-sandbox daemon.
+All ``exec`` and ``exec_background`` requests are served via daemon IPC so
+user commands inherit the same namespace/mount/seccomp/Landlock envelope
+without spawning bwrap per call.
"""
from __future__ import annotations
@@ -27,6 +24,7 @@ import socket
import subprocess
import sys
import tempfile
+import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
@@ -57,7 +55,10 @@ from jiuwenbox.supervisor.daemon_ipc import (
LISTENER_FD_ENV,
MAX_FILE_BYTES,
MAX_HEADER_BYTES,
+ REQUEST_TYPE_BG_KILL,
+ REQUEST_TYPE_BG_STATUS,
REQUEST_TYPE_EXEC,
+ REQUEST_TYPE_EXEC_BACKGROUND,
REQUEST_TYPE_LIST_DIR,
REQUEST_TYPE_READ_FILE,
REQUEST_TYPE_SHUTDOWN,
@@ -245,6 +246,36 @@ class _DaemonListDirCall:
include_dirs: bool
[email protected](frozen=True)
+class _DaemonBgExecCall:
+ """Inputs to one IPC ``exec_background`` request."""
+
+ socket_path: Path
+ job_id: str
+ command: list[str]
+ env: dict[str, str] | None
+ workdir: str | None
+ stdin_bytes: bytes | None
+ capture_output: bool
+
+
[email protected](frozen=True)
+class _DaemonBgStatusCall:
+ """Inputs to one IPC ``bg_status`` request."""
+
+ socket_path: Path
+ job_id: str
+
+
[email protected](frozen=True)
+class _DaemonBgKillCall:
+ """Inputs to one IPC ``bg_kill`` request."""
+
+ socket_path: Path
+ job_id: str
+ signum: int
+
+
# Admission control for ``exec``. ``exec`` is the one operation that
# spawns a fresh ``python3`` (or other) child inside the sandbox, which
# is overwhelmingly CPU-bound (interpreter cold start + imports + user
@@ -267,23 +298,15 @@ EXEC_CONCURRENCY_ENV = "JIUWENBOX_EXEC_CONCURRENCY"
# ---------------------------------------------------------------------------
# Zombie reaper plumbing.
#
-# Background: each ``bwrap`` invocation (sandbox daemon spawn, or
-# ``exec_background``) creates the bwrap monitor process as a direct child of
-# box-server. With ``--unshare-user`` (default in jiuwenbox) bwrap additionally
-# clones a userns helper via ``CLONE_PARENT`` so the helper's parent is *also*
-# box-server, not bwrap. When that helper finishes its short setup and exits,
-# it becomes a zombie of box-server until somebody calls ``waitpid`` on it.
-# Without proactive reaping the host process table fills up with
-# ``[bwrap] <defunct>`` entries (visible as a child of the box-server pid).
+# Background: each sandbox lifecycle spawns one bwrap monitor process as a
+# direct child of box-server. With ``--unshare-user`` (default in jiuwenbox)
+# bwrap additionally clones a userns helper via ``CLONE_PARENT`` so the
+# helper's parent is *also* box-server, not bwrap. When that helper finishes
+# its short setup and exits, it becomes a zombie of box-server until somebody
+# calls ``waitpid`` on it.
#
-# The historical code only reaped lazily:
-# - daemon bwrap monitor: ``Popen.poll()`` is called from ``stop()``/
-# ``cleanup()``/``is_running()``; if the user never invokes any of these
-# the monitor's eventual exit lingers indefinitely.
-# - background bwrap: ``_reap_background_processes`` runs at the start of the
-# *next* ``exec_background`` call; a workload that does one background exec
-# and then nothing else leaks a zombie until shutdown.
-# - userns helper / other bwrap-internal forks: never tracked, never reaped.
+# Background jobs no longer spawn per-command bwrap processes; they are forked
+# inside the sandbox daemon's PID namespace via daemon IPC.
#
# The fix is three-pronged:
# - ``prctl(PR_SET_CHILD_SUBREAPER, 1)`` so even when box-server isn't PID 1
@@ -316,15 +339,14 @@ class BackgroundJob:
job_id: str
sandbox_id: str
command: list[str]
- pid: int
- proc: subprocess.Popen
+ pid: int | None
capture_output: bool
- stdout_path: Path | None
- stderr_path: Path | None
workdir: str | None
started_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
finished_at: datetime | None = None
exit_code: int | None = None
+ stdout: str = ""
+ stderr: str = ""
class BackgroundJobNotFoundError(Exception):
@@ -648,55 +670,76 @@ class ProcessRuntime(RuntimeAdapter):
self._control_dirs[sandbox_id] = control_dir
return control_dir
- def _ensure_bg_logs_dir(self, sandbox_id: str) -> Path:
- control_dir = self._ensure_control_dir(sandbox_id)
- logs_dir = control_dir / "bg-logs"
- logs_dir.mkdir(parents=True, exist_ok=True)
- return logs_dir
-
def _background_jobs_for_sandbox(self, sandbox_id: str) -> dict[str, BackgroundJob]:
return self._background_processes.setdefault(sandbox_id, {})
- @staticmethod
- def _sync_background_job(job: BackgroundJob) -> None:
- if job.exit_code is not None:
+ def _apply_bg_status_response(
+ self,
+ job: BackgroundJob,
+ response: dict[str, Any],
+ ) -> None:
+ if not response.get("ok"):
return
- returncode = job.proc.poll()
- if returncode is None:
+ pid = response.get("pid")
+ if isinstance(pid, int):
+ job.pid = pid
+ running = response.get("running")
+ if not isinstance(running, bool):
return
- job.exit_code = returncode
- job.finished_at = datetime.now(timezone.utc)
+ if job.capture_output:
+ job.stdout = str(response.get("stdout", ""))
+ job.stderr = str(response.get("stderr", ""))
+ if running:
+ job.exit_code = None
+ job.finished_at = None
+ return
+ exit_code = response.get("exit_code")
+ if exit_code is None or isinstance(exit_code, int):
+ job.exit_code = exit_code
+ if job.finished_at is None:
+ job.finished_at = datetime.now(timezone.utc)
- @staticmethod
- def _read_job_stream(path: Path | None) -> str:
- if path is None or not path.exists():
- return ""
- return path.read_text(encoding="utf-8", errors="replace")
+ def _sync_background_job_blocking(
+ self,
+ sandbox_id: str,
+ job: BackgroundJob,
+ ) -> None:
+ socket_path = self._control_socket_host_path(sandbox_id)
+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):
+ return
+ try:
+ response = self._bg_status_via_daemon_blocking(
+ _DaemonBgStatusCall(socket_path=socket_path, job_id=job.job_id),
+ )
+ except (OSError, ValueError):
+ # ``OSError`` already covers ``ConnectionError`` and ``socket.timeout`` (G.ERR.09).
+ return
+ self._apply_bg_status_response(job, response)
def _job_status(self, job: BackgroundJob) -> BackgroundJobStatus:
- self._sync_background_job(job)
+ running = job.exit_code is None
return BackgroundJobStatus(
job_id=job.job_id,
sandbox_id=job.sandbox_id,
command=list(job.command),
pid=job.pid,
- running=job.exit_code is None,
+ running=running,
exit_code=job.exit_code,
started_at=job.started_at,
finished_at=job.finished_at,
capture_output=job.capture_output,
- stdout=self._read_job_stream(job.stdout_path),
- stderr=self._read_job_stream(job.stderr_path),
+ stdout=job.stdout,
+ stderr=job.stderr,
workdir=job.workdir,
)
def _job_summary(self, job: BackgroundJob) -> BackgroundJobSummary:
- self._sync_background_job(job)
+ running = job.exit_code is None
return BackgroundJobSummary(
job_id=job.job_id,
pid=job.pid,
command=list(job.command),
- running=job.exit_code is None,
+ running=running,
exit_code=job.exit_code,
started_at=job.started_at,
finished_at=job.finished_at,
@@ -823,7 +866,6 @@ class ProcessRuntime(RuntimeAdapter):
policy: SecurityPolicy,
command: list[str],
*,
- is_daemon: bool,
workdir: str | None,
sandbox_env: dict[str, str] | None,
netns_attached: bool,
@@ -855,7 +897,7 @@ class ProcessRuntime(RuntimeAdapter):
launcher_dir = self._launcher_dirs.get(sandbox_id)
landlock_enabled = policy.landlock.compatibility != "disabled"
- if is_daemon and launcher_dir is not None:
+ if launcher_dir is not None:
daemon_path = launcher_dir / "sandbox-daemon.py"
config.ro_binds.append(
(str(daemon_path), SANDBOX_DAEMON_SANDBOX_PATH),
@@ -899,28 +941,14 @@ class ProcessRuntime(RuntimeAdapter):
# on-disk path needing to remain reachable. That lets us
# keep ``/run`` outside the Landlock allowlist so user code
# cannot read the launcher / daemon scripts at runtime.
- #
- # For the generic (legacy) path used by ``exec_background``,
- # the launcher still runs in ``--`` mode: apply Landlock and
- # then ``execvp`` the requested user command.
- if is_daemon:
- config.command = [
- PYTHON_EXECUTABLE,
- "-S",
- SANDBOX_LAUNCHER_PATH,
- payload,
- "--daemon",
- SANDBOX_DAEMON_SANDBOX_PATH,
- ]
- else:
- config.command = [
- PYTHON_EXECUTABLE,
- "-S",
- SANDBOX_LAUNCHER_PATH,
- payload,
- "--",
- *config.command,
- ]
+ config.command = [
+ PYTHON_EXECUTABLE,
+ "-S",
+ SANDBOX_LAUNCHER_PATH,
+ payload,
+ "--daemon",
+ SANDBOX_DAEMON_SANDBOX_PATH,
+ ]
config.seccomp_fd = seccomp_fd
if self._needs_privdrop_for_process_identity(
@@ -1447,19 +1475,15 @@ class ProcessRuntime(RuntimeAdapter):
def _reap_background_processes(self, sandbox_id: str) -> None:
for job in self._background_jobs_for_sandbox(sandbox_id).values():
- self._sync_background_job(job)
+ self._sync_background_job_blocking(sandbox_id, job)
# ------------------------------------------------------------------
# SIGCHLD-driven zombie reaper.
#
# The reaper has two responsibilities:
- # 1. Poll every tracked ``Popen`` (sandbox daemon monitor + every
- # ``exec_background`` invocation) so their exit status is recorded
- # and they leave the host process table promptly. This uses
- # ``Popen.poll()``, which acquires ``Popen._waitpid_lock`` and is
- # therefore race-safe with concurrent ``Popen.wait()`` calls that
- # stop()/_stop_background_processes() issue on an executor thread.
- # 2. Drain any residual zombie via ``os.waitpid(-1, WNOHANG)``. These
+ # 1. Poll every tracked ``Popen`` (sandbox daemon monitor) so its exit
+ # status is recorded promptly.
+ # 2. Drain any residual zombie via ``os.waitpid(-1, WNOHANG)``.
# are bwrap-internal helpers (most importantly the ``--unshare-user``
# userns helper that is cloned with ``CLONE_PARENT`` and is therefore
# a direct child of box-server, *not* a child of the bwrap monitor)
@@ -1470,13 +1494,8 @@ class ProcessRuntime(RuntimeAdapter):
# branch (which silently sets ``returncode = 0``).
# ------------------------------------------------------------------
def _iter_tracked_popens(self) -> list[subprocess.Popen]:
- """Snapshot of all ``Popen`` objects tracked by this runtime."""
- result: list[subprocess.Popen] = []
- result.extend(self._processes.values())
- for jobs in self._background_processes.values():
- for job in jobs.values():
- result.append(job.proc)
- return result
+ """Snapshot of sandbox lifecycle ``Popen`` objects tracked by this runtime."""
+ return list(self._processes.values())
def _reap_zombies(self) -> None:
"""Reap every zombie child (tracked + orphan).
@@ -1728,25 +1747,67 @@ class ProcessRuntime(RuntimeAdapter):
if not jobs:
return
- running = [job for job in jobs.values() if job.proc.poll() is None]
- for job in running:
+ socket_path = self._control_socket_host_path(sandbox_id)
+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):
+ return
+
+ loop = asyncio.get_running_loop()
+ running_jobs = [
+ job for job in jobs.values() if job.exit_code is None
+ ]
+ for job in running_jobs:
try:
- os.killpg(job.proc.pid, signal.SIGTERM)
- except ProcessLookupError:
+ await loop.run_in_executor(
+ None,
+ self._bg_kill_via_daemon_blocking,
+ _DaemonBgKillCall(
+ socket_path=socket_path,
+ job_id=job.job_id,
+ signum=signal.SIGTERM,
+ ),
+ )
+ except (OSError, ValueError):
+ # ``OSError`` already covers ``ConnectionError`` and ``socket.timeout`` (G.ERR.09).
continue
- loop = asyncio.get_running_loop()
- for job in running:
- proc = job.proc
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ still_running = False
+ for job in running_jobs:
+ await loop.run_in_executor(
+ None,
+ self._sync_background_job_blocking,
+ sandbox_id,
+ job,
+ )
+ if job.exit_code is None:
+ still_running = True
+ if not still_running:
+ return
+ await asyncio.sleep(0.1)
+
+ for job in running_jobs:
+ if job.exit_code is not None:
+ continue
try:
- await loop.run_in_executor(None, proc.wait, timeout)
- except subprocess.TimeoutExpired:
- try:
- os.killpg(proc.pid, signal.SIGKILL)
- except ProcessLookupError:
- continue
- await loop.run_in_executor(None, proc.wait, 5.0)
- self._sync_background_job(job)
+ await loop.run_in_executor(
+ None,
+ self._bg_kill_via_daemon_blocking,
+ _DaemonBgKillCall(
+ socket_path=socket_path,
+ job_id=job.job_id,
+ signum=signal.SIGKILL,
+ ),
+ )
+ except (OSError, ValueError):
+ # ``OSError`` already covers ``ConnectionError`` and ``socket.timeout`` (G.ERR.09).
+ continue
+ await loop.run_in_executor(
+ None,
+ self._sync_background_job_blocking,
+ sandbox_id,
+ job,
+ )
async def create(
self,
@@ -1802,7 +1863,6 @@ class ProcessRuntime(RuntimeAdapter):
sandbox_id,
policy,
list(SANDBOX_DAEMON_COMMAND),
- is_daemon=True,
workdir=None,
sandbox_env=env,
netns_attached=netns_name is not None,
@@ -2171,52 +2231,6 @@ class ProcessRuntime(RuntimeAdapter):
f"Sandbox lifecycle process is not running; returncode={returncode}"
)
- def _prepare_exec_invocation(
- self,
- sandbox_id: str,
- request: RuntimeExecRequest,
- ) -> tuple[list[str], int | None] | None:
- """Build the bwrap argv + a fresh seccomp memfd for one ``exec``.
-
- Returns ``None`` when the sandbox has no recorded policy (the caller
- decides what failure to surface).
- """
- policy_path = self._policy_paths.get(sandbox_id)
- if policy_path is None:
- return None
-
- policy = self._policy_for_sandbox(sandbox_id, policy_path)
- if policy.network.mode == NetworkMode.ISOLATED:
- netns_name = self._ensure_named_netns(sandbox_id, policy)
- else:
- netns_name = None
- self._policy_binds_for_sandbox(sandbox_id, policy)
- self._ensure_launcher_dir(sandbox_id)
-
- seccomp_fd: int | None = None
- try:
- seccomp_fd = self._open_seccomp_fd_from_bytes(
- self._ensure_seccomp_bpf(sandbox_id, policy),
- )
- except Exception:
- logger.warning(
- "Failed to build seccomp filter for sandbox %s exec; continuing without seccomp",
- sandbox_id,
- exc_info=True,
- )
-
- bwrap_args = self._build_sandbox_bwrap_args(
- sandbox_id,
- policy,
- list(request.command),
- is_daemon=False,
- workdir=request.workdir,
- sandbox_env=request.env,
- netns_attached=netns_name is not None,
- seccomp_fd=seccomp_fd,
- )
- return self._wrap_command_in_namespace(bwrap_args, netns_name), seccomp_fd
-
def _daemon_ipc_available(self, sandbox_id: str) -> bool:
if not self._daemon_socket_ready.get(sandbox_id, False):
return False
@@ -2316,6 +2330,95 @@ class ProcessRuntime(RuntimeAdapter):
stderr=str(response.get("stderr", "")),
)
+ def _exec_background_via_daemon_blocking(
+ self,
+ call: _DaemonBgExecCall,
+ ) -> dict[str, Any]:
+ request_payload: dict[str, Any] = {
+ "job_id": call.job_id,
+ "command": list(call.command),
+ "capture_output": call.capture_output,
+ "stdin_size": len(call.stdin_bytes or b""),
+ }
+ if call.env:
+ request_payload["env"] = dict(call.env)
+ if call.workdir:
+ request_payload["workdir"] = call.workdir
+ header_blob = encode_request(
+ request_type=REQUEST_TYPE_EXEC_BACKGROUND,
+ payload=request_payload,
+ )
+ if len(header_blob) > MAX_HEADER_BYTES:
+ return {
+ "ok": False,
+ "started": False,
+ "stderr": (
+ f"daemon request header too large "
+ f"({len(header_blob)} > {MAX_HEADER_BYTES})"
+ ),
+ }
+
+ sock = self._connect_daemon_socket(call.socket_path)
+ try:
+ sock.settimeout(30.0)
+ self._send_request_blob(sock, header_blob, call.stdin_bytes)
+ try:
+ sock.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+ return self._read_response_blob(sock)
+ finally:
+ try:
+ sock.close()
+ except OSError:
+ pass
+
+ def _bg_status_via_daemon_blocking(
+ self,
+ call: _DaemonBgStatusCall,
+ ) -> dict[str, Any]:
+ header_blob = encode_request(
+ request_type=REQUEST_TYPE_BG_STATUS,
+ payload={"job_id": call.job_id},
+ )
+ sock = self._connect_daemon_socket(call.socket_path)
+ try:
+ sock.settimeout(30.0)
+ self._send_request_blob(sock, header_blob, None)
+ try:
+ sock.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+ return self._read_response_blob(sock)
+ finally:
+ try:
+ sock.close()
+ except OSError:
+ pass
+
+ def _bg_kill_via_daemon_blocking(
+ self,
+ call: _DaemonBgKillCall,
+ ) -> dict[str, Any]:
+ header_blob = encode_request(
+ request_type=REQUEST_TYPE_BG_KILL,
+ payload={"job_id": call.job_id, "signum": call.signum},
+ )
+ sock = self._connect_daemon_socket(call.socket_path)
+ try:
+ sock.settimeout(30.0)
+ self._send_request_blob(sock, header_blob, None)
+ try:
+ sock.shutdown(socket.SHUT_WR)
+ except OSError:
+ pass
+ return self._read_response_blob(sock)
+ finally:
+ try:
+ sock.close()
+ except OSError:
+ pass
+
async def _exec_via_daemon(
self,
sandbox_id: str,
@@ -2782,103 +2885,108 @@ class ProcessRuntime(RuntimeAdapter):
sandbox_id: str,
request: RuntimeBackgroundExecRequest,
) -> BackgroundExecResult:
- prepared = self._prepare_exec_invocation(
- sandbox_id,
- RuntimeExecRequest(
- command=request.command,
- workdir=request.workdir,
- env=request.env,
- stdin_data=request.stdin_data,
- ),
- )
- if prepared is None:
+ self._reap_background_processes(sandbox_id)
+
+ socket_path = self._control_socket_host_path(sandbox_id)
+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):
return BackgroundExecResult(
started=False,
command=list(request.command),
- error_message="No policy found for sandbox",
+ error_message=(
+ f"sandbox {sandbox_id!r} daemon IPC channel unavailable; "
+ "the daemon is not running or its control socket is gone"
+ ),
capture_output=request.capture_output,
)
- jobs = self._background_jobs_for_sandbox(sandbox_id)
- bwrap_cmd, seccomp_fd = prepared
- process_env = {**os.environ, **(request.env or {})}
- stdin_target = (
- subprocess.PIPE if request.stdin_data is not None else subprocess.DEVNULL
- )
- pass_fds = (seccomp_fd,) if seccomp_fd is not None else ()
-
- stdout_path: Path | None = None
- stderr_path: Path | None = None
- stdout_file = None
- stderr_file = None
- if request.capture_output:
- logs_dir = self._ensure_bg_logs_dir(sandbox_id)
- stdout_path = logs_dir / f"{request.job_id}.out"
- stderr_path = logs_dir / f"{request.job_id}.err"
- stdout_file = open(stdout_path, "wb")
- stderr_file = open(stderr_path, "wb")
- stdout_target = stdout_file
- stderr_target = stderr_file
- else:
- stdout_target = subprocess.DEVNULL
- stderr_target = subprocess.DEVNULL
-
+ loop = asyncio.get_running_loop()
try:
- proc = subprocess.Popen(
- bwrap_cmd,
- stdin=stdin_target,
- stdout=stdout_target,
- stderr=stderr_target,
- env=process_env,
- pass_fds=pass_fds,
- start_new_session=True,
+ response = await loop.run_in_executor(
+ None,
+ self._exec_background_via_daemon_blocking,
+ _DaemonBgExecCall(
+ socket_path=socket_path,
+ job_id=request.job_id,
+ command=list(request.command),
+ env=dict(request.env) if request.env else None,
+ workdir=request.workdir,
+ stdin_bytes=request.stdin_data,
+ capture_output=request.capture_output,
+ ),
)
- if request.stdin_data is not None and proc.stdin is not None:
- proc.stdin.write(request.stdin_data)
- proc.stdin.close()
- except Exception as exc:
+ except (ConnectionError, ValueError) as exc:
+ self._daemon_socket_ready[sandbox_id] = False
return BackgroundExecResult(
started=False,
command=list(request.command),
- error_message=str(exc),
+ error_message=f"daemon IPC transport failure: {exc}",
capture_output=request.capture_output,
)
- finally:
- if seccomp_fd is not None:
- _safe_close_fd(seccomp_fd)
- if stdout_file is not None:
- stdout_file.close()
- if stderr_file is not None:
- stderr_file.close()
+ except socket.timeout as exc:
+ self._daemon_socket_ready[sandbox_id] = False
+ return BackgroundExecResult(
+ started=False,
+ command=list(request.command),
+ error_message=f"daemon IPC timeout: {exc}",
+ capture_output=request.capture_output,
+ )
+ except OSError as exc:
+ if exc.errno in FATAL_DAEMON_ERRNOS:
+ self._daemon_socket_ready[sandbox_id] = False
+ return BackgroundExecResult(
+ started=False,
+ command=list(request.command),
+ error_message=f"daemon IPC unavailable: {exc}",
+ capture_output=request.capture_output,
+ )
+
+ if not response.get("ok") or not response.get("started", False):
+ error = response.get("stderr") or response.get("error") or "unknown error"
+ return BackgroundExecResult(
+ started=False,
+ command=list(request.command),
+ error_message=str(error),
+ capture_output=request.capture_output,
+ )
+
+ pid = response.get("pid")
+ pid_int = pid if isinstance(pid, int) else None
+ running = response.get("running")
+ running_bool = running if isinstance(running, bool) else True
+ exit_code = response.get("exit_code")
+ exit_code_int = exit_code if isinstance(exit_code, int) else None
job = BackgroundJob(
job_id=request.job_id,
sandbox_id=sandbox_id,
command=list(request.command),
- pid=proc.pid,
- proc=proc,
+ pid=pid_int,
capture_output=request.capture_output,
- stdout_path=stdout_path,
- stderr_path=stderr_path,
workdir=request.workdir,
+ exit_code=exit_code_int if not running_bool else None,
+ stdout=str(response.get("stdout", "")) if request.capture_output else "",
+ stderr=str(response.get("stderr", "")) if request.capture_output else "",
)
+ if not running_bool and job.finished_at is None:
+ job.finished_at = datetime.now(timezone.utc)
+
+ jobs = self._background_jobs_for_sandbox(sandbox_id)
jobs[request.job_id] = job
- self._sync_background_job(job)
logger.info(
- "Started background command in sandbox %s (job=%s pid=%d): %s",
+ "Started background command in sandbox %s (job=%s pid=%s): %s",
sandbox_id,
request.job_id,
- proc.pid,
+ pid_int,
_summarize_command(list(request.command)),
)
return BackgroundExecResult(
started=True,
job_id=request.job_id,
- pid=proc.pid,
+ pid=pid_int,
command=list(request.command),
- running=job.exit_code is None,
- exit_code=job.exit_code,
+ running=running_bool,
+ exit_code=exit_code_int,
capture_output=request.capture_output,
)
@@ -2887,7 +2995,15 @@ class ProcessRuntime(RuntimeAdapter):
sandbox_id: str,
job_id: str,
) -> BackgroundJobStatus:
- return self._job_status(self._get_background_job_record(sandbox_id, job_id))
+ job = self._get_background_job_record(sandbox_id, job_id)
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(
+ None,
+ self._sync_background_job_blocking,
+ sandbox_id,
+ job,
+ )
+ return self._job_status(job)
async def list_background_jobs(
self,
@@ -2896,6 +3012,14 @@ class ProcessRuntime(RuntimeAdapter):
running_only: bool = False,
) -> list[BackgroundJobSummary]:
jobs = list(self._background_jobs_for_sandbox(sandbox_id).values())
+ loop = asyncio.get_running_loop()
+ for job in jobs:
+ await loop.run_in_executor(
+ None,
+ self._sync_background_job_blocking,
+ sandbox_id,
+ job,
+ )
summaries = [self._job_summary(job) for job in jobs]
if running_only:
summaries = [item for item in summaries if item.running]
@@ -2909,7 +3033,13 @@ class ProcessRuntime(RuntimeAdapter):
signum: int = 15,
) -> KillBackgroundJobResult:
job = self._get_background_job_record(sandbox_id, job_id)
- self._sync_background_job(job)
+ loop = asyncio.get_running_loop()
+ await loop.run_in_executor(
+ None,
+ self._sync_background_job_blocking,
+ sandbox_id,
+ job,
+ )
if job.exit_code is not None:
return KillBackgroundJobResult(
job_id=job_id,
@@ -2917,24 +3047,28 @@ class ProcessRuntime(RuntimeAdapter):
reason="already_exited",
exit_code=job.exit_code,
)
- try:
- job.proc.send_signal(signum)
- except ProcessLookupError:
- self._sync_background_job(job)
- return KillBackgroundJobResult(
- job_id=job_id,
- killed=False,
- reason="already_exited",
- exit_code=job.exit_code,
- )
- except PermissionError:
+
+ socket_path = self._control_socket_host_path(sandbox_id)
+ if socket_path is None or not self._daemon_ipc_available(sandbox_id):
return KillBackgroundJobResult(
job_id=job_id,
killed=False,
reason="permission_denied",
exit_code=job.exit_code,
)
- except OSError:
+
+ try:
+ response = await loop.run_in_executor(
+ None,
+ self._bg_kill_via_daemon_blocking,
+ _DaemonBgKillCall(
+ socket_path=socket_path,
+ job_id=job_id,
+ signum=signum,
+ ),
+ )
+ except (OSError, ValueError):
+ # ``OSError`` already covers ``ConnectionError`` and ``socket.timeout`` (G.ERR.09).
return KillBackgroundJobResult(
job_id=job_id,
killed=False,
@@ -2942,12 +3076,21 @@ class ProcessRuntime(RuntimeAdapter):
exit_code=job.exit_code,
)
- self._sync_background_job(job)
+ reason = str(response.get("reason", "permission_denied"))
+ killed = bool(response.get("killed", False))
+ exit_code = response.get("exit_code")
+ exit_code_int = exit_code if isinstance(exit_code, int) else job.exit_code
+ await loop.run_in_executor(
+ None,
+ self._sync_background_job_blocking,
+ sandbox_id,
+ job,
+ )
return KillBackgroundJobResult(
job_id=job_id,
- killed=True,
- reason="ok",
- exit_code=job.exit_code,
+ killed=killed,
+ reason=reason,
+ exit_code=exit_code_int,
)
async def cleanup(self, sandbox_id: str) -> None:
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py b/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py
index 34f6e0b33e..99dec60a00 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/daemon_ipc.py
@@ -61,6 +61,13 @@ REQUEST_TYPE_SHUTDOWN = "shutdown"
REQUEST_TYPE_WRITE_FILE = "write_file"
REQUEST_TYPE_READ_FILE = "read_file"
REQUEST_TYPE_LIST_DIR = "list_dir"
+REQUEST_TYPE_EXEC_BACKGROUND = "exec_background"
+REQUEST_TYPE_BG_STATUS = "bg_status"
+REQUEST_TYPE_BG_KILL = "bg_kill"
+
+# Background job stdout/stderr files live inside the sandbox (same PID
+# namespace as ``exec``) so ``bg-get`` can read them back via daemon IPC.
+SANDBOX_BG_LOG_DIR = "/tmp/.jiuwenbox-bg"
PROTOCOL_VERSION = 1
MAX_HEADER_BYTES = 1 * 1024 * 1024 # 1 MiB JSON header upper bound
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py
index 98ebefecf2..9ab10095f0 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/landlock_launcher.py
@@ -32,6 +32,7 @@ import json
import logging
import os
import sys
+import types
LANDLOCK_CREATE_RULESET = 444
LANDLOCK_ADD_RULE = 445
@@ -238,10 +239,13 @@ def _run_daemon_in_process(daemon_path: str, payload: dict) -> int:
except LandlockHardRequirementError:
return 126
- daemon_globals: dict = {
- "__name__": "jiuwenbox.supervisor.sandbox_daemon_inproc",
- "__file__": daemon_path,
- }
+ module_name = "jiuwenbox.supervisor.sandbox_daemon_inproc"
+ module = types.ModuleType(module_name)
+ module.__file__ = daemon_path
+ sys.modules[module_name] = module
+ daemon_globals = module.__dict__
+ daemon_globals["__name__"] = module_name
+ daemon_globals["__file__"] = daemon_path
try:
compiled = compile(daemon_source, daemon_path, "exec")
except SyntaxError as exc:
@@ -263,44 +267,20 @@ def _run_daemon_in_process(daemon_path: str, payload: dict) -> int:
return 1
-def _run_command(command: list[str], payload: dict) -> int:
- """Apply Landlock and ``execvp`` the user command (legacy path).
-
- Used by ``exec_background``-style callers that still spawn a fresh
- bubblewrap per command and need Landlock to be inherited by the
- user binary they exec into.
- """
- try:
- apply_landlock(payload)
- except LandlockHardRequirementError:
- return 126
- try:
- os.execvp(command[0], command)
- except OSError as exc:
- logger.error("Failed to exec command %s: %s", command[0], exc)
- return 127
- return 0
-
-
def main() -> int:
- """Dispatch between the daemon and generic-exec launcher modes.
+ """Apply Landlock and run the in-sandbox daemon in this process.
- Layouts:
+ Layout:
``landlock_launcher.py PAYLOAD --daemon DAEMON_SCRIPT_PATH``
- Apply Landlock and run the daemon script via ``compile``/``exec``.
- ``landlock_launcher.py PAYLOAD -- COMMAND [ARGS...]``
- Apply Landlock and ``execvp`` the user command (legacy path,
- used by ``exec_background`` for one-shot bwrap invocations).
"""
- if len(sys.argv) < 4:
+ if len(sys.argv) != 4 or sys.argv[2] != "--daemon":
logger.error(
- "Usage: landlock_launcher.py <payload> --daemon <daemon_script>"
- " | landlock_launcher.py <payload> -- <command> [args...]",
+ "Usage: landlock_launcher.py <payload> --daemon <daemon_script>",
)
return 2
payload_b64 = sys.argv[1]
- mode_token = sys.argv[2]
+ daemon_path = sys.argv[3]
try:
payload = _decode_payload(payload_b64)
@@ -309,17 +289,7 @@ def main() -> int:
logger.error("Failed to decode landlock payload: %s", exc)
return 2
- if mode_token == "--daemon":
- return _run_daemon_in_process(sys.argv[3], payload)
- if mode_token == "--":
- command = sys.argv[3:]
- if not command:
- logger.error("Generic launcher mode requires a command after '--'")
- return 2
- return _run_command(command, payload)
-
- logger.error("Unknown launcher mode token %r", mode_token)
- return 2
+ return _run_daemon_in_process(daemon_path, payload)
if __name__ == "__main__":
diff --git a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
index 7f7590f801..6f98448347 100644
--- a/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
+++ b/jiuwenbox/src/jiuwenbox/supervisor/sandbox_daemon.py
@@ -75,6 +75,7 @@ import sys
import threading
import time
from collections.abc import Iterator
+from dataclasses import dataclass
from typing import Any
# These constants are duplicated from ``daemon_ipc`` so the in-sandbox
@@ -92,10 +93,16 @@ REQUEST_TYPE_SHUTDOWN = "shutdown"
REQUEST_TYPE_WRITE_FILE = "write_file"
REQUEST_TYPE_READ_FILE = "read_file"
REQUEST_TYPE_LIST_DIR = "list_dir"
+REQUEST_TYPE_EXEC_BACKGROUND = "exec_background"
+REQUEST_TYPE_BG_STATUS = "bg_status"
+REQUEST_TYPE_BG_KILL = "bg_kill"
+
+SANDBOX_BG_LOG_DIR = "/tmp/.jiuwenbox-bg"
PROTOCOL_VERSION = 1
MAX_HEADER_BYTES = 1 * 1024 * 1024
MAX_STDIN_BYTES = 64 * 1024 * 1024
+MAX_STDOUT_BYTES = 64 * 1024 * 1024
MAX_FILE_BYTES = 256 * 1024 * 1024
ACCEPT_TIMEOUT_SECONDS = 1.0
@@ -671,6 +678,367 @@ def _handle_list_dir(conn: socket.socket, header: dict[str, Any]) -> None:
)
+@dataclass
+class _BgJob:
+ job_id: str
+ command: list[str]
+ proc: subprocess.Popen
+ capture_output: bool
+ stdout_path: str | None
+ stderr_path: str | None
+
+
+_bg_jobs: dict[str, _BgJob | object] = {}
+_bg_jobs_lock = threading.Lock()
+_BG_JOB_RESERVED = object()
+
+
+def _try_reserve_bg_job(job_id: str) -> bool:
+ with _bg_jobs_lock:
+ if job_id in _bg_jobs:
+ return False
+ _bg_jobs[job_id] = _BG_JOB_RESERVED
+ return True
+
+
+def _release_bg_job_reservation(job_id: str) -> None:
+ with _bg_jobs_lock:
+ if _bg_jobs.get(job_id) is _BG_JOB_RESERVED:
+ del _bg_jobs[job_id]
+
+
+def _commit_bg_job(job_id: str, job: _BgJob) -> None:
+ with _bg_jobs_lock:
+ _bg_jobs[job_id] = job
+
+
+def _sync_bg_job(job: _BgJob) -> None:
+ if job.proc.returncode is None:
+ job.proc.poll()
+
+
+def _read_bg_log(path: str | None) -> str:
+ if not path or not os.path.exists(path):
+ return ""
+ try:
+ with open(path, "rb") as fh:
+ data = fh.read(MAX_STDOUT_BYTES + 1)
+ if len(data) > MAX_STDOUT_BYTES:
+ data = data[:MAX_STDOUT_BYTES]
+ return data.decode("utf-8", errors="replace")
+ except OSError:
+ return ""
+
+
+def _bg_job_response(
+ *,
+ ok: bool,
+ job_id: str,
+ job: _BgJob | None = None,
+ started: bool = True,
+ error: str | None = None,
+ stderr: str = "",
+) -> dict[str, Any]:
+ response: dict[str, Any] = {
+ "v": PROTOCOL_VERSION,
+ "ok": ok,
+ "job_id": job_id,
+ "started": started,
+ }
+ if error:
+ response["error"] = error
+ if stderr:
+ response["stderr"] = stderr
+ if job is not None:
+ _sync_bg_job(job)
+ response["pid"] = job.proc.pid
+ response["running"] = job.proc.returncode is None
+ response["exit_code"] = job.proc.returncode
+ if job.capture_output:
+ response["stdout"] = _read_bg_log(job.stdout_path)
+ response["stderr"] = _read_bg_log(job.stderr_path)
+ return response
+
+
+def _handle_exec_background(conn: socket.socket, header: dict[str, Any]) -> None:
+ try:
+ job_id = header.get("job_id")
+ if not isinstance(job_id, str) or not job_id.strip():
+ raise ValueError("exec_background request missing 'job_id'")
+ job_id = job_id.strip()
+
+ command = header.get("command")
+ if not isinstance(command, list) or not command:
+ raise ValueError("exec_background request missing 'command'")
+ command = _stringify_command(command)
+
+ capture_output = bool(header.get("capture_output", True))
+ env_override = _normalize_env(header.get("env"))
+ workdir = header.get("workdir")
+ if workdir is not None and not isinstance(workdir, str):
+ raise ValueError("workdir must be a string")
+ stdin_size = int(header.get("stdin_size") or 0)
+ if stdin_size < 0 or stdin_size > MAX_STDIN_BYTES:
+ raise ValueError(f"invalid stdin_size {stdin_size}")
+
+ stdin_bytes = _recv_exact(conn, stdin_size) if stdin_size else b""
+
+ if not _try_reserve_bg_job(job_id):
+ _send_response(
+ conn,
+ _bg_job_response(
+ ok=False,
+ job_id=job_id,
+ started=False,
+ error="job_exists",
+ stderr=f"background job {job_id!r} already exists",
+ ),
+ )
+ return
+
+ reserved = True
+ try:
+ merged_env = dict(os.environ)
+ merged_env.pop(LISTENER_FD_ENV, None)
+ if env_override is not None:
+ merged_env.update(env_override)
+
+ stdout_path: str | None = None
+ stderr_path: str | None = None
+ stdout_file = None
+ stderr_file = None
+ if capture_output:
+ os.makedirs(SANDBOX_BG_LOG_DIR, exist_ok=True)
+ stdout_path = f"{SANDBOX_BG_LOG_DIR}/{job_id}.out"
+ stderr_path = f"{SANDBOX_BG_LOG_DIR}/{job_id}.err"
+ stdout_file = open(stdout_path, "wb")
+ stderr_file = open(stderr_path, "wb")
+ stdout_target = stdout_file
+ stderr_target = stderr_file
+ else:
+ stdout_target = subprocess.DEVNULL
+ stderr_target = subprocess.DEVNULL
+
+ proc_kwargs: dict[str, Any] = {
+ "stdin": subprocess.PIPE if stdin_size else subprocess.DEVNULL,
+ "stdout": stdout_target,
+ "stderr": stderr_target,
+ "env": merged_env,
+ "close_fds": True,
+ "start_new_session": True,
+ }
+ if workdir:
+ proc_kwargs["cwd"] = workdir
+
+ try:
+ proc = subprocess.Popen(command, **proc_kwargs)
+ if stdin_size and proc.stdin is not None:
+ proc.stdin.write(stdin_bytes)
+ proc.stdin.close()
+ except OSError as exc:
+ _send_response(
+ conn,
+ _bg_job_response(
+ ok=False,
+ job_id=job_id,
+ started=False,
+ error="spawn_failed",
+ stderr=f"failed to spawn background command: {exc}",
+ ),
+ )
+ return
+ finally:
+ if stdout_file is not None:
+ stdout_file.close()
+ if stderr_file is not None:
+ stderr_file.close()
+
+ job = _BgJob(
+ job_id=job_id,
+ command=command,
+ proc=proc,
+ capture_output=capture_output,
+ stdout_path=stdout_path,
+ stderr_path=stderr_path,
+ )
+ _commit_bg_job(job_id, job)
+ reserved = False
+
+ _send_response(conn, _bg_job_response(ok=True, job_id=job_id, job=job))
+ finally:
+ if reserved:
+ _release_bg_job_reservation(job_id)
+ except (ValueError, ConnectionError) as exc:
+ _send_response(
+ conn,
+ _bg_job_response(
+ ok=False,
+ job_id=str(header.get("job_id") or ""),
+ started=False,
+ error="bad_request",
+ stderr=str(exc),
+ ),
+ )
+ except Exception as exc: # pragma: no cover - defensive guard
+ logger.exception("Unhandled error while handling exec_background request")
+ _send_response(
+ conn,
+ _bg_job_response(
+ ok=False,
+ job_id=str(header.get("job_id") or ""),
+ started=False,
+ error="internal",
+ stderr=f"daemon internal error: {exc}",
+ ),
+ )
+
+
+def _handle_bg_status(conn: socket.socket, header: dict[str, Any]) -> None:
+ job_id = header.get("job_id")
+ if not isinstance(job_id, str) or not job_id.strip():
+ _send_response(
+ conn,
+ _bg_job_response(
+ ok=False,
+ job_id="",
+ started=False,
+ error="bad_request",
+ stderr="bg_status request missing 'job_id'",
+ ),
+ )
+ return
+ job_id = job_id.strip()
+ with _bg_jobs_lock:
+ job = _bg_jobs.get(job_id)
+ if job is None or job is _BG_JOB_RESERVED:
+ _send_response(
+ conn,
+ _bg_job_response(
+ ok=False,
+ job_id=job_id,
+ started=False,
+ error="not_found",
+ stderr=f"background job {job_id!r} not found",
+ ),
+ )
+ return
+ _send_response(conn, _bg_job_response(ok=True, job_id=job_id, job=job))
+
+
+def _handle_bg_kill(conn: socket.socket, header: dict[str, Any]) -> None:
+ job_id = header.get("job_id")
+ if not isinstance(job_id, str) or not job_id.strip():
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": False,
+ "error": "bad_request",
+ "stderr": "bg_kill request missing 'job_id'",
+ },
+ )
+ return
+ job_id = job_id.strip()
+ signum = header.get("signum", 15)
+ if not isinstance(signum, int):
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": False,
+ "error": "bad_request",
+ "stderr": "signum must be an integer",
+ },
+ )
+ return
+
+ with _bg_jobs_lock:
+ job = _bg_jobs.get(job_id)
+ if job is None or job is _BG_JOB_RESERVED:
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": False,
+ "job_id": job_id,
+ "killed": False,
+ "reason": "not_found",
+ },
+ )
+ return
+
+ _sync_bg_job(job)
+ if job.proc.returncode is not None:
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": True,
+ "job_id": job_id,
+ "killed": False,
+ "reason": "already_exited",
+ "exit_code": job.proc.returncode,
+ },
+ )
+ return
+
+ try:
+ job.proc.send_signal(signum)
+ except ProcessLookupError:
+ _sync_bg_job(job)
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": True,
+ "job_id": job_id,
+ "killed": False,
+ "reason": "already_exited",
+ "exit_code": job.proc.returncode,
+ },
+ )
+ return
+ except PermissionError:
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": True,
+ "job_id": job_id,
+ "killed": False,
+ "reason": "permission_denied",
+ "exit_code": job.proc.returncode,
+ },
+ )
+ return
+ except OSError:
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": True,
+ "job_id": job_id,
+ "killed": False,
+ "reason": "permission_denied",
+ "exit_code": job.proc.returncode,
+ },
+ )
+ return
+
+ _sync_bg_job(job)
+ _send_response(
+ conn,
+ {
+ "v": PROTOCOL_VERSION,
+ "ok": True,
+ "job_id": job_id,
+ "killed": True,
+ "reason": "ok",
+ "exit_code": job.proc.returncode,
+ },
+ )
+
+
def _handle_connection(conn: socket.socket, state: DaemonState) -> None:
state.begin_request()
try:
@@ -708,6 +1076,12 @@ def _handle_connection(conn: socket.socket, state: DaemonState) -> None:
_handle_read_file(conn, header)
elif request_type == REQUEST_TYPE_LIST_DIR:
_handle_list_dir(conn, header)
+ elif request_type == REQUEST_TYPE_EXEC_BACKGROUND:
+ _handle_exec_background(conn, header)
+ elif request_type == REQUEST_TYPE_BG_STATUS:
+ _handle_bg_status(conn, header)
+ elif request_type == REQUEST_TYPE_BG_KILL:
+ _handle_bg_kill(conn, header)
else:
_send_response(
conn,
diff --git a/jiuwenbox/tests/integration/test_server_api_default.py b/jiuwenbox/tests/integration/test_server_api_default.py
index 974d81a57f..8a346440c3 100644
--- a/jiuwenbox/tests/integration/test_server_api_default.py
+++ b/jiuwenbox/tests/integration/test_server_api_default.py
@@ -3767,6 +3767,36 @@ class TestBackgroundJobs:
)
assert get_resp.status_code == 404, get_resp.text
+ @staticmethod
+ def test_bg_exec_visible_via_exec_ps(client):
+ create_resp = client.post("/api/v1/sandboxes", json={})
+ sandbox_id = create_resp.json()["id"]
+ job_id = f"ps-{uuid.uuid4().hex[:4]}"
+
+ started = _exec_background(
+ client,
+ sandbox_id,
+ ["sleep", "3600"],
+ job_id=job_id,
+ )
+ assert started["started"] is True
+
+ ps_resp = client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/exec",
+ json={
+ "command": ["ps", "-eo", "pid,args"],
+ "timeout_seconds": 10,
+ },
+ )
+ assert ps_resp.status_code == 200, ps_resp.text
+ assert ps_resp.json()["exit_code"] == 0
+ assert "sleep" in ps_resp.json()["stdout"]
+
+ client.post(
+ f"/api/v1/sandboxes/{sandbox_id}/background/{job_id}/kill",
+ json={},
+ )
+
class TestSandboxListing:
@staticmethod