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
feat(jiuwenbox): 支持 Java 程序在沙箱内运行
sapeurs522d5ab15c46
diff --git a/jiuwenbox/docker/Dockerfile b/jiuwenbox/docker/Dockerfileindex e7c8753faa..10c3438e57 100644--- a/jiuwenbox/docker/Dockerfile+++ b/jiuwenbox/docker/Dockerfile@@ -9,6 +9,9 @@ RUN echo "insecure" >> ~/.curlrcRUN sed -i 's/gpgcheck=1/gpgcheck=0/g' /etc/yum.conf /etc/yum.repos.d/openEuler.repoRUN yum makecache+# JDK 17 uses the headless + devel pair (BiSheng OpenJDK 17 on openEuler 24.03):+# headless gives `java` without X11 deps, devel gives `javac`/`jar`.+# Verified on 205 (aarch64).RUN yum install -y \bubblewrap \iproute \@@ -20,7 +23,19 @@ RUN yum install -y \python3-pip \git \vim \- unzip+ unzip \+ java-17-openjdk-headless \+ java-17-openjdk-devel \+ && yum clean all \+ && rm -rf /var/cache/yum++# JAVA_HOME points at the stable, version-independent symlink+# (/usr/lib/jvm/java-17-openjdk -> /etc/alternatives/java_sdk_17_openjdk -> the+# versioned dir), so minor JDK upgrades do not break the path. java/javac/jar+# are also on PATH via /usr/bin alternatives, but prepending $JAVA_HOME/bin+# makes the JDK the authoritative one.+ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk+ENV PATH="${JAVA_HOME}/bin:${PATH}"WORKDIR /appdiff --git a/jiuwenbox/src/jiuwenbox/configs/java-policy.yaml b/jiuwenbox/src/jiuwenbox/configs/java-policy.yamlnew file mode 100644index 0000000000..5db79aa6e7--- /dev/null+++ b/jiuwenbox/src/jiuwenbox/configs/java-policy.yaml@@ -0,0 +1,211 @@+# Java-ready sandbox policy.+#+# Predecessor of code-agent-policy but tuned for running OpenJDK 17 inside the+# sandbox: exposes the image-installed JDK (read-only via /usr), gives Java a+# writable /tmp (class output, hsperfdata) and /home (sources/jars/classes),+# injects JAVA_HOME/PATH, and applies conservative per-sandbox cgroup limits.+#+# Path model (jiuwenbox has NO /workspace; SANDBOX_WORKSPACE is host-side+# backing storage only). Conventional writable layout under /home:+# /home/src Java source files (uploaded or written via exec stdin)+# /home/jars uploaded dependency jars+# /home/classes javac -d output+# These sub-directories are created at runtime (mkdir -p); the policy only+# declares the writable roots /home and /tmp.+#+# Network is isolated with deny-by-default egress/ingress (no outbound): Java+# code cannot download dependencies or phone home. Validation emits a warning+# ("no outbound connectivity") which is intentional.+#+# Pair with the JDK-enabled image (Dockerfile installs java-17-openjdk-headless+# + java-17-openjdk-devel, JAVA_HOME=/usr/lib/jvm/java-17-openjdk).++version: 1++name: "java"++# Injected into every process inside the sandbox. JAVA_HOME points at the+# stable version-independent symlink; PATH prepends $JAVA_HOME/bin so+# java/javac/jar resolve to the JDK (alternatives symlinks in /usr/bin also+# work, but this makes the JDK authoritative).+environment:+ JAVA_HOME: "/usr/lib/jvm/java-17-openjdk"+ PATH: "/usr/lib/jvm/java-17-openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"++filesystem_policy:+ # Writable roots. /tmp 1777 for class output + JVM hsperfdata; /home 0777+ # for sources/jars/classes. Both are server-managed backing dirs bind-mounted+ # rw (they override any read-only view of the same paths).+ directories:+ - path: "/home"+ permissions: "0777"+ - path: "/tmp"+ permissions: "1777"+ files: []++ read_only:+ - "/"+ - "/bin"+ - "/sbin"+ - "/usr"+ - "/lib"+ - "/lib64"+ - "/etc"+ - "/opt"++ read_write:+ - "/home"+ - "/tmp"++ # Mount every immediate child of host_root "/" read-only. This exposes the+ # image's /usr (JDK at /usr/lib/jvm/java-17-openjdk), /bin, /lib, /lib64,+ # /etc (incl. /etc/alternatives — required because JAVA_HOME and+ # /usr/bin/{java,javac,jar} are alternatives symlinks that chain through+ # /etc/alternatives to the versioned JDK dir; without /etc/alternatives the+ # symlinks break and `java` is "command not found"), /etc/java-17-openjdk+ # (JVM security/config), /opt, etc. — all read-only.+ #+ # /home and /tmp declared above are re-bound rw on top of this ro view+ # (bwrap applies rw binds after ro binds, so the rw override wins). /proc and+ # /dev are bwrap-managed tmpfs (bind_root_entries skips /proc, /dev targets).+ bind_mounts: []+ bind_root_entries:+ - host_root: "/"+ sandbox_path: "/"+ mode: "ro"++ device:+ - host_path: "/dev/null"+ sandbox_path: "/dev/null"+ - host_path: "/dev/random"+ sandbox_path: "/dev/random"+ - host_path: "/dev/urandom"+ sandbox_path: "/dev/urandom"++process:+ # 'sandbox' user does not exist in the openEuler image; bwrap falls back to+ # uid/gid 65534 (nobody). The writable backing dirs are chown'd to that uid.+ run_as_user: sandbox+ run_as_group: sandbox++namespace:+ user: true+ pid: true+ ipc: true+ cgroup: true+ uts: true++capabilities:+ add: []+ drop: []++landlock:+ compatibility: best_effort++# Seccomp hardening: the same blocked list as default-policy.yaml (verified+# 2026-07-03 on 205 — JDK 17 e2e A-E all PASS under this list; seccomp filter+# confirmed active via EPERM on ptrace/perf_event_open/io_uring_setup, see+# docs/jiuwenbox-java-test-plan.md T5.4 / design §6.3). JDK 17 does not use+# io_uring; ptrace/perf_event_open blocking only disables jstack/JVMTI attach+# and JFR perf counters, which P0 does not require. clone/clone3 (thread+# creation) are NOT blocked.+syscall:+ x86_64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"+ arm64:+ blocked:+ - "kexec_load"+ - "kexec_file_load"+ - "reboot"+ - "pivot_root"+ - "swapon"+ - "swapoff"+ - "nfsservctl"+ - "lookup_dcookie"+ - "ptrace"+ - "mount"+ - "umount2"+ - "unshare"+ - "setns"+ - "userfaultfd"+ - "perf_event_open"+ - "bpf"+ - "add_key"+ - "request_key"+ - "keyctl"+ - "io_uring_setup"+ - "io_uring_enter"+ - "io_uring_register"+ - "open_by_handle_at"+ - "name_to_handle_at"+ - "init_module"+ - "finit_module"+ - "delete_module"+ - "acct"++# Isolated network namespace with deny-by-default egress + ingress: Java code+# has no outbound connectivity (no dependency download, no network egress).+# uplink is configured (veth + NAT) so the netns is well-formed, but egress+# deny-all blocks all OUTPUT. Validation warns about no outbound — intentional.+network:+ mode: isolated+ uplink:+ nat: true+ interface: ""+ egress:+ default: deny+ allowed_domains: []+ blocked_domains: []+ allowed_ips: []+ blocked_ips: []+ allowed_ports: []+ blocked_ports: []+ ingress:+ default: deny+ allowed_domains: []+ blocked_domains: []+ allowed_ips: []+ blocked_ips: []+ allowed_ports: []+ blocked_ports: []++# Conservative per-sandbox cgroup defaults. memory_max is the hard process-group+# cap (covers JVM non-heap: metaspace, thread stacks, JIT, direct memory); JVM+# -Xmx is NOT set here, so the JVM picks a heap based on the cgroup limit.+# cpu_max = 1 core, pids_max = 128 (caps thread/fork storms). All three are+# enforced by supervisor/cgroup.py (v2 preferred, v1 fallback).+cgroup:+ memory_max: "512M"+ cpu_max: 1.0+ pids_max: 128++# Idle reaping left at defaults (disabled).+timeout: {}diff --git a/jiuwenbox/tests/integration/test_java_e2e.py b/jiuwenbox/tests/integration/test_java_e2e.pynew file mode 100644index 0000000000..1021ff9bea--- /dev/null+++ b/jiuwenbox/tests/integration/test_java_e2e.py@@ -0,0 +1,206 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+"""Java end-to-end integration tests.++Run against a jiuwenbox server loaded with ``configs/java-policy.yaml``:++ python3 -m pytest tests/integration/test_java_e2e.py -v \+ --server-endpoint http://127.0.0.1:8321++The tests reuse the shared ``client`` fixture (httpx, TCP/UDS aware) from+``conftest.py``. They auto-skip when Java is not available in the sandbox+(e.g. the server runs an image without the JDK), so the file is safe to run+against any server endpoint.+"""++from __future__ import annotations++import base64++import pytest+++def _exec(client, sandbox_id: str, command: list[str], *, stdin: str | None = None,+ timeout: int = 30, env: dict[str, str] | None = None) -> dict:+ body: dict = {"command": command, "timeout_seconds": timeout}+ if stdin is not None:+ body["stdin"] = stdin+ if env is not None:+ body["env"] = env+ resp = client.post(f"/api/v1/sandboxes/{sandbox_id}/exec", json=body)+ assert resp.status_code == 200, f"exec failed: {resp.status_code} {resp.text}"+ return resp.json()+++def _write_file(client, sandbox_id: str, sandbox_path: str, content: str) -> None:+ b64 = base64.b64encode(content.encode()).decode()+ parent = sandbox_path.rsplit("/", 1)[0] or "/"+ out = _exec(client, sandbox_id,+ ["sh", "-c", f"mkdir -p {parent} && base64 -d > {sandbox_path}"],+ stdin=b64)+ assert out["exit_code"] == 0, f"write {sandbox_path} failed: {out}"+++def _java_available(client, sandbox_id: str) -> bool:+ try:+ out = _exec(client, sandbox_id, ["java", "-version"], timeout=15)+ return out["exit_code"] == 0+ except Exception:+ # Catch network errors (httpx.ConnectError/TimeoutException) and JSON+ # parse errors too, not just the AssertionError from _exec's status+ # check — so an unreachable server makes the test skip (via the caller's+ # pytest.skip) instead of crashing with an unhandled exception.+ return False+++def java_sandbox(client):+ """Create one sandbox per test; auto-cleaned by the (function-scoped) client fixture.++ Note: must stay function-scoped to match ``client`` in conftest.py. A wider+ scope (e.g. module) raises pytest ScopeMismatch (module cannot depend on a+ function-scoped fixture) and would also have its sandbox torn down by the+ first test's ``client`` teardown via ``cleanup_sandboxes()``.+ """+ try:+ resp = client.post("/api/v1/sandboxes", json={})+ assert resp.status_code == 201, f"create failed: {resp.status_code} {resp.text}"+ sb = resp.json()["id"]+ except Exception as e:+ # Server unreachable / non-JSON / wrong status: skip instead of crashing+ # the whole file. Catches httpx.ConnectError/TimeoutException etc. so a+ # dead endpoint yields SKIPPED, not ERROR.+ pytest.skip(f"jiuwenbox server not usable: {e!r}")+ if not _java_available(client, sb):+ pytest.skip("java not available in sandbox (image without JDK?)")+ return sb+++def test_a_policy_smoke(client, java_sandbox):+ """A. java/javac/jar versions + JAVA_HOME injection."""+ for cmd in (["java", "-version"], ["javac", "-version"], ["jar", "--version"]):+ out = _exec(client, java_sandbox, cmd, timeout=15)+ assert out["exit_code"] == 0, f"{' '.join(cmd)} failed: {out['stderr']}"++ out = _exec(client, java_sandbox, ["sh", "-c", "echo $JAVA_HOME"], timeout=10)+ assert out["stdout"].strip() == "/usr/lib/jvm/java-17-openjdk", out+++MAIN_JAVA = """+public class Main {+ public static void main(String[] args) {+ System.out.println("JIUWENBOX-JAVA-E2E-MAIN");+ }+}+"""++LIB_JAVA = """+package lib;+public class Lib {+ public static String greeting() { return "JIUWENBOX-JAVA-E2E-LIB"; }+}+"""++MAIN_WITH_LIB_JAVA = """+import lib.Lib;+public class MainWithLib {+ public static void main(String[] args) {+ System.out.println(Lib.greeting());+ }+}+"""+++def test_b_single_file_compile_and_run(client, java_sandbox):+ """B. upload Main.java -> javac -> java, expect fixed string."""+ _write_file(client, java_sandbox, "/home/src/Main.java", MAIN_JAVA)++ out = _exec(client, java_sandbox, ["javac", "-d", "/home/classes", "/home/src/Main.java"])+ assert out["exit_code"] == 0, f"javac failed: {out['stderr']}"++ out = _exec(client, java_sandbox, ["java", "-cp", "/home/classes", "Main"], timeout=15)+ assert out["stdout"].strip() == "JIUWENBOX-JAVA-E2E-MAIN", out+++def test_c_jar_classpath(client, java_sandbox):+ """C. build a lib jar, compile MainWithLib against it, run via -cp jars:classes."""+ _write_file(client, java_sandbox, "/home/src/Lib.java", LIB_JAVA)+ _write_file(client, java_sandbox, "/home/src/MainWithLib.java", MAIN_WITH_LIB_JAVA)++ # lib-classes is an intermediate scratch dir used only to build the jar.+ # Put it under /tmp (not /home): in some sandboxes a mkdir'd subdir under+ # /home becomes an overlay mount point, making `rm -rf` fail with EBUSY.+ # /tmp has no such quirk, and the jar output still lands in /home/jars.+ build = (+ "mkdir -p /tmp/lib-classes /home/jars /home/classes "+ "&& javac -d /tmp/lib-classes /home/src/Lib.java "+ "&& jar cf /home/jars/hello-lib.jar -C /tmp/lib-classes . "+ "&& rm -rf /tmp/lib-classes"+ )+ out = _exec(client, java_sandbox, ["sh", "-c", build])+ assert out["exit_code"] == 0, f"jar build failed: {out['stderr']}"++ out = _exec(client, java_sandbox,+ ["javac", "-cp", "/home/jars/hello-lib.jar", "-d", "/home/classes",+ "/home/src/MainWithLib.java"])+ assert out["exit_code"] == 0, f"javac MainWithLib failed: {out['stderr']}"++ out = _exec(client, java_sandbox,+ ["java", "-cp", "/home/jars/*:/home/classes", "MainWithLib"], timeout=15)+ assert out["stdout"].strip() == "JIUWENBOX-JAVA-E2E-LIB", out+++def test_d_tmp_writable(client, java_sandbox):+ """D. /tmp is writable; JVM hsperfdata does not break basic run."""+ out = _exec(client, java_sandbox,+ ["sh", "-c", "echo ok > /tmp/jb_writable_test && cat /tmp/jb_writable_test"])+ assert out["stdout"].strip() == "ok", out++ # Running java exercises /tmp/hsperfdata_<user>; just assert it does not+ # error (some JVM configs disable perf data, so presence is not asserted).+ out = _exec(client, java_sandbox,+ ["sh", "-c", "java -version 2>/dev/null; ls /tmp/hsperfdata_* 2>/dev/null | head -1 || true"],+ timeout=15)+ assert out["exit_code"] == 0, out+++BUSY_JAVA = """+public class Busy {+ public static void main(String[] args) {+ long t = System.currentTimeMillis() + 60000;+ while (System.currentTimeMillis() < t) { Math.sqrt(Math.random()); }+ }+}+"""++OOM_JAVA = """+import java.util.*;+public class Oom {+ public static void main(String[] args) {+ List<byte[]> list = new ArrayList<>();+ while (true) { list.add(new byte[8 * 1024 * 1024]); }+ }+}+"""+++def test_e1_busy_loop_timeout(client, java_sandbox):+ """E1. busy loop is terminated by timeout_seconds (exit != 0)."""+ _write_file(client, java_sandbox, "/home/src/Busy.java", BUSY_JAVA)+ out = _exec(client, java_sandbox, ["javac", "-d", "/home/classes", "/home/src/Busy.java"])+ assert out["exit_code"] == 0, f"javac Busy failed: {out['stderr']}"+ out = _exec(client, java_sandbox, ["java", "-cp", "/home/classes", "Busy"], timeout=3)+ assert out["exit_code"] != 0, f"busy loop not stopped: {out}"+++def test_e2_oom_failure_and_server_healthy(client, java_sandbox):+ """E2. heap OOM exits non-zero; server stays healthy afterwards."""+ _write_file(client, java_sandbox, "/home/src/Oom.java", OOM_JAVA)+ out = _exec(client, java_sandbox, ["javac", "-d", "/home/classes", "/home/src/Oom.java"])+ assert out["exit_code"] == 0, f"javac Oom failed: {out['stderr']}"+ out = _exec(client, java_sandbox, ["java", "-Xmx128m", "-cp", "/home/classes", "Oom"],+ timeout=30)+ assert out["exit_code"] != 0, f"OOM did not fail: {out}"++ # Server must still respond.+ resp = client.get("/health")+ assert resp.status_code == 200, f"server unhealthy after OOM: {resp.status_code}"diff --git a/jiuwenbox/tests/manual/e2e_java.sh b/jiuwenbox/tests/manual/e2e_java.shnew file mode 100755index 0000000000..4a00e77376--- /dev/null+++ b/jiuwenbox/tests/manual/e2e_java.sh@@ -0,0 +1,196 @@+#!/usr/bin/env bash+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+#+# Java end-to-end verification against a RUNNING jiuwenbox server loaded with+# configs/java-policy.yaml. Uses only curl + jq + base64 (no Python deps), so+# it runs on the 205 build host directly.+#+# It does NOT start the server. Start one first, e.g. on 205:+# cd jiuwenswarm/jiuwenbox+# bash scripts/build_docker.sh+# bash scripts/run_docker.sh src/jiuwenbox/configs/java-policy.yaml+# bash tests/manual/e2e_java.sh+#+# Usage:+# ./tests/manual/e2e_java.sh # http://127.0.0.1:8321+# ENDPOINT=http://127.0.0.1:18321 ./tests/manual/e2e_java.sh+#+# Exit code: 0 if all checks pass, non-zero otherwise.+set -euo pipefail++ENDPOINT="${ENDPOINT:-http://127.0.0.1:8321}"+JQ="${JQ:-jq}"+FAIL=0++# Per-run temp dir so concurrent runs (or a stale leftover) don't collide on+# fixed paths like /tmp/jb_Main.java. Cleaned up on exit.+WORK="$(mktemp -d -t jbw-e2e-XXXXXX)"+trap 'rm -rf "${WORK}"' EXIT++note() { printf '\n===== %s =====\n' "$1"; }+pass() { echo "PASS $1"; }+fail() { echo "FAIL $1"; FAIL=1; }++# Create a sandbox and echo its id. The server must be loaded with java-policy+# so the sandbox inherits JAVA_HOME/PATH/cgroup.+create_sandbox() {+ curl -sS -X POST "${ENDPOINT}/api/v1/sandboxes" -H 'Content-Type: application/json' \+ -d '{}' | "${JQ}" -r .id+}++# exec a command in the sandbox. Args: sandbox_id, then a JSON string for the+# request body. Prints the response JSON.+exec_cmd() {+ local sb="$1"; shift+ local body="$1"; shift+ curl -sS -X POST "${ENDPOINT}/api/v1/sandboxes/${sb}/exec" \+ -H 'Content-Type: application/json' -d "${body}"+}++# Write a file inside the sandbox by base64-encoding local content and decoding+# on the sandbox side via exec stdin. Args: sandbox_id, sandbox_path, local_file.+write_file() {+ local sb="$1" path="$2" local="$3"+ local b64+ b64=$(base64 -w0 "${local}")+ local dir+ dir=$(dirname "${path}")+ exec_cmd "${sb}" "{\"command\":[\"sh\",\"-c\",\"mkdir -p ${dir} && base64 -d > ${path}\"],\"stdin\":\"${b64}\"}" \+ | "${JQ}" -e '.exit_code == 0' >/dev/null+}++SB=$(create_sandbox)+echo "sandbox: ${SB}"++# ---------------------------------------------------------------------------+note "A. policy smoke (java/javac/jar/JAVA_HOME)"+# ---------------------------------------------------------------------------+for c in "java -version" "javac -version" "jar --version"; do+ out=$(exec_cmd "${SB}" "{\"command\":[\"sh\",\"-c\",\"${c}\"],\"timeout_seconds\":15}")+ code=$(echo "${out}" | "${JQ}" -r .exit_code)+ if [[ "${code}" == "0" ]]; then pass "${c}"; else fail "${c} (exit=${code}): $(echo "${out}" | "${JQ}" -r .stderr)"; fi+done+jh=$(exec_cmd "${SB}" '{"command":["sh","-c","echo $JAVA_HOME"],"timeout_seconds":10}' | "${JQ}" -r .stdout | tr -d '\n')+if [[ "${jh}" == "/usr/lib/jvm/java-17-openjdk" ]]; then pass "JAVA_HOME=${jh}"; else fail "JAVA_HOME=${jh} (expected /usr/lib/jvm/java-17-openjdk)"; fi++# ---------------------------------------------------------------------------+note "B. single-file Java: compile + run"+# ---------------------------------------------------------------------------+cat > "${WORK}/jb_Main.java" <<'JAVA'+public class Main {+ public static void main(String[] args) {+ System.out.println("JIUWENBOX-JAVA-E2E-MAIN");+ }+}+JAVA+write_file "${SB}" /home/src/Main.java "${WORK}/jb_Main.java" \+ && pass "upload /home/src/Main.java" || fail "upload /home/src/Main.java"++out=$(exec_cmd "${SB}" '{"command":["javac","-d","/home/classes","/home/src/Main.java"],"timeout_seconds":30}')+[[ "$(echo "${out}" | "${JQ}" -r .exit_code)" == "0" ]] && pass "javac Main.java" || fail "javac Main.java: $(echo "${out}" | "${JQ}" -r .stderr)"++out=$(exec_cmd "${SB}" '{"command":["java","-cp","/home/classes","Main"],"timeout_seconds":15}')+res=$(echo "${out}" | "${JQ}" -r .stdout | tr -d '\n')+[[ "${res}" == "JIUWENBOX-JAVA-E2E-MAIN" ]] && pass "java Main -> ${res}" || fail "java Main -> '${res}' (exit=$(echo "${out}" | "${JQ}" -r .exit_code))"++# ---------------------------------------------------------------------------+note "C. jar + classpath"+# ---------------------------------------------------------------------------+cat > "${WORK}/jb_Lib.java" <<'JAVA'+package lib;+public class Lib {+ public static String greeting() { return "JIUWENBOX-JAVA-E2E-LIB"; }+}+JAVA+cat > "${WORK}/jb_MainWithLib.java" <<'JAVA'+import lib.Lib;+public class MainWithLib {+ public static void main(String[] args) {+ System.out.println(Lib.greeting());+ }+}+JAVA+write_file "${SB}" /home/src/Lib.java "${WORK}/jb_Lib.java" || fail "upload Lib.java"+write_file "${SB}" /home/src/MainWithLib.java "${WORK}/jb_MainWithLib.java" || fail "upload MainWithLib.java"++# Compile Lib into a separate classes dir, jar it, then remove the loose class+# so MainWithLib can only resolve Lib via the jar. lib-classes goes under /tmp+# (not /home): in some sandboxes a mkdir'd subdir under /home becomes an overlay+# mount point, making `rm -rf` fail with EBUSY. /tmp has no such quirk; the jar+# output still lands in /home/jars.+exec_cmd "${SB}" '{"command":["sh","-c","mkdir -p /tmp/lib-classes /home/jars /home/classes && javac -d /tmp/lib-classes /home/src/Lib.java && jar cf /home/jars/hello-lib.jar -C /tmp/lib-classes . && rm -rf /tmp/lib-classes"],"timeout_seconds":30}' \+ | "${JQ}" -e '.exit_code == 0' >/dev/null && pass "build hello-lib.jar" || fail "build hello-lib.jar"++out=$(exec_cmd "${SB}" '{"command":["javac","-cp","/home/jars/hello-lib.jar","-d","/home/classes","/home/src/MainWithLib.java"],"timeout_seconds":30}')+[[ "$(echo "${out}" | "${JQ}" -r .exit_code)" == "0" ]] && pass "javac MainWithLib.java (-cp jar)" || fail "javac MainWithLib.java: $(echo "${out}" | "${JQ}" -r .stderr)"++out=$(exec_cmd "${SB}" '{"command":["java","-cp","/home/jars/*:/home/classes","MainWithLib"],"timeout_seconds":15}')+res=$(echo "${out}" | "${JQ}" -r .stdout | tr -d '\n')+[[ "${res}" == "JIUWENBOX-JAVA-E2E-LIB" ]] && pass "java -cp jars:classes MainWithLib -> ${res}" || fail "jar classpath run -> '${res}' (exit=$(echo "${out}" | "${JQ}" -r .exit_code), stderr=$(echo "${out}" | "${JQ}" -r .stderr))"++# ---------------------------------------------------------------------------+note "D. /tmp writable + JVM hsperfdata"+# ---------------------------------------------------------------------------+out=$(exec_cmd "${SB}" '{"command":["sh","-c","echo ok > /tmp/jb_writable_test && cat /tmp/jb_writable_test"],"timeout_seconds":10}')+[[ "$(echo "${out}" | "${JQ}" -r .stdout | tr -d '\n')" == "ok" ]] && pass "/tmp shell write" || fail "/tmp shell write"+# Running java already exercises /tmp/hsperfdata_<user>; verify the dir exists+# after a java invocation (JVM writes perf data there). If absent, JVM still+# ran (some configs disable it), so only soft-check.+out=$(exec_cmd "${SB}" '{"command":["sh","-c","java -version 2>/dev/null; ls /tmp/hsperfdata_* 2>/dev/null | head -1 || true"],"timeout_seconds":15}')+echo "hsperfdata check: $(echo "${out}" | "${JQ}" -r .stdout)"+pass "/tmp hsperfdata (soft, java ran)"++# ---------------------------------------------------------------------------+note "E. resource limits (best-effort)"+# ---------------------------------------------------------------------------+# E1: timeout enforcement — busy loop killed at timeout_seconds.+cat > "${WORK}/jb_Busy.java" <<'JAVA'+public class Busy {+ public static void main(String[] args) {+ long t = System.currentTimeMillis() + 60000;+ while (System.currentTimeMillis() < t) { Math.sqrt(Math.random()); }+ }+}+JAVA+write_file "${SB}" /home/src/Busy.java "${WORK}/jb_Busy.java" || fail "upload Busy.java"+out=$(exec_cmd "${SB}" '{"command":["javac","-d","/home/classes","/home/src/Busy.java"],"timeout_seconds":30}')+[[ "$(echo "${out}" | "${JQ}" -r .exit_code)" == "0" ]] && pass "javac Busy.java" || fail "javac Busy.java"+out=$(exec_cmd "${SB}" '{"command":["java","-cp","/home/classes","Busy"],"timeout_seconds":3}')+code=$(echo "${out}" | "${JQ}" -r .exit_code)+# exit 124 = jiuwenbox timeout; non-zero also acceptable (cgroup/oom). Zero = bad.+if [[ "${code}" != "0" ]]; then pass "busy loop terminated (exit=${code})"; else fail "busy loop was NOT stopped (exit=0)"; fi++# E2: memory failure — heap OOM with -Xmx128m. Should exit non-zero; server+# must stay healthy afterwards. (cgroup memory_max 512M is the outer cap; this+# exercises JVM-internal OOM, not cgroup kill. cgroup kill verification is+# manual, see docs/jiuwenbox-java-test-plan.md T4.)+cat > "${WORK}/jb_Oom.java" <<'JAVA'+import java.util.*;+public class Oom {+ public static void main(String[] args) {+ List<byte[]> list = new ArrayList<>();+ while (true) { list.add(new byte[8 * 1024 * 1024]); }+ }+}+JAVA+write_file "${SB}" /home/src/Oom.java "${WORK}/jb_Oom.java" || fail "upload Oom.java"+exec_cmd "${SB}" '{"command":["javac","-d","/home/classes","/home/src/Oom.java"],"timeout_seconds":30}' | "${JQ}" -e '.exit_code == 0' >/dev/null && pass "javac Oom.java" || fail "javac Oom.java"+out=$(exec_cmd "${SB}" '{"command":["java","-Xmx128m","-cp","/home/classes","Oom"],"timeout_seconds":30}')+code=$(echo "${out}" | "${JQ}" -r .exit_code)+if [[ "${code}" != "0" ]]; then pass "OOM java exited non-zero (exit=${code})"; else fail "OOM java did not fail (exit=0)"; fi++# Server health after resource tests.+hc=$(curl -sS -o /dev/null -w '%{http_code}' "${ENDPOINT}/health")+[[ "${hc}" == "200" ]] && pass "server healthy after resource tests (HTTP ${hc})" || fail "server unhealthy (HTTP ${hc})"++# ---------------------------------------------------------------------------+# Cleanup+# ---------------------------------------------------------------------------+curl -sS -X DELETE "${ENDPOINT}/api/v1/sandboxes/${SB}" -o /dev/null -w 'delete: %{http_code}\n'++note "summary"+if [[ "${FAIL}" -ne 0 ]]; then+ echo "Java e2e FAILED"+ exit 1+fi+echo "Java e2e PASSED"