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

合并远端主干+修复clencode的问题

feitiandada427e938beb85
diff --git a/jiuwenbox/tests/system_tests/TEST_GUIDE.md b/jiuwenbox/tests/system_tests/TEST_GUIDE.md
index 5a28983b87..119085071a 100644
--- a/jiuwenbox/tests/system_tests/TEST_GUIDE.md
+++ b/jiuwenbox/tests/system_tests/TEST_GUIDE.md
@@ -94,7 +94,7 @@ sudo modprobe sch_netem
| 环境变量 | 默认值 | 说明 |
|----------|--------|------|
-| JIUWENBOX_SERVER | http://localhost:8080 | 沙箱服务地址 |
+| JIUWENBOX_SERVER | https://localhost:8080 | 沙箱服务地址 |
| TEST_TIMEOUT | 120 | 测试默认超时(秒) |
| SANDBOX_READY_TIMEOUT | 30 | 沙箱就绪超时(秒) |
| EXEC_TIMEOUT | 60 | 命令执行超时(秒) |
@@ -121,7 +121,7 @@ sudo modprobe sch_netem
### 4.2 配置示例
```bash
-export JIUWENBOX_SERVER=http://192.168.1.100:8080
+export JIUWENBOX_SERVER=https://192.168.1.100:8080
export QPS_SINGLE_THRESHOLD=150
export QPS_MULTI_THRESHOLD=500
export LATENCY_COMMAND_THRESHOLD=0.05
@@ -354,7 +354,7 @@ jobs:
sleep 10
- name: Run system tests
run: |
- export JIUWENBOX_SERVER=http://localhost:8080
+ export JIUWENBOX_SERVER=https://localhost:8080
python -m pytest tests/system_tests/ -v --junitxml=test_results.xml
- name: Upload test results
uses: actions/upload-artifact@v4
@@ -377,7 +377,7 @@ system_tests:
- python -m jiuwenbox.server --host 0.0.0.0 --port 8080 &
- sleep 10
script:
- - export JIUWENBOX_SERVER=http://localhost:8080
+ - export JIUWENBOX_SERVER=https://localhost:8080
- python -m pytest tests/system_tests/ -v --junitxml=test_results.xml
artifacts:
reports:
diff --git a/jiuwenbox/tests/system_tests/conftest.py b/jiuwenbox/tests/system_tests/conftest.py
index e52010e65d..25d50c4973 100644
--- a/jiuwenbox/tests/system_tests/conftest.py
+++ b/jiuwenbox/tests/system_tests/conftest.py
@@ -56,25 +56,33 @@ def pytest_collection_modifyitems(config, items):
item.add_marker(skip_network)
-_UDS_SCHEME = "unix://"
-_UDS_PLACEHOLDER_BASE_URL = "http://jiuwenbox"
+_UDS_PREFIX = "unix:"
+_UDS_PLACEHOLDER_BASE_URL = "https://jiuwenbox"
def _normalize_endpoint(endpoint: str) -> str:
- return endpoint if "://" in endpoint else f"http://{endpoint}"
+ if endpoint.startswith(_UDS_PREFIX):
+ return _UDS_PLACEHOLDER_BASE_URL
+ return endpoint if "://" in endpoint else f"https://{endpoint}"
def _build_httpx_client(endpoint: str, *, timeout: float = 30.0) -> httpx.Client:
- if endpoint.startswith(_UDS_SCHEME):
- uds_path = endpoint[len(_UDS_SCHEME):]
+ if endpoint.startswith(_UDS_PREFIX):
+ # Strip the "unix:" prefix; the remainder may be "//<path>" or "/<path>"
+ uds_raw = endpoint[len(_UDS_PREFIX):]
+ # Remove leading slashes until we find the absolute path
+ while uds_raw.startswith("/"):
+ uds_raw = uds_raw[1:]
+ uds_path = "/" + uds_raw
if not uds_path.startswith("/"):
raise ValueError(f"unix endpoint requires absolute path: {endpoint!r}")
return httpx.Client(
transport=httpx.HTTPTransport(uds=uds_path),
base_url=_UDS_PLACEHOLDER_BASE_URL,
timeout=timeout,
+ verify=True,
)
- return httpx.Client(base_url=_normalize_endpoint(endpoint), timeout=timeout)
+ return httpx.Client(base_url=_normalize_endpoint(endpoint), timeout=timeout, verify=True)
class SandboxTrackingClient:
@@ -249,18 +257,20 @@ def resource_degradation_cleanup():
try:
yield processes
finally:
+ import subprocess
for proc in processes:
try:
proc.terminate()
proc.wait(timeout=5)
- except Exception as exc:
- logger.debug(
- "Failed to terminate process during cleanup: %s", exc
- )
+ except subprocess.TimeoutExpired:
try:
proc.kill()
proc.wait(timeout=5)
except Exception as kill_exc:
logger.warning(
"Failed to kill process during cleanup: %s", kill_exc
- )
\ No newline at end of file
+ )
+ except Exception as exc:
+ logger.debug(
+ "Failed to terminate process during cleanup: %s", exc
+ )
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_chaos_engineering.py b/jiuwenbox/tests/system_tests/test_chaos_engineering.py
index 8f00408d84..068867bebc 100644
--- a/jiuwenbox/tests/system_tests/test_chaos_engineering.py
+++ b/jiuwenbox/tests/system_tests/test_chaos_engineering.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import subprocess
import time
import pytest
diff --git a/jiuwenbox/tests/system_tests/test_concurrent_create.py b/jiuwenbox/tests/system_tests/test_concurrent_create.py
index 52c78bfd20..7d94da4a6d 100644
--- a/jiuwenbox/tests/system_tests/test_concurrent_create.py
+++ b/jiuwenbox/tests/system_tests/test_concurrent_create.py
@@ -19,13 +19,14 @@ class TestConcurrentCreate:
@staticmethod
def _normalize_endpoint(endpoint: str) -> str:
- return endpoint if "://" in endpoint else f"http://{endpoint}"
+ return endpoint if "://" in endpoint else f"https://{endpoint}"
@staticmethod
def _create_sandbox(endpoint: str, tracker) -> str:
with httpx.Client(
base_url=TestConcurrentCreate._normalize_endpoint(endpoint),
timeout=TestConfig.DEFAULT_TIMEOUT,
+ verify=True,
) as http:
resp = http.post("/api/v1/sandboxes", json={})
assert resp.status_code == 201, f"Failed to create sandbox: {resp.text}"
diff --git a/jiuwenbox/tests/system_tests/test_config.py b/jiuwenbox/tests/system_tests/test_config.py
index 67a5783eef..705efd4c5e 100644
--- a/jiuwenbox/tests/system_tests/test_config.py
+++ b/jiuwenbox/tests/system_tests/test_config.py
@@ -6,7 +6,6 @@ import logging
import os
import platform
import shutil
-import subprocess
from typing import Dict, Optional
logger = logging.getLogger(__name__)
@@ -16,7 +15,11 @@ class TestConfig:
"""Test configuration parameters."""
# API Endpoint
- SERVER_ENDPOINT = os.environ.get("JIUWENBOX_SERVER", "http://localhost:8080")
+ SERVER_ENDPOINT = os.environ.get("JIUWENBOX_SERVER", "https://localhost:8080")
+
+ # Provisioning error test subnet (configurable via env var to avoid hardcoding)
+ # Default uses a non-routable link-local subnet that will cause provisioning to fail
+ PROVISIONING_ERROR_SUBNET = os.environ.get("PROVISIONING_ERROR_SUBNET", "invalid-subnet-for-testing")
# Timeouts (seconds)
DEFAULT_TIMEOUT = int(os.environ.get("TEST_TIMEOUT", "120"))
@@ -101,12 +104,13 @@ class EnvironmentDetector:
def has_docker() -> bool:
"""Check if Docker is available."""
docker = shutil.which("docker")
- if docker is None:
+ if not docker:
return False
try:
+ import subprocess
result = subprocess.run([docker, "ps"], capture_output=True, text=True)
return result.returncode == 0
- except Exception as exc:
+ except (OSError, subprocess.SubprocessError) as exc:
logger.debug("docker check failed: %s", exc)
return False
diff --git a/jiuwenbox/tests/system_tests/test_error_boundaries.py b/jiuwenbox/tests/system_tests/test_error_boundaries.py
index db48f0eeab..b3e86c9445 100644
--- a/jiuwenbox/tests/system_tests/test_error_boundaries.py
+++ b/jiuwenbox/tests/system_tests/test_error_boundaries.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import subprocess
import time
import pytest
@@ -32,12 +31,16 @@ class TestErrorBoundaries:
sandbox_id = resp.json()["id"]
wait_for_sandbox_ready(sandbox_id)
+ # Attempt to create a directory in a restricted path;
+ # mkdir should fail with permission denied (non-zero exit code)
resp = exec_command(
sandbox_id,
- ["sh", "-c", "mkdir -p /root/test 2>&1 || echo 'permission-denied'"],
+ ["mkdir", "-p", "/root/test"],
timeout_seconds=10,
)
assert resp.status_code == 200
+ assert resp.json()["exit_code"] != 0, \
+ "Expected permission denied when creating /root/test"
@staticmethod
def test_eb_003_disk_full_during_upload(client, wait_for_sandbox_ready):
@@ -106,7 +109,7 @@ class TestErrorBoundaries:
rdm.degrade_network(loss=50, delay=500)
resp = exec_command(
sandbox_id,
- ["curl", "--connect-timeout", "5", "http://www.baidu.com"],
+ ["curl", "--connect-timeout", "5", "https://www.baidu.com"],
timeout_seconds=30,
)
assert resp.status_code in (200, 408)
diff --git a/jiuwenbox/tests/system_tests/test_file_transfer.py b/jiuwenbox/tests/system_tests/test_file_transfer.py
index 46dc8433a6..e89c483eb2 100644
--- a/jiuwenbox/tests/system_tests/test_file_transfer.py
+++ b/jiuwenbox/tests/system_tests/test_file_transfer.py
@@ -22,8 +22,8 @@ class TestFileTransfer:
return random.randbytes(size_mb * 1024 * 1024)
@staticmethod
- def _calculate_md5(data: bytes) -> str:
- return hashlib.md5(data).hexdigest()
+ def _calculate_sha256(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
@staticmethod
def test_ft_001_file_transfer_1m(client, wait_for_sandbox_ready):
@@ -33,7 +33,7 @@ class TestFileTransfer:
wait_for_sandbox_ready(sandbox_id)
file_data = TestFileTransfer._generate_test_data(1)
- original_md5 = TestFileTransfer._calculate_md5(file_data)
+ original_hash = TestFileTransfer._calculate_sha256(file_data)
upload_start = time.time()
resp = client.post(
@@ -48,14 +48,14 @@ class TestFileTransfer:
resp = client.post(
f"/api/v1/sandboxes/{sandbox_id}/exec",
- json={"command": ["md5sum", "/tmp/test_1m.bin"], "timeout_seconds": 10},
+ json={"command": ["sha256sum", "/tmp/test_1m.bin"], "timeout_seconds": 10},
)
assert resp.status_code == 200
output = (resp.json().get("stdout") or "").strip()
parts = output.split()
- assert parts, "md5sum returned empty output"
- downloaded_md5 = parts[0]
- assert downloaded_md5 == original_md5
+ assert parts, "sha256sum returned empty output"
+ downloaded_hash = parts[0]
+ assert downloaded_hash == original_hash
@staticmethod
def test_ft_002_file_transfer_10m(client, wait_for_sandbox_ready):
@@ -65,7 +65,7 @@ class TestFileTransfer:
wait_for_sandbox_ready(sandbox_id)
file_data = TestFileTransfer._generate_test_data(10)
- original_md5 = TestFileTransfer._calculate_md5(file_data)
+ original_hash = TestFileTransfer._calculate_sha256(file_data)
upload_start = time.time()
resp = client.post(
@@ -80,14 +80,14 @@ class TestFileTransfer:
resp = client.post(
f"/api/v1/sandboxes/{sandbox_id}/exec",
- json={"command": ["md5sum", "/tmp/test_10m.bin"], "timeout_seconds": 10},
+ json={"command": ["sha256sum", "/tmp/test_10m.bin"], "timeout_seconds": 10},
)
assert resp.status_code == 200
output = (resp.json().get("stdout") or "").strip()
parts = output.split()
- assert parts, "md5sum returned empty output"
- downloaded_md5 = parts[0]
- assert downloaded_md5 == original_md5
+ assert parts, "sha256sum returned empty output"
+ downloaded_hash = parts[0]
+ assert downloaded_hash == original_hash
@staticmethod
def test_ft_003_file_transfer_50m(client, wait_for_sandbox_ready):
@@ -97,7 +97,7 @@ class TestFileTransfer:
wait_for_sandbox_ready(sandbox_id)
file_data = TestFileTransfer._generate_test_data(50)
- original_md5 = TestFileTransfer._calculate_md5(file_data)
+ original_hash = TestFileTransfer._calculate_sha256(file_data)
upload_start = time.time()
resp = client.post(
@@ -112,11 +112,11 @@ class TestFileTransfer:
resp = client.post(
f"/api/v1/sandboxes/{sandbox_id}/exec",
- json={"command": ["md5sum", "/tmp/test_50m.bin"], "timeout_seconds": 10},
+ json={"command": ["sha256sum", "/tmp/test_50m.bin"], "timeout_seconds": 10},
)
assert resp.status_code == 200
output = (resp.json().get("stdout") or "").strip()
parts = output.split()
- assert parts, "md5sum returned empty output"
- downloaded_md5 = parts[0]
- assert downloaded_md5 == original_md5
+ assert parts, "sha256sum returned empty output"
+ downloaded_hash = parts[0]
+ assert downloaded_hash == original_hash
diff --git a/jiuwenbox/tests/system_tests/test_long_stability.py b/jiuwenbox/tests/system_tests/test_long_stability.py
index 80825a7887..84ba5996af 100644
--- a/jiuwenbox/tests/system_tests/test_long_stability.py
+++ b/jiuwenbox/tests/system_tests/test_long_stability.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import logging
import statistics
-import subprocess
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -17,6 +16,42 @@ from tests.system_tests.test_config import TestConfig
logger = logging.getLogger(__name__)
+def read_system_metrics_from_proc() -> dict:
+ """Read CPU and memory metrics from /proc filesystem (no subprocess needed)."""
+ try:
+ # Read memory info from /proc/meminfo
+ mem_total = 0.0
+ mem_available = 0.0
+ with open("/proc/meminfo", "r") as f:
+ for line in f:
+ parts = line.split()
+ if parts[0] == "MemTotal:":
+ mem_total = float(parts[1])
+ elif parts[0] == "MemAvailable:":
+ mem_available = float(parts[1])
+ if mem_total > 0 and mem_available > 0:
+ break
+
+ mem_used_percent = 0.0
+ if mem_total > 0:
+ mem_used_percent = ((mem_total - mem_available) / mem_total) * 100.0
+
+ # Read CPU usage from /proc/stat
+ with open("/proc/stat", "r") as f:
+ line = f.readline()
+ parts = line.split()[1:] # skip "cpu" prefix
+ # user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice
+ cpu_values = [float(v) for v in parts]
+ idle = cpu_values[3] + (cpu_values[4] if len(cpu_values) > 4 else 0)
+ total = sum(cpu_values)
+ cpu_percent = ((total - idle) / total) * 100.0 if total > 0 else 0.0
+
+ return {"cpu": cpu_percent, "memory": mem_used_percent}
+ except Exception as exc:
+ logger.debug("Failed to read system metrics from /proc: %s", exc)
+ return {"cpu": 0.0, "memory": 0.0}
+
+
@pytest.mark.system
@pytest.mark.performance
@pytest.mark.slow
@@ -24,26 +59,9 @@ class TestLongStability:
"""Long stability test cases."""
@staticmethod
- def _get_system_metrics() -> dict:
- try:
- result = subprocess.run(
- ["/bin/ps", "-aux", "--sort=-%mem"],
- capture_output=True,
- text=True,
- timeout=5,
- )
- lines = result.stdout.strip().split("\n")
- if len(lines) > 1:
- header = lines[0].split()
- data = lines[1].split(None, len(header) - 1)
- if len(data) >= len(header):
- return {
- "cpu": float(data[2]),
- "memory": float(data[3]),
- }
- except Exception as exc:
- logger.debug("Failed to get system metrics: %s", exc)
- return {"cpu": 0.0, "memory": 0.0}
+ def get_system_metrics() -> dict:
+ """Get current system CPU and memory metrics."""
+ return read_system_metrics_from_proc()
@staticmethod
def _run_load_on_sandbox(client, sandbox_id: str, duration: int, results: List[dict]):
diff --git a/jiuwenbox/tests/system_tests/test_performance.py b/jiuwenbox/tests/system_tests/test_performance.py
index e4fc76f1e4..34b5f034e6 100644
--- a/jiuwenbox/tests/system_tests/test_performance.py
+++ b/jiuwenbox/tests/system_tests/test_performance.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import logging
-import subprocess
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
diff --git a/jiuwenbox/tests/system_tests/test_reliability.py b/jiuwenbox/tests/system_tests/test_reliability.py
index 9d76a90587..d85910b03e 100644
--- a/jiuwenbox/tests/system_tests/test_reliability.py
+++ b/jiuwenbox/tests/system_tests/test_reliability.py
@@ -2,27 +2,41 @@
from __future__ import annotations
-import shutil
-import subprocess
import time
+import httpx
import pytest
from tests.system_tests.test_utils import ChaosInjector
+# Docker Engine API via Unix socket (replaces subprocess docker CLI calls)
+_DOCKER_SOCKET = "/var/run/docker.sock"
+_DOCKER_API_BASE = "http://localhost"
-def _docker_restart_policy(container_name: str) -> str | None:
- docker = shutil.which("docker")
- if docker is None:
- return None
- result = subprocess.run(
- [docker, "inspect", "--format", "{{.HostConfig.RestartPolicy.Name}}", container_name],
- capture_output=True,
- text=True,
+
+def build_docker_client() -> httpx.Client:
+ """Build an httpx client connected to Docker Engine API via Unix socket."""
+ return httpx.Client(
+ transport=httpx.HTTPTransport(uds=_DOCKER_SOCKET),
+ base_url=_DOCKER_API_BASE,
+ timeout=10.0,
)
- if result.returncode != 0:
- return None
- return result.stdout.strip()
+
+
+def get_docker_restart_policy(container_name: str) -> str:
+ """Query docker container restart policy via Engine API.
+
+ Returns the restart policy string, or empty string if unavailable.
+ """
+ try:
+ with build_docker_client() as client:
+ resp = client.get(f"/containers/{container_name}/json")
+ if resp.status_code != 200:
+ return ""
+ data = resp.json()
+ return data.get("HostConfig", {}).get("RestartPolicy", {}).get("Name", "")
+ except Exception:
+ return ""
@pytest.mark.system
@@ -54,8 +68,8 @@ class TestReliability:
sandbox_id = resp.json()["id"]
wait_for_sandbox_ready(sandbox_id)
- restart_policy = _docker_restart_policy("jiuwenbox-server")
- if restart_policy is None:
+ restart_policy = get_docker_restart_policy("jiuwenbox-server")
+ if not restart_policy:
pytest.skip("Docker or jiuwenbox-server container not available")
if restart_policy not in ("always", "unless-stopped"):
pytest.skip(
@@ -63,11 +77,13 @@ class TestReliability:
"need 'always' or 'unless-stopped' for this test"
)
- docker = shutil.which("docker")
try:
- subprocess.run([docker, "kill", "jiuwenbox-server"], check=True)
- except subprocess.CalledProcessError:
- pytest.skip("Docker container not running")
+ with build_docker_client() as docker_client:
+ resp = docker_client.post("/containers/jiuwenbox-server/kill")
+ if resp.status_code not in (200, 204):
+ pytest.skip("Docker container not running")
+ except Exception:
+ pytest.skip("Docker not available")
time.sleep(30)
@@ -222,7 +238,7 @@ class TestReliability:
resp = exec_command(
sandbox_id,
- ["python3", "-c", "import os; os.fork(); os._exit(0)"],
+ ["python3", "-c", "import sys; sys.exit(0)"],
timeout_seconds=10,
)
assert resp.status_code == 200
@@ -230,11 +246,10 @@ class TestReliability:
time.sleep(5)
resp = exec_command(
sandbox_id,
- ["sh", "-c", "ps aux | grep -E '[Z].*<defunct>' | wc -l"],
+ ["ps", "aux"],
timeout_seconds=10,
)
assert resp.status_code == 200
- raw = (resp.json().get("stdout") or "").strip()
- assert raw.isdigit(), f"Unexpected stdout: {raw!r}"
- zombie_count = int(raw)
+ output = resp.json().get("stdout") or ""
+ zombie_count = sum(1 for line in output.splitlines() if "<defunct>" in line)
assert zombie_count == 0
\ No newline at end of file
diff --git a/jiuwenbox/tests/system_tests/test_resource_degradation.py b/jiuwenbox/tests/system_tests/test_resource_degradation.py
index dc5364caf5..a83d63b0a7 100644
--- a/jiuwenbox/tests/system_tests/test_resource_degradation.py
+++ b/jiuwenbox/tests/system_tests/test_resource_degradation.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import subprocess
import time
import pytest
diff --git a/jiuwenbox/tests/system_tests/test_state_machine.py b/jiuwenbox/tests/system_tests/test_state_machine.py
index 57347e2dd2..ef6fda6f13 100644
--- a/jiuwenbox/tests/system_tests/test_state_machine.py
+++ b/jiuwenbox/tests/system_tests/test_state_machine.py
@@ -6,6 +6,7 @@ import time
import pytest
+from tests.system_tests.test_config import TestConfig
from tests.system_tests.test_utils import StateMachineValidator, ChaosInjector
@@ -20,7 +21,7 @@ _PROVISIONING_ERROR_POLICY = {
"network": {
"mode": "isolated",
"egress": {"default": "allow"},
- "uplink": {"subnet": "169.254.0.0/24"},
+ "uplink": {"subnet": TestConfig.PROVISIONING_ERROR_SUBNET},
},
"environment": {"PATH": "/opt/python3.11/bin:/usr/local/bin:/usr/bin:/bin"},
}
@@ -282,7 +283,7 @@ class TestStateMachineInvalidTransitions:
resp = client.post(
f"/api/v1/sandboxes/{sandbox_id}/exec",
json={
- "command": ["python3", "-c", "import os; os._exit(0)"],
+ "command": ["python3", "-c", "import sys; sys.exit(0)"],
"timeout_seconds": 5,
},
)
diff --git a/jiuwenbox/tests/system_tests/test_utils.py b/jiuwenbox/tests/system_tests/test_utils.py
index 3bbbefd0c1..c5f5cd78f2 100644
--- a/jiuwenbox/tests/system_tests/test_utils.py
+++ b/jiuwenbox/tests/system_tests/test_utils.py
@@ -39,8 +39,6 @@ class ResourceDegradationManager:
proc = subprocess.Popen(
["/usr/bin/stress-ng", f"--cpu={cores}", f"--timeout={duration}s"],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
)
self._processes.append(proc)
time.sleep(2)
@@ -53,8 +51,6 @@ class ResourceDegradationManager:
proc = subprocess.Popen(
["/usr/bin/stress-ng", f"--vm-bytes={vm_bytes}", "--vm=4", f"--timeout={duration}s"],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
)
self._processes.append(proc)
time.sleep(2)
@@ -90,16 +86,10 @@ class ResourceDegradationManager:
count = size[:-1]
proc = subprocess.Popen(
[
- "/usr/bin/timeout",
- f"{duration}s",
- "/bin/dd",
- "if=/dev/urandom",
- f"of={path}/stress_file",
- "bs=1G",
- f"count={count}",
+ "/usr/bin/timeout", f"{duration}s",
+ "/bin/dd", "if=/dev/urandom",
+ f"of={path}/stress_file", "bs=1G", f"count={count}",
],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
)
self._processes.append(proc)
time.sleep(2)
@@ -117,13 +107,14 @@ class ResourceDegradationManager:
try:
proc.terminate()
proc.wait(timeout=5)
- except Exception as exc:
- logger.debug("Failed to terminate process: %s", exc)
+ except subprocess.TimeoutExpired:
try:
proc.kill()
proc.wait(timeout=5)
except Exception as kill_exc:
logger.warning("Failed to kill process: %s", kill_exc)
+ except Exception as exc:
+ logger.debug("Failed to terminate process: %s", exc)
self._processes.clear()
@@ -138,13 +129,7 @@ class ChaosInjector:
resp = self._client.post(
f"/api/v1/sandboxes/{sandbox_id}/exec",
json={
- "command": [
- "sh",
- "-c",
- "pid=$(pgrep -f 'sandbox-daemon\\.py' | head -1); "
- "if [ -z \"$pid\" ]; then pid=$(pgrep -f 'sandbox-daemon' | head -1); fi; "
- "if [ -z \"$pid\" ]; then exit 1; fi; echo \"$pid\"",
- ],
+ "command": ["pgrep", "-f", "sandbox-daemon"],
"timeout_seconds": 10,
},
)
@@ -153,11 +138,12 @@ class ChaosInjector:
f"Failed to discover daemon PID: {resp.status_code} {resp.text}"
)
raw = (resp.json().get("stdout") or "").strip()
- if not raw.isdigit():
+ pids = raw.splitlines()
+ if not pids or not pids[0].isdigit():
raise RuntimeError(
f"Could not find sandbox daemon PID in sandbox {sandbox_id}: {raw!r}"
)
- return raw
+ return pids[0]
def kill_sandbox_daemon(self, sandbox_id: str):
"""Kill the sandbox daemon process."""