Files
ARTEX-chixuweihu/internal/sandbox/manager.go
T
ji ruo 8bac4960e7 fix(sandbox,traffic): keep sandbox command output and free scan dial slots
Docker exec no longer wraps commands in setsid, which exited immediately and cut stdout after about two seconds. Netstack releases the pending-dial slot once the handshake finishes, raises the in-flight limits, and treats local file-descriptor exhaustion as a silent drop. The gateway container gets a higher open-file limit.
2026-12-02 17:45:28 +08:00

1542 lines
41 KiB
Go

package sandbox
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
labelManaged = "artex.managed"
labelInstance = "artex.instance"
labelScope = "artex.scope"
labelOwnerID = "artex.owner_id"
defaultMaxExecOutput = 1 << 20 // 1 MiB
statsCacheTTL = 10 * time.Second
)
// Manager owns the lifecycle of all sandbox containers and exposes exec/stream
// operations for Worker, ChatAgent, CustomTool, and Stdio MCP callers.
type Manager struct {
mu sync.RWMutex
cfg Config
docker *dockerClient
// Per-target serialization lock prevents concurrent Workers from racing
// container creation/start/stop for the same task or session.
targetLocks sync.Map // target.Key() -> *sync.Mutex
// Active run tracking prevents auto-stop while any worker, settlement,
// human follow-up, or intercept approval is in flight.
stateMu sync.Mutex
states map[string]*targetState
// Cached container stats (short TTL) so UI polling doesn't hammer Docker.
statsMu sync.Mutex
statsCache map[string]cachedStats
statsInFlight map[string]struct{}
// Detected sandbox network CIDRs & bridge gateway IP.
netCIDRMu sync.RWMutex
netCIDRs []*net.IPNet
gatewayIP string
// Real-time container IP -> sandbox owner identity map for SNAT-free traffic attribution (#218).
ipMu sync.RWMutex
ipMap map[string]ContainerIdentity
stopReaper context.CancelFunc
reaperWG sync.WaitGroup
}
type targetState struct {
activeRuns int
lastActive time.Time
stopWhenIdle bool
}
type cachedStats struct {
at time.Time
stats dockerStats
}
var defaultMgr atomic.Pointer[Manager]
// Default returns the process-wide sandbox Manager (may be nil in tests / before init).
func Default() *Manager { return defaultMgr.Load() }
// SetDefault installs the process-wide sandbox Manager.
func SetDefault(m *Manager) { defaultMgr.Store(m) }
// New creates a Manager. In ModeLocal it requires no Docker daemon.
func New(cfg Config) (*Manager, error) {
m := &Manager{
cfg: cfg,
states: map[string]*targetState{},
statsCache: map[string]cachedStats{},
statsInFlight: map[string]struct{}{},
ipMap: map[string]ContainerIdentity{},
}
if cfg.Mode == ModeDocker {
dc, err := newDockerClient(cfg.DockerHost)
if err != nil {
return nil, err
}
m.docker = dc
}
return m, nil
}
// Enabled reports whether Docker sandbox isolation is active.
func (m *Manager) Enabled() bool {
if m == nil {
return false
}
m.mu.RLock()
defer m.mu.RUnlock()
return m.cfg.Mode == ModeDocker && m.docker != nil
}
// Config returns a copy of the current sandbox configuration.
func (m *Manager) Config() Config {
if m == nil {
return Config{Mode: ModeLocal}
}
m.mu.RLock()
defer m.mu.RUnlock()
return m.cfg
}
// ApplyOverrides updates mutable runtime config fields (typically loaded from DB settings).
func (m *Manager) ApplyOverrides(o RuntimeOverrides) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if o.Image != nil && strings.TrimSpace(*o.Image) != "" {
m.cfg.Image = strings.TrimSpace(*o.Image)
}
if o.MemoryMB != nil && *o.MemoryMB >= 256 {
m.cfg.MemoryMB = *o.MemoryMB
}
if o.CPUs != nil && *o.CPUs >= 0.25 {
m.cfg.CPUs = *o.CPUs
}
if o.PidsLimit != nil && *o.PidsLimit >= 32 {
m.cfg.PidsLimit = *o.PidsLimit
}
if o.ShmSizeMB != nil && *o.ShmSizeMB >= 64 {
m.cfg.ShmSizeMB = *o.ShmSizeMB
}
if o.Runtime != nil {
m.cfg.Runtime = strings.TrimSpace(*o.Runtime)
}
if o.AutoStopOnComplete != nil {
m.cfg.AutoStopOnComplete = *o.AutoStopOnComplete
}
if o.SessionIdleMinutes != nil && *o.SessionIdleMinutes >= 1 {
m.cfg.SessionIdleMinutes = *o.SessionIdleMinutes
}
}
// SetProxyConfig updates the proxy URL and CA cert path exposed to sandbox containers.
func (m *Manager) SetProxyConfig(proxyURL, caCertPath string) {
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if strings.TrimSpace(proxyURL) != "" {
m.cfg.ProxyURL = strings.TrimSpace(proxyURL)
}
if strings.TrimSpace(caCertPath) != "" {
m.cfg.CACertPath = strings.TrimSpace(caCertPath)
}
}
// SetSystemCABundlePath sets the host path to the merged system + ARTEX MITM CA
// bundle mounted read-only into sandbox containers at /etc/ssl/certs/ca-certificates.crt.
func (m *Manager) SetSystemCABundlePath(bundlePath string) {
if m == nil {
return
}
m.mu.Lock()
m.cfg.SystemCABundlePath = strings.TrimSpace(bundlePath)
m.mu.Unlock()
}
// GatewayIP returns the detected bridge gateway IP of the sandbox network (e.g. "172.30.0.1").
func (m *Manager) GatewayIP() string {
if m == nil {
return ""
}
m.netCIDRMu.RLock()
defer m.netCIDRMu.RUnlock()
return m.gatewayIP
}
// ContainerIPSnapshot returns a copy of the live container IP -> identity map
// for transparent gateway policy sync (#218 Phase 3).
func (m *Manager) ContainerIPSnapshot() map[string]ContainerIdentity {
if m == nil {
return nil
}
m.ipMu.RLock()
defer m.ipMu.RUnlock()
out := make(map[string]ContainerIdentity, len(m.ipMap))
for k, v := range m.ipMap {
out[k] = v
}
return out
}
// ProxyEnv returns HTTP(S)_PROXY + CA cert environment variables for processes
// running inside a sandbox container. Empty when capture/proxy is disabled.
func (m *Manager) ProxyEnv(proxyActive bool) []string {
if m == nil || !proxyActive {
return nil
}
return m.ProxyEnvWithURL(m.Config().ProxyURL)
}
// ProxyEnvWithURL returns HTTP(S)_PROXY + CA cert environment variables for
// processes inside a sandbox container using an explicit proxy URL (e.g. a
// Proxy-Authorization tagged recording proxy URL for per-intent attribution).
func (m *Manager) ProxyEnvWithURL(proxyURL string) []string {
if m == nil {
return nil
}
proxyURL = strings.TrimSpace(proxyURL)
if proxyURL == "" {
return nil
}
cfg := m.Config()
env := []string{
"HTTP_PROXY=" + proxyURL,
"HTTPS_PROXY=" + proxyURL,
"http_proxy=" + proxyURL,
"https_proxy=" + proxyURL,
"ALL_PROXY=" + proxyURL,
"all_proxy=" + proxyURL,
"NODE_USE_ENV_PROXY=1",
}
caBundle := ""
if cfg.SystemCABundlePath != "" {
if _, err := os.Stat(cfg.SystemCABundlePath); err == nil {
caBundle = ContainerSystemCABundlePath
}
}
if cfg.CACertPath != "" {
if _, err := os.Stat(cfg.CACertPath); err == nil {
if caBundle == "" {
caBundle = ContainerCACertPath
}
env = append(env,
"SSL_CERT_FILE="+caBundle,
"CURL_CA_BUNDLE="+caBundle,
"REQUESTS_CA_BUNDLE="+caBundle,
"GIT_SSL_CAINFO="+caBundle,
"NODE_EXTRA_CA_CERTS="+ContainerCACertPath,
)
}
}
return env
}
// IsSandboxSourceIP reports whether remoteAddr belongs to the isolated sandbox
// Docker network (used to block sandbox containers from calling :8787 admin API).
func (m *Manager) IsSandboxSourceIP(remoteAddr string) bool {
if m == nil || !m.Enabled() {
return false
}
host := remoteAddr
if h, _, err := net.SplitHostPort(remoteAddr); err == nil {
host = h
}
ip := net.ParseIP(strings.TrimSpace(host))
if ip == nil {
return false
}
m.netCIDRMu.RLock()
defer m.netCIDRMu.RUnlock()
for _, n := range m.netCIDRs {
if n.Contains(ip) {
return true
}
}
return false
}
// SandboxSubnets returns the detected sandbox bridge subnets (e.g. ["172.28.0.0/16"]).
func (m *Manager) SandboxSubnets() []*net.IPNet {
if m == nil {
return nil
}
m.netCIDRMu.RLock()
defer m.netCIDRMu.RUnlock()
out := make([]*net.IPNet, len(m.netCIDRs))
copy(out, m.netCIDRs)
return out
}
func (m *Manager) lockFor(t Target) *sync.Mutex {
v, _ := m.targetLocks.LoadOrStore(t.Key(), &sync.Mutex{})
return v.(*sync.Mutex)
}
// Acquire increments the active run counter for target and clears any pending
// stop-when-idle flag. Every Acquire must be paired with Release.
func (m *Manager) Acquire(t Target) {
if m == nil || !t.Valid() {
return
}
m.stateMu.Lock()
defer m.stateMu.Unlock()
st := m.states[t.Key()]
if st == nil {
st = &targetState{}
m.states[t.Key()] = st
}
st.activeRuns++
st.lastActive = time.Now()
st.stopWhenIdle = false
}
// Release decrements activeRuns. If activeRuns hits 0 and MarkIdleStop was
// requested (e.g. task paused/completed while finishing settlement), it stops
// the container asynchronously.
func (m *Manager) Release(t Target) {
if m == nil || !t.Valid() {
return
}
var shouldStop bool
m.stateMu.Lock()
st := m.states[t.Key()]
if st != nil {
if st.activeRuns > 0 {
st.activeRuns--
}
st.lastActive = time.Now()
if st.activeRuns == 0 && st.stopWhenIdle {
shouldStop = true
st.stopWhenIdle = false
}
}
m.stateMu.Unlock()
if shouldStop && m.Enabled() && m.Config().AutoStopOnComplete {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := m.Stop(ctx, t); err != nil {
log.Printf("[sandbox] auto-stop %s failed: %v", t.Key(), err)
}
}()
}
}
// ActiveRuns returns the number of active executions currently using target.
func (m *Manager) ActiveRuns(t Target) int {
if m == nil || !t.Valid() {
return 0
}
m.stateMu.Lock()
defer m.stateMu.Unlock()
if st := m.states[t.Key()]; st != nil {
return st.activeRuns
}
return 0
}
// RequestIdleStop stops target immediately if no active run holds it; otherwise
// schedules an automatic stop the moment the last active run releases it.
func (m *Manager) RequestIdleStop(t Target) {
if m == nil || !m.Enabled() || !t.Valid() {
return
}
if !m.Config().AutoStopOnComplete {
return
}
var stopNow bool
m.stateMu.Lock()
st := m.states[t.Key()]
if st == nil || st.activeRuns == 0 {
stopNow = true
} else {
st.stopWhenIdle = true
}
m.stateMu.Unlock()
if stopNow {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := m.Stop(ctx, t); err != nil {
log.Printf("[sandbox] idle-stop %s failed: %v", t.Key(), err)
}
}()
}
}
// ClearIdleStop cancels any pending deferred stop when a task resumes.
func (m *Manager) ClearIdleStop(t Target) {
if m == nil || !t.Valid() {
return
}
m.stateMu.Lock()
defer m.stateMu.Unlock()
if st := m.states[t.Key()]; st != nil {
st.stopWhenIdle = false
}
}
// StartBackgroundReaper periodically stops idle session containers.
func (m *Manager) StartBackgroundReaper(parent context.Context) {
if m == nil || !m.Enabled() {
return
}
ctx, cancel := context.WithCancel(parent)
m.stopReaper = cancel
m.reaperWG.Add(1)
go func() {
defer m.reaperWG.Done()
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
m.reapIdleSessions(ctx)
}
}
}()
}
func (m *Manager) reapIdleSessions(ctx context.Context) {
idleLimit := time.Duration(m.Config().SessionIdleMinutes) * time.Minute
if idleLimit <= 0 {
idleLimit = 20 * time.Minute
}
now := time.Now()
var victims []Target
m.stateMu.Lock()
for key, st := range m.states {
if !strings.HasPrefix(key, string(ScopeSession)+":") {
continue
}
if st.activeRuns == 0 && !st.lastActive.IsZero() && now.Sub(st.lastActive) >= idleLimit {
victims = append(victims, Target{
Scope: ScopeSession,
OwnerID: strings.TrimPrefix(key, string(ScopeSession)+":"),
})
}
}
m.stateMu.Unlock()
for _, t := range victims {
sctx, cancel := context.WithTimeout(ctx, 15*time.Second)
if info, err := m.Inspect(sctx, t, false); err == nil && info.State == "running" {
log.Printf("[sandbox] stopping idle session container %s", t.OwnerID)
_ = m.Stop(sctx, t)
}
cancel()
}
}
// ReconcileOnStartup verifies Docker connectivity, ensures the isolated network
// exists (with ICC disabled), removes orphan containers whose tasks/sessions no
// longer exist in DB, and stops leftover running containers from a prior crash.
func (m *Manager) ReconcileOnStartup(ctx context.Context, validTaskIDs, validSessionIDs map[string]bool) error {
if m == nil || !m.Enabled() {
return nil
}
cfg := m.Config()
if err := m.docker.Ping(ctx); err != nil {
return fmt.Errorf("docker ping failed (%s): %w", cfg.DockerHost, err)
}
netInfo, err := m.docker.EnsureNetwork(ctx, cfg.Network)
if err != nil {
return fmt.Errorf("ensure sandbox network %q: %w", cfg.Network, err)
}
m.recordNetworkCIDRs(netInfo)
items, err := m.docker.ListContainersByLabel(ctx, map[string]string{
labelManaged: "true",
labelInstance: cfg.InstanceID,
})
if err != nil {
return fmt.Errorf("list managed containers: %w", err)
}
for _, item := range items {
scope := Scope(item.Labels[labelScope])
ownerID := item.Labels[labelOwnerID]
orphan := false
switch scope {
case ScopeTask:
orphan = validTaskIDs != nil && !validTaskIDs[ownerID]
case ScopeSession:
orphan = validSessionIDs != nil && !validSessionIDs[ownerID]
case ScopeEphemeral:
orphan = true
}
if orphan {
log.Printf("[sandbox] removing orphan container %s (%s:%s)", shortID(item.ID), scope, ownerID)
_ = m.docker.RemoveContainer(ctx, item.ID)
continue
}
if item.State == "running" {
log.Printf("[sandbox] stopping leftover running container %s (%s:%s)", shortID(item.ID), scope, ownerID)
_ = m.docker.StopContainer(ctx, item.ID, 5)
}
}
return nil
}
// Shutdown stops the background reaper and gracefully stops all running managed
// containers (preserving stopped containers + mounted workspaces across restarts).
func (m *Manager) Shutdown(ctx context.Context) {
if m == nil || !m.Enabled() {
return
}
if m.stopReaper != nil {
m.stopReaper()
m.reaperWG.Wait()
}
cfg := m.Config()
items, err := m.docker.ListContainersByLabel(ctx, map[string]string{
labelManaged: "true",
labelInstance: cfg.InstanceID,
})
if err != nil {
return
}
for _, item := range items {
if Scope(item.Labels[labelScope]) == ScopeEphemeral {
_ = m.docker.RemoveContainer(ctx, item.ID)
} else if item.State == "running" {
_ = m.docker.StopContainer(ctx, item.ID, 5)
}
}
}
func (m *Manager) recordNetworkCIDRs(netInfo *dockerNetworkInspect) {
if netInfo == nil {
return
}
var cidrs []*net.IPNet
var gateway string
for _, c := range netInfo.IPAM.Config {
if _, ipnet, err := net.ParseCIDR(strings.TrimSpace(c.Subnet)); err == nil {
cidrs = append(cidrs, ipnet)
}
if gateway == "" && strings.TrimSpace(c.Gateway) != "" {
gateway = strings.TrimSpace(c.Gateway)
}
}
m.netCIDRMu.Lock()
m.netCIDRs = cidrs
if gateway != "" {
m.gatewayIP = gateway
}
m.netCIDRMu.Unlock()
// attached directly to artex-sandbox (eliminates bridge SNAT so the proxy
// observes each sandbox container's real source IP). Fall back to the
// bridge gateway on single-network setups.
proxyHost := detectLocalIPInSubnets(cidrs)
if proxyHost == "" {
proxyHost = gateway
}
if proxyHost != "" {
m.mu.Lock()
if m.cfg.ProxyURL == "" || strings.EqualFold(m.cfg.ProxyURL, "auto") {
m.cfg.ProxyURL = "http://" + proxyHost + ":8788"
}
m.mu.Unlock()
}
}
func detectLocalIPInSubnets(cidrs []*net.IPNet) string {
if len(cidrs) == 0 {
return ""
}
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, a := range addrs {
ipnet, ok := a.(*net.IPNet)
if !ok || ipnet.IP == nil {
continue
}
ip := ipnet.IP.To4()
if ip == nil {
continue
}
for _, sub := range cidrs {
if sub.Contains(ip) {
return ip.String()
}
}
}
return ""
}
// ResolveContainerByIP returns the managed sandbox container owning srcIP.
func (m *Manager) ResolveContainerByIP(srcIP string) (ContainerIdentity, bool) {
if m == nil {
return ContainerIdentity{}, false
}
raw := strings.TrimSpace(srcIP)
if h, _, err := net.SplitHostPort(raw); err == nil {
raw = h
}
ip := net.ParseIP(strings.Trim(raw, "[]"))
if ip == nil {
return ContainerIdentity{}, false
}
if v4 := ip.To4(); v4 != nil {
ip = v4
}
m.ipMu.RLock()
id, ok := m.ipMap[ip.String()]
m.ipMu.RUnlock()
return id, ok
}
func (m *Manager) registerContainerIP(ip string, id ContainerIdentity) {
parsed := net.ParseIP(strings.TrimSpace(ip))
if parsed == nil {
return
}
if v4 := parsed.To4(); v4 != nil {
parsed = v4
}
ipStr := parsed.String()
id.IP = ipStr
m.ipMu.Lock()
// Evict stale IP entries for the same container name/id first.
for k, existing := range m.ipMap {
if k != ipStr && ((id.ContainerName != "" && existing.ContainerName == id.ContainerName) || (id.ContainerID != "" && existing.ContainerID == id.ContainerID)) {
delete(m.ipMap, k)
}
}
m.ipMap[ipStr] = id
m.ipMu.Unlock()
}
func (m *Manager) evictContainerIP(name string) {
if name == "" {
return
}
m.ipMu.Lock()
for k, existing := range m.ipMap {
if existing.ContainerName == name {
delete(m.ipMap, k)
}
}
m.ipMu.Unlock()
}
// Ensure guarantees that target's sandbox container exists and is running.
func (m *Manager) Ensure(ctx context.Context, t Target) (string, error) {
if !m.Enabled() {
return "", errors.New("sandbox docker mode is not enabled")
}
if !t.Valid() {
return "", errors.New("invalid sandbox target")
}
mu := m.lockFor(t)
mu.Lock()
defer mu.Unlock()
cfg := m.Config()
name := cfg.ContainerName(t)
// Ensure host-side workspace directory exists with sandbox-writable perms
// BEFORE mounting so Docker never auto-creates a root-owned directory.
localRoot := cfg.LocalRootFor(t)
if err := ensureWritableDir(localRoot, cfg.User); err != nil {
return "", fmt.Errorf("prepare sandbox workspace: %w", err)
}
if info, err := m.docker.InspectContainer(ctx, name); err == nil {
if !info.State.Running {
if err := m.docker.StartContainer(ctx, info.ID); err != nil {
return "", fmt.Errorf("start sandbox container %s: %w", name, err)
}
if refreshed, ierr := m.docker.InspectContainer(ctx, info.ID); ierr == nil {
info = refreshed
}
}
if ip := info.IPOnNetwork(cfg.Network); ip != "" {
m.registerContainerIP(ip, ContainerIdentity{
Scope: t.Scope,
OwnerID: t.OwnerID,
ContainerID: info.ID,
ShortID: shortID(info.ID),
ContainerName: name,
})
}
return info.ID, nil
} else if !isDockerNotFound(err) {
return "", fmt.Errorf("inspect sandbox container %s: %w", name, err)
}
netInfo, err := m.docker.EnsureNetwork(ctx, cfg.Network)
if err != nil {
return "", fmt.Errorf("ensure network %s: %w", cfg.Network, err)
}
m.recordNetworkCIDRs(netInfo)
hostRoot := cfg.MapDataPathToHost(localRoot)
binds := []string{hostRoot + ":" + ContainerWorkDir + ":rw"}
baseEnv := []string{
"HOME=/tmp",
"TERM=dumb",
"ARTEX_SANDBOX=1",
"ARTEX_WORKSPACE=" + ContainerWorkDir,
}
if cfg.AllowNetRaw {
baseEnv = append(baseEnv, "NMAP_PRIVILEGED=1")
}
if cfg.CACertPath != "" {
if _, err := os.Stat(cfg.CACertPath); err == nil {
hostCA := cfg.MapDataPathToHost(cfg.CACertPath)
binds = append(binds, hostCA+":"+ContainerCACertPath+":ro")
baseEnv = append(baseEnv, "NODE_EXTRA_CA_CERTS="+ContainerCACertPath)
}
}
if cfg.SystemCABundlePath != "" {
if _, err := os.Stat(cfg.SystemCABundlePath); err == nil {
hostBundle := cfg.MapDataPathToHost(cfg.SystemCABundlePath)
binds = append(binds, hostBundle+":"+ContainerSystemCABundlePath+":ro")
baseEnv = append(baseEnv,
"SSL_CERT_FILE="+ContainerSystemCABundlePath,
"CURL_CA_BUNDLE="+ContainerSystemCABundlePath,
"REQUESTS_CA_BUNDLE="+ContainerSystemCABundlePath,
"GIT_SSL_CAINFO="+ContainerSystemCABundlePath,
)
}
}
memBytes := int64(cfg.MemoryMB) << 20
shmBytes := int64(cfg.ShmSizeMB) << 20
nanoCPUs := int64(cfg.CPUs * 1e9)
pidsLimit := int64(cfg.PidsLimit)
hostCfg := map[string]any{
"Binds": binds,
"NetworkMode": cfg.Network,
"Memory": memBytes,
"MemorySwap": memBytes, // disable swap thrashing
"NanoCpus": nanoCPUs,
"PidsLimit": pidsLimit,
"ShmSize": shmBytes,
"CapDrop": []string{"ALL"},
"Init": true, // tini/docker-init reaps zombies inside container
"Tmpfs": map[string]string{"/tmp": fmt.Sprintf("rw,nosuid,nodev,size=%dm", cfg.TmpSizeMB)},
"Sysctls": map[string]string{"net.ipv4.ping_group_range": "0 2147483647"},
"RestartPolicy": map[string]any{"Name": "no"},
}
if cfg.AllowNetRaw {
// Permit CAP_NET_RAW in the bounding set ONLY (paired with file-cap cap_net_raw+ep
// on /usr/bin/nmap, /usr/bin/nping, and /usr/bin/ping in Dockerfile.sandbox, with
// all SUID/SGID bits stripped). Ordinary non-root processes keep CapEff=0.
hostCfg["CapAdd"] = []string{"NET_RAW"}
} else {
// Strict lockdown for untrusted custom images that may contain SUID binaries.
hostCfg["SecurityOpt"] = []string{"no-new-privileges:true"}
}
// Route container DNS through the sandbox gateway IP when transparent mode is enabled
// so Docker's embedded DNS forwards queries across the sandbox bridge with real container src_ip.
if cfg.TransparentGateway {
dnsIP := strings.TrimSpace(cfg.GatewayDNSIP)
if dnsIP == "" {
dnsIP = m.GatewayIP()
}
if dnsIP != "" {
hostCfg["Dns"] = []string{dnsIP}
}
}
if cfg.Runtime != "" {
hostCfg["Runtime"] = cfg.Runtime
}
spec := map[string]any{
"Image": cfg.Image,
"Hostname": sanitizeToken(string(t.Scope) + "-" + t.OwnerID),
"User": cfg.User,
"WorkingDir": ContainerWorkDir,
"Cmd": []string{"sleep", "infinity"},
"AttachStdin": false,
"AttachStdout": false,
"AttachStderr": false,
"Tty": false,
"Env": baseEnv,
"Labels": map[string]string{
labelManaged: "true",
labelInstance: cfg.InstanceID,
labelScope: string(t.Scope),
labelOwnerID: t.OwnerID,
},
"HostConfig": hostCfg,
}
id, err := m.docker.CreateContainer(ctx, name, spec)
if err != nil {
return "", fmt.Errorf("create sandbox container %s (image %s): %w", name, cfg.Image, err)
}
if err := m.docker.StartContainer(ctx, id); err != nil {
_ = m.docker.RemoveContainer(ctx, id)
return "", fmt.Errorf("start sandbox container %s: %w", name, err)
}
if info, ierr := m.docker.InspectContainer(ctx, id); ierr == nil {
if ip := info.IPOnNetwork(cfg.Network); ip != "" {
m.registerContainerIP(ip, ContainerIdentity{
Scope: t.Scope,
OwnerID: t.OwnerID,
ContainerID: id,
ShortID: shortID(id),
ContainerName: name,
})
}
}
log.Printf("[sandbox] created & started %s (%s, image=%s, mem=%dMiB, cpus=%.2f)", name, shortID(id), cfg.Image, cfg.MemoryMB, cfg.CPUs)
return id, nil
}
// Stop stops target's container (releasing CPU/memory while retaining container + workspace).
func (m *Manager) Stop(ctx context.Context, t Target) error {
if !m.Enabled() || !t.Valid() {
return nil
}
mu := m.lockFor(t)
mu.Lock()
defer mu.Unlock()
name := m.Config().ContainerName(t)
if err := m.docker.StopContainer(ctx, name, 5); err != nil {
return err
}
m.dropStatsCache(name)
m.evictContainerIP(name)
return nil
}
// Remove force-removes target's container (leaving host workspace files to caller).
func (m *Manager) Remove(ctx context.Context, t Target) error {
if !m.Enabled() || !t.Valid() {
return nil
}
mu := m.lockFor(t)
mu.Lock()
defer mu.Unlock()
name := m.Config().ContainerName(t)
if err := m.docker.RemoveContainer(ctx, name); err != nil {
return err
}
m.dropStatsCache(name)
m.evictContainerIP(name)
m.stateMu.Lock()
delete(m.states, t.Key())
m.stateMu.Unlock()
return nil
}
// Recreate deletes target's existing container (optionally clearing workspace)
// and creates + starts a fresh container using the latest Config.
func (m *Manager) Recreate(ctx context.Context, t Target, clearWorkspace bool) (ContainerInfo, error) {
if !m.Enabled() || !t.Valid() {
return ContainerInfo{}, errors.New("sandbox docker mode is not enabled")
}
if err := m.Remove(ctx, t); err != nil {
return ContainerInfo{}, err
}
if clearWorkspace {
root := m.Config().LocalRootFor(t)
entries, err := os.ReadDir(root)
if err == nil {
for _, e := range entries {
_ = os.RemoveAll(filepath.Join(root, e.Name()))
}
}
}
if _, err := m.Ensure(ctx, t); err != nil {
return ContainerInfo{}, err
}
return m.Inspect(ctx, t, false)
}
// PruneStopped removes stopped/exited managed containers (and any ephemeral containers).
func (m *Manager) PruneStopped(ctx context.Context) (int, error) {
if !m.Enabled() {
return 0, nil
}
cfg := m.Config()
items, err := m.docker.ListContainersByLabel(ctx, map[string]string{
labelManaged: "true",
labelInstance: cfg.InstanceID,
})
if err != nil {
return 0, err
}
removed := 0
for _, item := range items {
if item.State != "running" {
if err := m.docker.RemoveContainer(ctx, item.ID); err == nil {
removed++
}
}
}
return removed, nil
}
// Inspect returns current container metadata and optional cached CPU/memory stats.
func (m *Manager) Inspect(ctx context.Context, t Target, withStats bool) (ContainerInfo, error) {
cfg := m.Config()
base := ContainerInfo{
Scope: t.Scope,
OwnerID: t.OwnerID,
Name: cfg.ContainerName(t),
Image: cfg.Image,
State: "local",
ActiveRuns: m.ActiveRuns(t),
WorkDirContainer: ContainerWorkDir,
Network: cfg.Network,
Runtime: cfg.Runtime,
}
if !m.Enabled() {
return base, nil
}
info, err := m.docker.InspectContainer(ctx, base.Name)
if err != nil {
if isDockerNotFound(err) {
base.State = "missing"
base.StatusText = "not created"
return base, nil
}
base.State = "error"
base.Error = err.Error()
return base, err
}
base.ContainerID = info.ID
base.ShortID = shortID(info.ID)
base.Image = info.Config.Image
base.State = info.State.Status
base.StatusText = info.State.Status
base.CreatedAt = info.Created
if info.State.Running {
base.StartedAt = info.State.StartedAt
}
base.Runtime = info.HostConfig.Runtime
base.Network = info.HostConfig.NetworkMode
if info.HostConfig.Memory > 0 {
base.MemLimitBytes = uint64(info.HostConfig.Memory)
}
if withStats && info.State.Running {
if st, err := m.cachedContainerStats(ctx, base.Name); err == nil {
base.CPUPercent = st.CPUPercent
base.MemUsageBytes = st.MemUsageBytes
if st.MemLimitBytes > 0 {
base.MemLimitBytes = st.MemLimitBytes
}
base.PidsCurrent = st.PidsCurrent
}
}
return base, nil
}
// Status returns global sandbox status plus all managed containers (using cached stats only).
func (m *Manager) Status(ctx context.Context) GlobalStatus {
return m.StatusWithStats(ctx, false)
}
// StatusWithStats returns global sandbox status plus all managed containers.
// When withStats is true, live CPU/memory/PID stats are concurrently fetched
// (with short caching) for every running container.
func (m *Manager) StatusWithStats(ctx context.Context, withStats bool) GlobalStatus {
cfg := m.Config()
out := GlobalStatus{
Mode: cfg.Mode,
Enabled: m.Enabled(),
Available: !m.Enabled(), // local mode is always available
Image: cfg.Image,
Network: cfg.Network,
Runtime: cfg.Runtime,
MemoryMB: cfg.MemoryMB,
CPUs: cfg.CPUs,
PidsLimit: cfg.PidsLimit,
ShmSizeMB: cfg.ShmSizeMB,
AutoStopOnComplete: cfg.AutoStopOnComplete,
SessionIdleMinutes: cfg.SessionIdleMinutes,
Containers: []ContainerInfo{},
}
if !m.Enabled() {
return out
}
items, err := m.docker.ListContainersByLabel(ctx, map[string]string{
labelManaged: "true",
labelInstance: cfg.InstanceID,
})
if err != nil {
out.Available = false
out.Error = err.Error()
return out
}
out.Available = true
var staleRunning []string
for _, item := range items {
t := Target{
Scope: Scope(item.Labels[labelScope]),
OwnerID: item.Labels[labelOwnerID],
}
name := ""
if len(item.Names) > 0 {
name = strings.TrimPrefix(item.Names[0], "/")
}
ipAddr := item.IPOnNetwork(cfg.Network)
ci := ContainerInfo{
Scope: t.Scope,
OwnerID: t.OwnerID,
Name: name,
ContainerID: item.ID,
ShortID: shortID(item.ID),
IPAddress: ipAddr,
Image: item.Image,
State: item.State,
StatusText: item.Status,
CreatedAt: time.Unix(item.Created, 0).UTC().Format(time.RFC3339),
ActiveRuns: m.ActiveRuns(t),
WorkDirContainer: ContainerWorkDir,
Network: cfg.Network,
Runtime: cfg.Runtime,
}
if item.State == "running" && ipAddr != "" {
m.registerContainerIP(ipAddr, ContainerIdentity{
Scope: t.Scope,
OwnerID: t.OwnerID,
ContainerID: item.ID,
ShortID: shortID(item.ID),
ContainerName: name,
})
}
if item.State == "running" {
if st, fresh, ok := m.peekStatsCacheAny(name); ok {
ci.CPUPercent = st.CPUPercent
ci.MemUsageBytes = st.MemUsageBytes
ci.MemLimitBytes = st.MemLimitBytes
ci.PidsCurrent = st.PidsCurrent
if !fresh {
staleRunning = append(staleRunning, name)
}
} else if name != "" {
staleRunning = append(staleRunning, name)
}
}
out.Containers = append(out.Containers, ci)
}
if withStats {
var wg sync.WaitGroup
sem := make(chan struct{}, 8)
for i := range out.Containers {
if out.Containers[i].State != "running" || out.Containers[i].Name == "" {
continue
}
wg.Add(1)
sem <- struct{}{}
go func(idx int) {
defer wg.Done()
defer func() { <-sem }()
name := out.Containers[idx].Name
if st, err := m.cachedContainerStats(ctx, name); err == nil {
out.Containers[idx].CPUPercent = st.CPUPercent
out.Containers[idx].MemUsageBytes = st.MemUsageBytes
if st.MemLimitBytes > 0 {
out.Containers[idx].MemLimitBytes = st.MemLimitBytes
}
out.Containers[idx].PidsCurrent = st.PidsCurrent
}
}(i)
}
wg.Wait()
} else if len(staleRunning) > 0 {
m.triggerStatsRefresh(staleRunning)
}
sort.Slice(out.Containers, func(i, j int) bool {
if out.Containers[i].State != out.Containers[j].State {
return out.Containers[i].State == "running"
}
return out.Containers[i].Name < out.Containers[j].Name
})
return out
}
func (m *Manager) cachedContainerStats(ctx context.Context, name string) (dockerStats, error) {
if st, ok := m.peekStatsCache(name); ok {
return st, nil
}
sctx, cancel := context.WithTimeout(ctx, 4*time.Second)
defer cancel()
st, err := m.docker.ContainerStats(sctx, name)
if err != nil {
return dockerStats{}, err
}
m.statsMu.Lock()
m.statsCache[name] = cachedStats{at: time.Now(), stats: st}
m.statsMu.Unlock()
return st, nil
}
func (m *Manager) peekStatsCache(name string) (dockerStats, bool) {
st, fresh, ok := m.peekStatsCacheAny(name)
return st, ok && fresh
}
func (m *Manager) peekStatsCacheAny(name string) (dockerStats, bool, bool) {
m.statsMu.Lock()
defer m.statsMu.Unlock()
c, ok := m.statsCache[name]
if !ok {
return dockerStats{}, false, false
}
return c.stats, time.Since(c.at) <= statsCacheTTL, true
}
// triggerStatsRefresh asynchronously refreshes stale container stats in the
// background with per-container single-flight deduplication so non-blocking
// status calls stay sub-20ms while keeping stats warm.
func (m *Manager) triggerStatsRefresh(names []string) {
for _, name := range names {
if name == "" {
continue
}
m.statsMu.Lock()
if _, busy := m.statsInFlight[name]; busy {
m.statsMu.Unlock()
continue
}
m.statsInFlight[name] = struct{}{}
m.statsMu.Unlock()
go func(containerName string) {
defer func() {
m.statsMu.Lock()
delete(m.statsInFlight, containerName)
m.statsMu.Unlock()
}()
sctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
defer cancel()
if st, err := m.docker.ContainerStats(sctx, containerName); err == nil {
m.statsMu.Lock()
m.statsCache[containerName] = cachedStats{at: time.Now(), stats: st}
m.statsMu.Unlock()
}
}(name)
}
}
func (m *Manager) dropStatsCache(name string) {
m.statsMu.Lock()
delete(m.statsCache, name)
m.statsMu.Unlock()
}
// Exec runs a command inside target's sandbox container, capturing combined
// stdout+stderr up to MaxOutput bytes, enforcing Timeout, and explicitly killing
// the container process group on timeout or context cancellation.
func (m *Manager) Exec(ctx context.Context, t Target, spec ExecSpec) ExecResult {
if !m.Enabled() {
return ExecResult{ExitCode: -1, Err: errors.New("sandbox docker mode not enabled")}
}
containerID, err := m.Ensure(ctx, t)
if err != nil {
return ExecResult{ExitCode: -1, Err: err}
}
m.Acquire(t)
defer m.Release(t)
workDir := strings.TrimSpace(spec.WorkDir)
if workDir == "" {
workDir = ContainerWorkDir
}
// Ensure nested working dir (e.g. /workspace/i42) exists on host side.
if workDir != ContainerWorkDir {
if localSub, ok := ResolveConfined(m.Config().LocalRootFor(t), "", workDir); ok {
_ = ensureWritableDir(localSub, m.Config().User)
}
}
maxOut := spec.MaxOutput
if maxOut <= 0 {
maxOut = defaultMaxExecOutput
}
runCtx := ctx
var cancel context.CancelFunc
if spec.Timeout > 0 {
runCtx, cancel = context.WithTimeout(ctx, spec.Timeout)
defer cancel()
}
cmd := spec.Cmd
var pgidFile string
if spec.KillOnAbort && len(cmd) > 0 {
pgidFile = "/tmp/.artex-pgid-" + randomToken(8)
cmd = wrapPGIDCommand(pgidFile, spec.Cmd)
}
execID, err := m.docker.ExecCreate(runCtx, containerID, dockerExecCreateReq{
AttachStdin: len(spec.Stdin) > 0,
AttachStdout: true,
AttachStderr: true,
Tty: false,
Env: spec.Env,
Cmd: cmd,
WorkingDir: workDir,
User: m.Config().User,
})
if err != nil {
return ExecResult{ExitCode: -1, Err: err}
}
stream, err := m.docker.ExecStartStream(runCtx, execID)
if err != nil {
return ExecResult{ExitCode: -1, Err: err}
}
defer stream.Close()
if len(spec.Stdin) > 0 {
go func() {
_, _ = stream.Write(spec.Stdin)
_ = stream.CloseWrite()
}()
}
outBuf := newCappedBuffer(maxOut)
var readWG sync.WaitGroup
readWG.Add(2)
go func() {
defer readWG.Done()
_, _ = io.Copy(outBuf, stream.stdout)
}()
go func() {
defer readWG.Done()
_, _ = io.Copy(outBuf, stream.stderr)
}()
doneCh := make(chan error, 1)
go func() {
err := <-stream.done
readWG.Wait()
doneCh <- err
}()
var timedOut bool
var runErr error
select {
case runErr = <-doneCh:
case <-runCtx.Done():
timedOut = errors.Is(runCtx.Err(), context.DeadlineExceeded)
runErr = runCtx.Err()
_ = stream.Close()
if pgidFile != "" {
m.killProcessGroup(containerID, pgidFile)
}
select {
case <-doneCh:
case <-time.After(2 * time.Second):
}
}
res := ExecResult{
Output: outBuf.String(),
OutputTruncated: outBuf.Truncated(),
ExitCode: -1,
TimedOut: timedOut,
Err: runErr,
}
if !timedOut && ctx.Err() == nil {
inspectCtx, icancel := context.WithTimeout(context.Background(), 5*time.Second)
defer icancel()
if info, ierr := m.waitExecInspect(inspectCtx, execID); ierr == nil {
if info.Running {
if pgidFile != "" {
m.killProcessGroup(containerID, pgidFile)
}
if res.Err == nil {
res.Err = errors.New("sandbox exec stream closed prematurely while command was still running")
}
} else {
res.ExitCode = info.ExitCode
if info.ExitCode != 0 && res.Err == nil {
res.Err = fmt.Errorf("exit status %d", info.ExitCode)
}
}
}
}
return res
}
// ExecStream opens a bidirectional stdio session inside target's sandbox
// container (used by stdio MCP servers like playwright-mcp and background tasks).
func (m *Manager) ExecStream(ctx context.Context, t Target, spec ExecSpec) (*StreamSession, error) {
if !m.Enabled() {
return nil, errors.New("sandbox docker mode not enabled")
}
containerID, err := m.Ensure(ctx, t)
if err != nil {
return nil, err
}
m.Acquire(t)
workDir := strings.TrimSpace(spec.WorkDir)
if workDir == "" {
workDir = ContainerWorkDir
}
if workDir != ContainerWorkDir {
if localSub, ok := ResolveConfined(m.Config().LocalRootFor(t), "", workDir); ok {
_ = ensureWritableDir(localSub, m.Config().User)
}
}
pgidFile := "/tmp/.artex-stream-" + randomToken(8)
cmd := wrapPGIDCommand(pgidFile, spec.Cmd)
execID, err := m.docker.ExecCreate(ctx, containerID, dockerExecCreateReq{
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: false,
Env: spec.Env,
Cmd: cmd,
WorkingDir: workDir,
User: m.Config().User,
})
if err != nil {
m.Release(t)
return nil, err
}
stream, err := m.docker.ExecStartStream(ctx, execID)
if err != nil {
m.Release(t)
return nil, err
}
var releaseOnce sync.Once
release := func() {
releaseOnce.Do(func() {
m.Release(t)
})
}
stdinWriter := &hijackedWriteCloser{h: stream}
return &StreamSession{
Stdin: stdinWriter,
Stdout: stream.stdout,
Stderr: stream.stderr,
waitFn: func() (int, error) {
err := <-stream.done
release()
inspectCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if info, ierr := m.docker.ExecInspect(inspectCtx, execID); ierr == nil {
return info.ExitCode, err
}
return -1, err
},
closeFn: func() error {
err := stream.Close()
m.killProcessGroup(containerID, pgidFile)
release()
return err
},
}, nil
}
// wrapPGIDCommand records the exec process PID before replacing the shell with
// the target command. Docker's runc already places every exec process into its
// own session and process group (PID == PGID == SID), so we must NOT invoke
// util-linux `setsid` (which without `--wait` forks when PID == PGID and exits
// 0 immediately, causing containerd to cut off stdout/stderr at ~2s and masking
// non-zero exit codes).
func wrapPGIDCommand(pgidFile string, cmd []string) []string {
wrapped := fmt.Sprintf(`echo $$ > %q; exec "$@"`, pgidFile)
return append([]string{"sh", "-c", wrapped, "--"}, cmd...)
}
// waitExecInspect polls Docker ExecInspect briefly after the stdio stream closes
// so containerd's final Running->false transition settles before reading ExitCode.
func (m *Manager) waitExecInspect(ctx context.Context, execID string) (dockerExecInspect, error) {
var (
info dockerExecInspect
err error
)
backoffs := []time.Duration{0, 15 * time.Millisecond, 40 * time.Millisecond, 100 * time.Millisecond, 150 * time.Millisecond, 200 * time.Millisecond}
for _, d := range backoffs {
if d > 0 {
select {
case <-ctx.Done():
return info, ctx.Err()
case <-time.After(d):
}
}
info, err = m.docker.ExecInspect(ctx, execID)
if err != nil || !info.Running {
return info, err
}
}
return info, err
}
type hijackedWriteCloser struct {
h *hijackedExec
}
func (w *hijackedWriteCloser) Write(p []byte) (int, error) { return w.h.Write(p) }
func (w *hijackedWriteCloser) Close() error { return w.h.CloseWrite() }
// killProcessGroup sends SIGTERM then SIGKILL to the tracked process group
// inside containerID so cancelled/timed-out tools never linger.
func (m *Manager) killProcessGroup(containerID, pgidFile string) {
kctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel()
script := fmt.Sprintf(
`if [ -f %q ]; then p=$(cat %q 2>/dev/null); rm -f %q; if [ -n "$p" ]; then kill -TERM -- -"$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null || true; sleep 1; kill -KILL -- -"$p" 2>/dev/null || kill -KILL "$p" 2>/dev/null || true; fi; fi`,
pgidFile, pgidFile, pgidFile,
)
execID, err := m.docker.ExecCreate(kctx, containerID, dockerExecCreateReq{
AttachStdout: true,
AttachStderr: true,
Cmd: []string{"sh", "-c", script},
User: m.Config().User,
})
if err != nil {
return
}
s, err := m.docker.ExecStartStream(kctx, execID)
if err != nil {
return
}
defer s.Close()
go io.Copy(io.Discard, s.stdout)
go io.Copy(io.Discard, s.stderr)
select {
case <-s.done:
case <-kctx.Done():
}
}
func ensureWritableDir(dir, userSpec string) error {
if err := os.MkdirAll(dir, 0o777); err != nil {
return err
}
uid, gid := -1, -1
if os.Geteuid() == 0 && userSpec != "" {
uid, gid = parseUIDGID(userSpec)
}
// Best-effort chmod + chown on dir AND pre-existing non-symlink entries so
// workspaces migrated from root-owned standalone deployments remain writable
// by the non-root sandbox user without ever following symlinks.
_ = filepath.WalkDir(dir, func(p string, d os.DirEntry, walkErr error) error {
if walkErr != nil {
return nil
}
if d.Type()&os.ModeSymlink != 0 {
return nil
}
if d.IsDir() {
_ = os.Chmod(p, 0o777)
} else if info, err := d.Info(); err == nil {
// Preserve execute bits while ensuring non-root sandbox user can write.
_ = os.Chmod(p, info.Mode().Perm()|0o666)
}
if uid >= 0 {
_ = os.Lchown(p, uid, gid)
}
return nil
})
return nil
}
func parseUIDGID(spec string) (int, int) {
parts := strings.Split(strings.TrimSpace(spec), ":")
uid, err := strconv.Atoi(parts[0])
if err != nil {
return -1, -1
}
gid := uid
if len(parts) > 1 {
if g, err := strconv.Atoi(parts[1]); err == nil {
gid = g
}
}
return uid, gid
}
func shortID(id string) string {
if len(id) > 12 {
return id[:12]
}
return id
}
func randomToken(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
type cappedBuffer struct {
mu sync.Mutex
buf bytes.Buffer
limit int
truncated bool
}
func newCappedBuffer(limit int) *cappedBuffer { return &cappedBuffer{limit: limit} }
func (b *cappedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
n := len(p)
if b.limit <= 0 {
_, _ = b.buf.Write(p)
return n, nil
}
rem := b.limit - b.buf.Len()
if rem <= 0 {
b.truncated = true
return n, nil
}
if len(p) > rem {
_, _ = b.buf.Write(p[:rem])
b.truncated = true
return n, nil
}
_, _ = b.buf.Write(p)
return n, nil
}
func (b *cappedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
func (b *cappedBuffer) Truncated() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.truncated
}