ARTEX/sandbox/docker.go
BaaRai dc75d58f98
Merge pull request #825 from UknownPerson/codex/fix-docker-worker-recovery
fix(sandbox): start recovered Docker workers before exec
2026-12-02 16:24:24 +01:00

976 lines
31 KiB
Go

package sandbox
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
)
// DockerConfig configures the DockerBackend for artex-runner.
type DockerConfig struct {
SocketPath string // default /var/run/docker.sock
WorkerImage string // default artex-worker:local
ProxyImage string // default artex-egress-proxy:local
WorkspaceRoot string // panel/runner path, default /app/data/tasks
HostWorkspaceRoot string // host path used in Docker bind mounts (defaults to WorkspaceRoot)
AuditRoot string // proxy-only egress audit log dir (never mounted into worker)
HostAuditRoot string // host path used in Docker bind mounts for AuditRoot
TaskNetPrefix string // default artex-task-
EgressNet string // default egress-net
}
type taskContainers struct {
taskID string
workerID string
proxyID string
netName string
scopeHash string
// cleanupMu serializes creation, recovery on exec, and cleanup for this task.
// Commands may execute concurrently, but lifecycle changes share this lock.
cleanupMu sync.Mutex
}
// cleanupTimeout bounds Docker calls that must still complete after the
// caller's request context is gone (a paused or deleted task). Cleanup never
// inherits cancellation: a cancelled request must not turn into a silent no-op
// while a worker or proxy keeps running.
const cleanupTimeout = 30 * time.Second
// cleanupContext detaches from ctx cancellation and applies a fresh bound.
func cleanupContext(ctx context.Context) (context.Context, context.CancelFunc) {
if ctx == nil {
ctx = context.Background()
}
return context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
}
// DockerBackend implements Backend using Docker Engine's Unix socket REST API.
type DockerBackend struct {
cfg DockerConfig
http *http.Client
mu sync.Mutex
tasks map[string]*taskContainers
}
// NewDockerBackend creates a DockerBackend talking to cfg.SocketPath.
func NewDockerBackend(cfg DockerConfig) *DockerBackend {
if cfg.SocketPath == "" {
cfg.SocketPath = "/var/run/docker.sock"
}
if cfg.WorkerImage == "" {
cfg.WorkerImage = DefaultWorkerImage
}
if cfg.ProxyImage == "" {
cfg.ProxyImage = DefaultProxyImage
}
if cfg.WorkspaceRoot == "" {
cfg.WorkspaceRoot = DefaultWorkspaceRoot
}
if cfg.HostWorkspaceRoot == "" {
cfg.HostWorkspaceRoot = cfg.WorkspaceRoot
}
if cfg.AuditRoot == "" {
cfg.AuditRoot = DefaultAuditRoot
}
if cfg.HostAuditRoot == "" {
cfg.HostAuditRoot = cfg.AuditRoot
}
if cfg.TaskNetPrefix == "" {
cfg.TaskNetPrefix = DefaultTaskNetPrefix
}
if cfg.EgressNet == "" {
cfg.EgressNet = DefaultEgressNet
}
sock := cfg.SocketPath
tr := &http.Transport{
Proxy: nil,
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "unix", sock)
},
}
return &DockerBackend{
cfg: cfg,
http: &http.Client{Transport: tr},
tasks: map[string]*taskContainers{},
}
}
func (b *DockerBackend) dockerDo(ctx context.Context, method, path string, body any) (*http.Response, error) {
var r io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return nil, err
}
r = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+path, r)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := b.http.Do(req)
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrDockerUnavailable, err)
}
return resp, nil
}
// Ping verifies the Docker daemon is reachable.
func (b *DockerBackend) Ping(ctx context.Context) error {
resp, err := b.dockerDo(ctx, http.MethodGet, "/_ping", nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("%w: ping HTTP %d", ErrDockerUnavailable, resp.StatusCode)
}
return nil
}
// WorkerCount returns the number of tracked task workers.
func (b *DockerBackend) WorkerCount() int {
b.mu.Lock()
defer b.mu.Unlock()
return len(b.tasks)
}
// Recover discovers existing runner-created containers by label on startup.
// It strictly filters by artex.managed_by=artex-runner so it never adopts foreign containers.
func (b *DockerBackend) Recover(ctx context.Context) (int, error) {
filters, _ := json.Marshal(map[string][]string{
"label": {LabelManagedBy + "=" + ManagedByRunner},
})
resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/json?all=true&filters="+url.QueryEscape(string(filters)), nil)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return 0, fmt.Errorf("%w: list containers HTTP %d: %s", ErrDockerUnavailable, resp.StatusCode, string(raw))
}
var list []struct {
ID string `json:"Id"`
Labels map[string]string `json:"Labels"`
State string `json:"State"`
}
if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
return 0, err
}
b.mu.Lock()
defer b.mu.Unlock()
for _, c := range list {
if c.Labels[LabelManagedBy] != ManagedByRunner {
continue
}
tid := c.Labels[LabelTask]
if ValidateTaskID(tid) != nil {
continue
}
tc := b.tasks[tid]
if tc == nil {
tc = &taskContainers{taskID: tid, netName: b.cfg.TaskNetPrefix + tid}
b.tasks[tid] = tc
}
switch c.Labels[LabelComponent] {
case ComponentWorker:
tc.workerID = c.ID
case ComponentProxy:
tc.proxyID = c.ID
}
}
return len(b.tasks), nil
}
func (b *DockerBackend) ensureNetwork(ctx context.Context, name string, internal bool, taskID string) error {
resp, err := b.dockerDo(ctx, http.MethodGet, "/networks/"+url.PathEscape(name), nil)
if err != nil {
return err
}
if resp.StatusCode == http.StatusOK {
var existing struct {
Internal bool `json:"Internal"`
Labels map[string]string `json:"Labels"`
}
derr := json.NewDecoder(resp.Body).Decode(&existing)
resp.Body.Close()
if derr != nil {
return fmt.Errorf("inspect existing network %s: %w", name, derr)
}
if internal && !existing.Internal {
return fmt.Errorf("existing network %s is not internal=true (refusing to attach worker)", name)
}
if taskID != "" {
if existing.Labels[LabelManagedBy] != ManagedByRunner || existing.Labels[LabelTask] != taskID {
return fmt.Errorf("existing task network %s has untrusted labels %v (refusing to attach worker)", name, existing.Labels)
}
}
return nil
}
resp.Body.Close()
labels := map[string]string{LabelManagedBy: ManagedByRunner}
if taskID != "" {
labels[LabelTask] = taskID
}
payload := map[string]any{
"Name": name,
"CheckDuplicate": true,
"Driver": "bridge",
"Internal": internal,
"Labels": labels,
}
cresp, err := b.dockerDo(ctx, http.MethodPost, "/networks/create", payload)
if err != nil {
return err
}
defer cresp.Body.Close()
if cresp.StatusCode >= 300 && cresp.StatusCode != http.StatusConflict {
raw, _ := io.ReadAll(io.LimitReader(cresp.Body, 4096))
return fmt.Errorf("create network %s: HTTP %d: %s", name, cresp.StatusCode, string(raw))
}
return nil
}
func (b *DockerBackend) connectNetwork(ctx context.Context, netName, containerID string) error {
resp, err := b.dockerDo(ctx, http.MethodPost, "/networks/"+url.PathEscape(netName)+"/connect", map[string]any{
"Container": containerID,
})
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
if strings.Contains(string(raw), "already exists") {
return nil
}
return fmt.Errorf("connect %s to %s: HTTP %d: %s", containerID, netName, resp.StatusCode, string(raw))
}
return nil
}
// removeNetwork deletes one task network. A 404 proves the network is already
// absent and therefore counts as success; every transport or non-2xx failure is
// returned so cleanup cannot report success while the network survives.
func (b *DockerBackend) removeNetwork(ctx context.Context, name string) error {
if name == "" {
return nil
}
resp, err := b.dockerDo(ctx, http.MethodDelete, "/networks/"+url.PathEscape(name), nil)
if err != nil {
return fmt.Errorf("remove network %s: %w", name, err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil
}
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("remove network %s: HTTP %d: %s", name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
return nil
}
// removeContainer force-deletes one container. As with removeNetwork, 404 means
// the container is proven absent, and every other failure is reported.
func (b *DockerBackend) removeContainer(ctx context.Context, idOrName string) error {
if idOrName == "" {
return nil
}
resp, err := b.dockerDo(ctx, http.MethodDelete, "/containers/"+url.PathEscape(idOrName)+"?force=true&v=true", nil)
if err != nil {
return fmt.Errorf("remove container %s: %w", idOrName, err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil
}
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("remove container %s: HTTP %d: %s", idOrName, resp.StatusCode, strings.TrimSpace(string(raw)))
}
return nil
}
func (b *DockerBackend) startContainer(ctx context.Context, id string) error {
resp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(id)+"/start", nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 && resp.StatusCode != http.StatusNotModified {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("start container %s: HTTP %d: %s", id, resp.StatusCode, string(raw))
}
return nil
}
func (b *DockerBackend) createContainer(ctx context.Context, name string, spec map[string]any) (string, error) {
resp, err := b.dockerDo(ctx, http.MethodPost, "/containers/create?name="+url.QueryEscape(name), spec)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return "", fmt.Errorf("create container %s: HTTP %d: %s", name, resp.StatusCode, string(raw))
}
var out struct {
ID string `json:"Id"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return "", err
}
return out.ID, nil
}
func (b *DockerBackend) resolveHostWorkspaceRoot(ctx context.Context) string {
if filepath.IsAbs(b.cfg.HostWorkspaceRoot) && b.cfg.HostWorkspaceRoot != b.cfg.WorkspaceRoot {
return b.cfg.HostWorkspaceRoot
}
// When running inside Docker (artex-runner container), inspect our own container
// mounts via the Docker API to discover the exact host path backing WorkspaceRoot.
hostname, err := os.Hostname()
if err == nil && hostname != "" {
resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+url.PathEscape(hostname)+"/json", nil)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var info struct {
Mounts []struct {
Source string `json:"Source"`
Destination string `json:"Destination"`
} `json:"Mounts"`
}
if json.NewDecoder(resp.Body).Decode(&info) == nil {
cleanWS := filepath.Clean(b.cfg.WorkspaceRoot)
for _, m := range info.Mounts {
if filepath.Clean(m.Destination) == cleanWS && m.Source != "" {
b.cfg.HostWorkspaceRoot = m.Source
return m.Source
}
}
}
}
}
}
if abs, err := filepath.Abs(b.cfg.HostWorkspaceRoot); err == nil {
return abs
}
return b.cfg.HostWorkspaceRoot
}
func (b *DockerBackend) resolveHostAuditRoot(ctx context.Context) string {
if filepath.IsAbs(b.cfg.HostAuditRoot) && b.cfg.HostAuditRoot != b.cfg.AuditRoot {
return b.cfg.HostAuditRoot
}
hostname, err := os.Hostname()
if err == nil && hostname != "" {
resp, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+url.PathEscape(hostname)+"/json", nil)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
var info struct {
Mounts []struct {
Source string `json:"Source"`
Destination string `json:"Destination"`
} `json:"Mounts"`
}
if json.NewDecoder(resp.Body).Decode(&info) == nil {
cleanAudit := filepath.Clean(b.cfg.AuditRoot)
for _, m := range info.Mounts {
if filepath.Clean(m.Destination) == cleanAudit && m.Source != "" {
b.cfg.HostAuditRoot = m.Source
return m.Source
}
}
}
}
}
}
if abs, err := filepath.Abs(b.cfg.HostAuditRoot); err == nil {
return abs
}
return b.cfg.HostAuditRoot
}
func (b *DockerBackend) hostTaskDir(ctx context.Context, taskID string) string {
return filepath.Join(b.resolveHostWorkspaceRoot(ctx), taskID)
}
func (b *DockerBackend) localTaskDir(taskID string) string {
return filepath.Join(b.cfg.WorkspaceRoot, taskID)
}
func (b *DockerBackend) hostAuditDir(ctx context.Context, taskID string) string {
return filepath.Join(b.resolveHostAuditRoot(ctx), taskID)
}
func (b *DockerBackend) localAuditDir(taskID string) string {
return filepath.Join(b.cfg.AuditRoot, taskID)
}
func scopeFingerprint(domains, cidrs []string) string {
d := append([]string(nil), domains...)
c := append([]string(nil), cidrs...)
sort.Strings(d)
sort.Strings(c)
return strings.Join(d, ",") + "|" + strings.Join(c, ",")
}
func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*taskContainers, error) {
b.mu.Lock()
tc := b.tasks[taskID]
if tc == nil {
tc = &taskContainers{taskID: taskID, netName: b.cfg.TaskNetPrefix + taskID}
b.tasks[taskID] = tc
}
b.mu.Unlock()
tc.cleanupMu.Lock()
defer tc.cleanupMu.Unlock()
// Delete may have completed while this request waited for the lifecycle lock.
b.mu.Lock()
current := b.tasks[taskID] == tc
b.mu.Unlock()
if !current {
return nil, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID)
}
netName := b.cfg.TaskNetPrefix + taskID
tc.netName = netName
proxyName := "artex-egress-" + taskID
workerName := "artex-worker-" + taskID
sh := scopeFingerprint(scopeDomains, scopeCIDRs)
if tc.scopeHash == sh {
proxyOK := tc.proxyID != "" && b.startContainer(ctx, tc.proxyID) == nil
if !proxyOK && tc.proxyID != "" {
b.removeContainer(ctx, tc.proxyID)
tc.proxyID = ""
}
if proxyOK {
if err := b.ensureWorkerStarted(ctx, tc); err != nil {
return nil, err
}
if tc.workerID != "" {
return tc, nil
}
}
}
// Prepare per-task workspace directory (owned by 10001:10001 when running as root)
// and separate proxy-only audit directory (NEVER mounted into the worker).
localDir := b.localTaskDir(taskID)
if err := os.MkdirAll(localDir, 0o775); err != nil {
log.Printf("[runner] mkdir %s: %v", localDir, err)
} else {
_ = os.Chown(localDir, WorkerUID, WorkerGID)
}
localAudit := b.localAuditDir(taskID)
if err := os.MkdirAll(localAudit, 0o775); err != nil {
log.Printf("[runner] mkdir audit %s: %v", localAudit, err)
} else {
_ = os.Chown(localAudit, WorkerUID, WorkerGID)
}
// Ensure per-task internal network (no direct egress) and shared egress-net for the proxy.
if err := b.ensureNetwork(ctx, netName, true, taskID); err != nil {
return nil, err
}
if err := b.ensureNetwork(ctx, b.cfg.EgressNet, false, ""); err != nil {
return nil, err
}
// Recreate proxy if missing or scope changed.
if tc.proxyID == "" || tc.scopeHash != sh {
b.removeContainer(ctx, proxyName)
proxySpec := map[string]any{
"Image": b.cfg.ProxyImage,
"User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID),
"Env": []string{
"ARTEX_TASK_ID=" + taskID,
"ARTEX_SCOPE_DOMAINS=" + strings.Join(scopeDomains, ","),
"ARTEX_SCOPE_CIDRS=" + strings.Join(scopeCIDRs, ","),
fmt.Sprintf("ARTEX_PROXY_PORT=%d", DefaultProxyPort),
fmt.Sprintf("ARTEX_SOCKS_PORT=%d", DefaultSocksPort),
"ARTEX_EGRESS_LOG_PATH=/audit/egress.jsonl",
},
"Labels": map[string]string{
LabelTask: taskID,
LabelComponent: ComponentProxy,
LabelManagedBy: ManagedByRunner,
},
"HostConfig": map[string]any{
"ReadonlyRootfs": true,
"CapDrop": []string{"ALL"},
"SecurityOpt": []string{"no-new-privileges:true"},
"PidsLimit": int64(128),
"Memory": int64(256 << 20),
"NanoCpus": int64(500_000_000),
"NetworkMode": netName,
"Binds": []string{b.hostAuditDir(ctx, taskID) + ":/audit:rw"},
},
}
pid, err := b.createContainer(ctx, proxyName, proxySpec)
if err != nil {
return nil, err
}
if err := b.connectNetwork(ctx, b.cfg.EgressNet, pid); err != nil {
b.removeContainer(ctx, pid)
return nil, err
}
if err := b.startContainer(ctx, pid); err != nil {
b.removeContainer(ctx, pid)
return nil, err
}
tc.proxyID = pid
tc.scopeHash = sh
}
// Recover does not know the proxy's scope. After reconciling the proxy,
// start any tracked worker before reusing it, including workers found stopped
// after a Docker restart.
if err := b.ensureWorkerStarted(ctx, tc); err != nil {
return nil, err
}
// Create worker container strictly matching CONTRACT.md §4.
if tc.workerID == "" {
b.removeContainer(ctx, workerName)
proxyURL := fmt.Sprintf("http://%s:%d", proxyName, DefaultProxyPort)
socksURL := fmt.Sprintf("socks5h://%s:%d", proxyName, DefaultSocksPort)
workerSpec := map[string]any{
"Image": b.cfg.WorkerImage,
"Cmd": []string{"/usr/local/bin/artex-exec-wrap", "--init"},
"User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID),
"WorkingDir": "/workspace",
"Env": []string{
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HOME=/home/exec",
"LANG=C.UTF-8",
"TERM=xterm",
"HTTP_PROXY=" + proxyURL,
"HTTPS_PROXY=" + proxyURL,
"ALL_PROXY=" + socksURL,
"NO_PROXY=localhost,127.0.0.1",
"http_proxy=" + proxyURL,
"https_proxy=" + proxyURL,
"all_proxy=" + socksURL,
"no_proxy=localhost,127.0.0.1",
},
"Labels": map[string]string{
LabelTask: taskID,
LabelComponent: ComponentWorker,
LabelManagedBy: ManagedByRunner,
},
"HostConfig": map[string]any{
"ReadonlyRootfs": true,
"CapDrop": []string{"ALL"},
"SecurityOpt": []string{"no-new-privileges:true"},
"PidsLimit": int64(512),
"Memory": int64(2 << 30),
"NanoCpus": int64(2_000_000_000),
"Tmpfs": map[string]string{
"/tmp": "rw,noexec,nosuid,size=512m",
"/home/exec": fmt.Sprintf("rw,nosuid,size=128m,uid=%d,gid=%d,mode=0700", WorkerUID, WorkerGID),
},
"Binds": []string{b.hostTaskDir(ctx, taskID) + ":/workspace:rw"},
"NetworkMode": netName,
},
}
wid, err := b.createContainer(ctx, workerName, workerSpec)
if err != nil {
return nil, err
}
if err := b.startContainer(ctx, wid); err != nil {
b.removeContainer(ctx, wid)
return nil, err
}
tc.workerID = wid
}
return tc, nil
}
// ensureWorkerStarted runs under the task lifecycle lock. Clear a stale ID only
// after Docker confirms removal or absence so cleanup can be retried on failure.
func (b *DockerBackend) ensureWorkerStarted(ctx context.Context, tc *taskContainers) error {
if tc.workerID == "" {
return nil
}
if startErr := b.startContainer(ctx, tc.workerID); startErr != nil {
if removeErr := b.removeContainer(ctx, tc.workerID); removeErr != nil {
return errors.Join(startErr, removeErr)
}
tc.workerID = ""
}
return nil
}
// Exec runs req.Argv directly inside the task's worker container via /usr/local/bin/artex-exec-wrap
// (zero shell interpolation, isolated process group, SIGTERM -> 5s -> SIGKILL on timeout).
func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) {
start := time.Now()
tc, err := b.ensureTask(ctx, taskID, req.ScopeDomains, req.ScopeCIDRs)
if err != nil {
return ExecResponse{}, err
}
tc.cleanupMu.Lock()
workerID := tc.workerID
tc.cleanupMu.Unlock()
if workerID == "" {
return ExecResponse{}, fmt.Errorf("%w: task %s worker was removed", ErrNotFound, taskID)
}
// Wrap argv with artex-exec-wrap so every exec gets its own process group,
// enforces timeout_ms (SIGTERM group -> 5s -> SIGKILL -> exit 124) without
// relying on any agent-writable state.
wrappedArgv := make([]string, 0, len(req.Argv)+4)
wrappedArgv = append(wrappedArgv,
"/usr/local/bin/artex-exec-wrap",
strconv.Itoa(req.TimeoutMS),
"--",
)
wrappedArgv = append(wrappedArgv, req.Argv...)
envList := make([]string, 0, len(req.Env))
for k, v := range req.Env {
envList = append(envList, k+"="+v)
}
sort.Strings(envList)
createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(workerID)+"/exec", map[string]any{
"AttachStdout": true,
"AttachStderr": true,
"Tty": false,
"User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID),
"WorkingDir": req.Workdir,
"Env": envList,
"Cmd": wrappedArgv,
})
if err != nil {
return ExecResponse{}, err
}
defer createResp.Body.Close()
if createResp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(createResp.Body, 4096))
return ExecResponse{}, fmt.Errorf("create exec: HTTP %d: %s", createResp.StatusCode, string(raw))
}
var created struct {
ID string `json:"Id"`
}
if err := json.NewDecoder(createResp.Body).Decode(&created); err != nil {
return ExecResponse{}, err
}
// Give the HTTP start stream a small buffer over timeout_ms (5s SIGKILL grace + 5s slack).
execCtx, cancel := context.WithTimeout(ctx, time.Duration(req.TimeoutMS)*time.Millisecond+12*time.Second)
defer cancel()
execStart := time.Now()
startResp, err := b.dockerDo(execCtx, http.MethodPost, "/exec/"+url.PathEscape(created.ID)+"/start", map[string]any{
"Detach": false,
"Tty": false,
})
if err != nil {
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
}
defer startResp.Body.Close()
if startResp.StatusCode >= 300 {
return ExecResponse{}, errors.Join(fmt.Errorf("start exec: HTTP %d", startResp.StatusCode), b.removeExecWorker(ctx, tc, workerID))
}
stdout, stderr, truncated, streamErr := demuxDockerStream(startResp.Body, MaxOutputBytes)
if err := errors.Join(streamErr, execCtx.Err()); err != nil {
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
}
ic, cancelInspect := cleanupContext(ctx)
defer cancelInspect()
inspectResp, err := b.dockerDo(ic, http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil)
if err != nil {
return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID))
}
defer inspectResp.Body.Close()
var ins struct {
ExitCode *int `json:"ExitCode"`
Running *bool `json:"Running"`
}
decodeErr := json.NewDecoder(inspectResp.Body).Decode(&ins)
completed := ins.ExitCode != nil && ins.Running != nil && !*ins.Running
if decodeErr != nil || inspectResp.StatusCode != http.StatusOK || !completed {
return ExecResponse{}, errors.Join(fmt.Errorf("cannot prove exec completed (HTTP %d): %v", inspectResp.StatusCode, decodeErr), b.removeExecWorker(ctx, tc, workerID))
}
exitCode := *ins.ExitCode
// artex-exec-wrap exits 124 when it enforces timeout_ms, but the command
// itself can also exit 124 (coreutils `timeout N cmd` does). Only the
// wrapper's own timeout can take timeout_ms or longer, so a 124 that came
// back sooner is the command's exit code: keep the worker.
timedOut := exitCode == 124 && time.Since(execStart) >= time.Duration(req.TimeoutMS)*time.Millisecond
if timedOut || ctx.Err() != nil {
// Process-group timeout cannot kill setsid/double-fork descendants.
// Destroy the captured container, including its PID namespace and cgroup.
if err := b.removeExecWorker(ctx, tc, workerID); err != nil {
return ExecResponse{}, err
}
}
return ExecResponse{
ExitCode: exitCode,
Stdout: stdout,
Stderr: stderr,
Truncated: truncated,
TimedOut: timedOut,
DurationMS: time.Since(start).Milliseconds(),
}, nil
}
// removeExecWorker removes the exact container that ran this exec. A timeout
// also terminates sibling execs in that task, while preserving /workspace.
// Never remove a replacement worker, or forget a failed cleanup.
func (b *DockerBackend) removeExecWorker(ctx context.Context, tc *taskContainers, workerID string) error {
tc.cleanupMu.Lock()
defer tc.cleanupMu.Unlock()
cctx, cancel := cleanupContext(ctx)
defer cancel()
if err := b.removeContainer(cctx, workerID); err != nil {
return fmt.Errorf("exec cleanup for task %s: %w", tc.taskID, err)
}
b.clearWorkerID(tc, workerID)
return nil
}
// Kill terminates EVERY uid-10001 process inside the task's worker container
// (excluding PID 1) by running a root exec scanning /proc directly — never
// trusting any agent-writable state. If root exec fails or reports surviving
// processes, Kill falls back to force-removing the worker container so no
// process can ever survive Pause/Stop (preserving /workspace for the next exec).
// The worker ID is cleared only once the container is proven stopped or absent;
// a cleanup that cannot be proven returns an error so the caller can retry.
func (b *DockerBackend) Kill(ctx context.Context, taskID string) error {
b.mu.Lock()
tc := b.tasks[taskID]
b.mu.Unlock()
if tc == nil {
return fmt.Errorf("%w: task %s", ErrNotFound, taskID)
}
tc.cleanupMu.Lock()
defer tc.cleanupMu.Unlock()
if tc.workerID == "" {
return fmt.Errorf("%w: task %s", ErrNotFound, taskID)
}
return b.killCaptured(ctx, tc)
}
// killCaptured runs the kill sequence for the worker recorded in tc. It must be
// called with tc.cleanupMu held. tc.workerID is mutated under b.mu so a
// concurrent ensureTask cannot resurrect a half-removed container.
func (b *DockerBackend) killCaptured(ctx context.Context, tc *taskContainers) error {
workerID := tc.workerID
if workerID == "" {
return nil
}
err := b.killWorkerByProcScan(ctx, workerID)
if err == nil {
return nil
}
if errors.Is(err, ErrNotFound) {
// The worker container is gone: nothing can survive it.
b.clearWorkerID(tc, workerID)
return nil
}
// Fail closed: force-remove the worker container (kernel destroys the
// entire PID namespace & cgroup) while keeping /workspace and the task
// network/proxy intact so the next exec recreates a clean worker.
log.Printf("[runner] /proc uid kill for task %s failed (%v); force-removing worker container", tc.taskID, err)
cctx, cancel := cleanupContext(ctx)
defer cancel()
if rerr := b.removeContainer(cctx, workerID); rerr != nil {
// Keep the ID: a retry must still be able to find and remove the worker,
// and a paused task must not look cleaned up while the container lives.
return fmt.Errorf("kill task %s: proc scan: %v; %w", tc.taskID, err, rerr)
}
b.clearWorkerID(tc, workerID)
return nil
}
func (b *DockerBackend) clearWorkerID(tc *taskContainers, workerID string) {
b.mu.Lock()
if cur := b.tasks[tc.taskID]; cur == tc && cur.workerID == workerID {
cur.workerID = ""
}
b.mu.Unlock()
}
func (b *DockerBackend) killWorkerByProcScan(ctx context.Context, workerID string) error {
resp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(workerID)+"/exec", map[string]any{
"AttachStdout": true,
"AttachStderr": true,
"Tty": false,
"User": fmt.Sprintf("%d:%d", WorkerUID, WorkerGID),
"Cmd": []string{"/usr/local/bin/artex-exec-wrap", "--kill-uid", strconv.Itoa(WorkerUID)},
})
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("%w: worker %s gone", ErrNotFound, workerID)
}
if resp.StatusCode >= 300 {
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("kill exec create: HTTP %d: %s", resp.StatusCode, string(raw))
}
var created struct {
ID string `json:"Id"`
}
if err := json.NewDecoder(resp.Body).Decode(&created); err != nil {
return err
}
kctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
sresp, err := b.dockerDo(kctx, http.MethodPost, "/exec/"+url.PathEscape(created.ID)+"/start", map[string]any{
"Detach": false,
"Tty": false,
})
if err != nil {
return err
}
_, _ = io.Copy(io.Discard, sresp.Body)
sresp.Body.Close()
insResp, err := b.dockerDo(context.Background(), http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil)
if err != nil {
return err
}
defer insResp.Body.Close()
var ins struct {
ExitCode int `json:"ExitCode"`
}
if err := json.NewDecoder(insResp.Body).Decode(&ins); err != nil {
return err
}
if ins.ExitCode != 0 {
return fmt.Errorf("kill-uid exited %d", ins.ExitCode)
}
return nil
}
// Delete kills and removes the task's worker container, egress proxy container, and
// per-task internal network, while preserving /app/data/tasks/<id> on disk.
// The task stays in the in-memory map until every resource is proven stopped or
// absent: a failed cleanup must remain visible and retryable instead of leaving
// a worker or proxy running while the control plane forgets its identifiers.
func (b *DockerBackend) Delete(ctx context.Context, taskID string) error {
b.mu.Lock()
tc := b.tasks[taskID]
b.mu.Unlock()
if tc == nil {
return fmt.Errorf("%w: task %s", ErrNotFound, taskID)
}
tc.cleanupMu.Lock()
defer tc.cleanupMu.Unlock()
cctx, cancel := cleanupContext(ctx)
defer cancel()
// Removing the worker also stops its processes and detaches the network
// endpoint. A process scan alone leaves PID 1 and the endpoint alive.
workerID := tc.workerID
if err := b.removeContainer(cctx, workerID); err != nil {
return fmt.Errorf("delete task %s worker: %w", taskID, err)
}
b.clearWorkerID(tc, workerID)
var errs []error
if err := b.removeContainer(cctx, tc.proxyID); err != nil {
errs = append(errs, err)
} else {
tc.proxyID = ""
}
if err := b.removeNetwork(cctx, tc.netName); err != nil {
errs = append(errs, err)
} else {
tc.netName = ""
}
if len(errs) > 0 {
return fmt.Errorf("delete task %s: %w", taskID, errors.Join(errs...))
}
b.mu.Lock()
if b.tasks[taskID] == tc {
delete(b.tasks, taskID)
}
b.mu.Unlock()
return nil
}
// demuxDockerStream parses Docker's 8-byte multiplexed stdout/stderr framing
// ([stream_type, 0, 0, 0, size_be32]) and caps each stream at maxBytes.
func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, truncated bool, err error) {
var outBuf, errBuf bytes.Buffer
hdr := make([]byte, 8)
for {
if _, err := io.ReadFull(r, hdr); err != nil {
if errors.Is(err, io.EOF) {
break
}
return outBuf.String(), errBuf.String(), truncated, err
}
streamType := hdr[0]
frameLen := int64(binary.BigEndian.Uint32(hdr[4:8]))
if frameLen <= 0 {
continue
}
var dst *bytes.Buffer
if streamType == 2 {
dst = &errBuf
} else {
dst = &outBuf
}
rem := int64(maxBytes - dst.Len())
if rem > 0 {
take := frameLen
if take > rem {
take = rem
truncated = true
}
if _, err := io.CopyN(dst, r, take); err != nil {
return outBuf.String(), errBuf.String(), truncated, err
}
frameLen -= take
} else {
truncated = true
}
if frameLen > 0 {
if _, err := io.CopyN(io.Discard, r, frameLen); err != nil {
return outBuf.String(), errBuf.String(), truncated, err
}
}
}
return outBuf.String(), errBuf.String(), truncated, nil
}