pkg/service/process_pool.go
package service
import (
"bufio"
"context"
"fmt"
"io"
"log/slog"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"sync"
"sync/atomic"
"time"
"git.cafe/ezterry/ez-agent/internal/builtinconfig"
"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
"git.cafe/ezterry/ez-agent/pkg/service/config"
)
const (
processOutputDrainTimeout = 250 * time.Millisecond
processRetireTimeout = 2 * time.Second
processRetryDelay = 250 * time.Millisecond
)
type ProcessPool struct {
mu sync.Mutex
backgroundStart sync.Mutex // fences ancestry snapshots around background exec
sandboxBackgroundStart sync.Mutex // same fence for the restricted listener only
procs map[string]*childRecord
spawning map[string]*spawnFlight
closed bool
outputDrainTimeout time.Duration
bubblewrap atomic.Pointer[bubblewrapLauncher] // nil when off or awaiting a decoded startup config
restrictedSocket atomic.Pointer[sandboxSocket] // captured before the first provider launch
sandboxOnce sync.Once
sandboxErr error // set under mu at the end of sandboxOnce
sandboxSystem *sandboxSystem // guarded by mu
sandboxCancel context.CancelFunc // guarded by mu, cancels only setup
}
type childRecord struct {
name string
serviceConfig config.ServiceConfig
hostHub bool // fixed at admission; not owned by the sandbox
conn *Connection
cmd *serviceChild
published bool
retiring bool
done chan struct{}
finished chan struct{}
finishOnce sync.Once
stdoutR *os.File
stderrR *os.File
sandboxedBackground bool
backgroundPeers map[net.Conn]struct{} // guarded by ProcessPool.mu
once sync.Once
}
type spawnFlight struct {
done chan struct{}
serviceConfig config.ServiceConfig
hostHub *exec.Cmd
conn *Connection
err error
waiters int
retryAfter time.Time
}
func NewProcessPool() *ProcessPool {
return newProcessPool(nil)
}
func newProcessPool(bubblewrap *bubblewrapLauncher) *ProcessPool {
p := &ProcessPool{
procs: make(map[string]*childRecord),
spawning: make(map[string]*spawnFlight),
outputDrainTimeout: processOutputDrainTimeout,
}
p.bubblewrap.Store(bubblewrap)
p.watchPrivateNetwork(bubblewrap)
return p
}
type SpawnCallbacks struct {
connectionID func() string
RegisterConn func(*Connection)
CleanupConn func(*Connection)
ServiceOptions func(*Connection) ezagentapi.ServiceOptions
// CredentialEnvironmentNames returns auth-configured environment variable
// names whose values must not be inherited by a spawned service.
CredentialEnvironmentNames func() []string
}
func newProcessConnection(name string, process *os.Process, service config.ServiceConfig, allocateID func() string) *Connection {
if allocateID == nil {
allocateID = freshConnectionID
}
return &Connection{
ID: allocateID(), Name: name, process: process,
helloCh: make(chan struct{}), announceCh: make(chan struct{}), infoCh: make(chan struct{}),
launchedServiceName: name, launchedService: &service,
}
}
func (p *ProcessPool) GetOrSpawn(serviceName string, cfg *config.ServiceConfig, cb SpawnCallbacks) (*Connection, error) {
if cfg == nil || !cfg.Direct {
return nil, fmt.Errorf("service %s is not configured for direct JSONL", serviceName)
}
return p.getOrSpawn(serviceName, cfg, cb)
}
// RecoverDirectConn retires stale only if it still owns the configured service,
// then shares one replacement startup with other pool callers. A healthy matching
// replacement is reused. The caller must authorize recovery before dispatch;
// this method never replays a request. Cancellation stops this caller's wait, not
// the shared startup. Failed starts are briefly shared to limit restart churn.
func (p *ProcessPool) RecoverDirectConn(ctx context.Context, serviceName string, cfg *config.ServiceConfig, stale *Connection, cb SpawnCallbacks) (*Connection, error) {
if cfg == nil || !cfg.Direct {
return nil, fmt.Errorf("service %s is not configured for direct JSONL", serviceName)
}
if stale == nil || stale.launchedServiceName != serviceName || stale.launchedService == nil || !reflect.DeepEqual(*stale.launchedService, cloneServiceConfig(*cfg)) {
return nil, fmt.Errorf("service %s recovery configuration does not match stale connection", serviceName)
}
startupTimeout, err := cfg.ParsedStartupTimeout()
if err != nil {
return nil, fmt.Errorf("service %s: %w", serviceName, err)
}
// Include the existing optional announce wait and the bounded retirement.
retireTimeout := processRetireTimeout
if p.bubblewrap.Load() != nil {
retireTimeout = sandboxRetireTimeout(startupTimeout)
}
ctx, cancel := context.WithTimeout(ctx, startupTimeout+5*time.Second+retireTimeout)
defer cancel()
return p.getOrSpawnContext(ctx, serviceName, cfg, stale, cb)
}
// StartService starts one configured service generation if it is not already
// running or starting. Direct and background services share singleton and
// startup-flight ownership.
func (p *ProcessPool) StartService(serviceName string, cfg *config.ServiceConfig, cb SpawnCallbacks) error {
if cfg == nil {
return fmt.Errorf("service %s has no configuration", serviceName)
}
_, err := p.getOrSpawn(serviceName, cfg, cb)
return err
}
func cloneServiceConfig(cfg config.ServiceConfig) config.ServiceConfig {
cfg.Args = append([]string(nil), cfg.Args...)
cfg.Tools = append([]string(nil), cfg.Tools...)
cfg.Plugins = append([]string(nil), cfg.Plugins...)
cfg.Macros = append([]string(nil), cfg.Macros...)
return cfg
}
func (p *ProcessPool) getOrSpawn(connName string, cfg *config.ServiceConfig, cb SpawnCallbacks) (*Connection, error) {
return p.getOrSpawnContext(context.Background(), connName, cfg, nil, cb)
}
// recordHealthy is called under p.mu. Transport closure is terminal even when
// the OS process is still alive or callback cleanup has not finished yet.
func recordHealthy(rec *childRecord) bool {
if rec.retiring {
return false
}
select {
case <-rec.done:
return false
default:
}
if rec.serviceConfig.Direct {
if rec.conn == nil || rec.conn.apiConn == nil {
return false
}
select {
case <-rec.conn.apiConn.Closed():
return false
default:
}
}
return true
}
func (p *ProcessPool) getOrSpawnContext(ctx context.Context, connName string, cfg *config.ServiceConfig, stale *Connection, cb SpawnCallbacks) (*Connection, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
snapshot := cloneServiceConfig(*cfg)
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return nil, fmt.Errorf("process pool is shut down")
}
rec := p.procs[connName]
flight := p.spawning[connName]
if flight != nil {
select {
case <-flight.done:
if flight.err == nil || (flight.waiters == 0 && !time.Now().Before(flight.retryAfter)) {
delete(p.spawning, connName)
flight = nil
}
default:
}
}
if stale != nil && ((rec != nil && !reflect.DeepEqual(rec.serviceConfig, snapshot)) || (flight != nil && !reflect.DeepEqual(flight.serviceConfig, snapshot))) {
p.mu.Unlock()
return nil, fmt.Errorf("service %s is already managed with a different configuration", connName)
}
if rec != nil && rec.published && recordHealthy(rec) && (stale == nil || rec.conn != stale) {
if err := p.launchFailureLocked(rec.hostHub); err != nil {
p.mu.Unlock()
return nil, err
}
if cfg.Direct && rec.conn == nil {
p.mu.Unlock()
return nil, fmt.Errorf("service %s is already running without direct JSONL", connName)
}
p.mu.Unlock()
return rec.conn, nil
}
if flight == nil {
if rec != nil && stale == nil {
// Ordinary callers follow the first owner, including while it is
// retiring. Keep its configuration and await cleanup rather than
// letting an incidental caller change the managed service.
if cfg.Direct && !rec.serviceConfig.Direct {
p.mu.Unlock()
return nil, fmt.Errorf("service %s is retiring without direct JSONL", connName)
}
snapshot = rec.serviceConfig
}
var hostHub *exec.Cmd
if p.bubblewrap.Load() != nil {
hostHub = installedHubCommand(&snapshot)
}
if err := p.launchFailureLocked(hostHub != nil); err != nil {
p.mu.Unlock()
return nil, err
}
flight = &spawnFlight{done: make(chan struct{}), serviceConfig: snapshot, hostHub: hostHub}
p.spawning[connName] = flight
if rec != nil {
rec.retiring = true
} else {
rec = newChildRecord(connName, flight)
p.procs[connName] = rec
}
go p.runSpawnFlight(rec, flight, cb)
} else if err := p.launchFailureLocked(flight.hostHub != nil); err != nil {
p.mu.Unlock()
return nil, err
}
flight.waiters++
p.mu.Unlock()
select {
case <-ctx.Done():
case <-flight.done:
}
p.mu.Lock()
c, err := flight.conn, flight.err
if ctx.Err() != nil {
c, err = nil, ctx.Err()
} else if failure := p.launchFailureLocked(flight.hostHub != nil); failure != nil {
c, err = nil, failure
} else if err == nil && (p.closed || p.procs[connName] == nil || p.procs[connName].conn != c || !recordHealthy(p.procs[connName])) {
c, err = nil, fmt.Errorf("service %s exited during startup or pool shut down", connName)
}
flight.waiters--
p.releaseFlightLocked(connName, flight)
p.mu.Unlock()
return c, err
}
func newChildRecord(name string, flight *spawnFlight) *childRecord {
return &childRecord{
name: name,
serviceConfig: flight.serviceConfig,
hostHub: flight.hostHub != nil,
done: make(chan struct{}),
finished: make(chan struct{}),
}
}
func (p *ProcessPool) releaseFlightLocked(name string, flight *spawnFlight) {
select {
case <-flight.done:
if flight.waiters == 0 && flight.err == nil && p.spawning[name] == flight {
delete(p.spawning, name)
}
default:
}
}
func (p *ProcessPool) runSpawnFlight(rec *childRecord, flight *spawnFlight, cb SpawnCallbacks) {
connName := rec.name
cfg := &flight.serviceConfig
launcher := p.bubblewrap.Load()
if flight.hostHub != nil {
launcher = nil
}
var c *Connection
var err error
p.mu.Lock()
retiring := rec.retiring
retireTimeout := processRetireTimeout
if rec.cmd != nil && rec.cmd.system != nil {
retireTimeout = rec.cmd.retireTimeout
}
p.mu.Unlock()
if retiring {
p.stopRecord(rec)
timer := time.NewTimer(retireTimeout)
select {
case <-rec.finished:
case <-timer.C:
err = fmt.Errorf("service %s retirement timed out", connName)
}
timer.Stop()
if err == nil {
p.mu.Lock()
if p.closed {
err = fmt.Errorf("process pool is shut down")
} else {
rec = newChildRecord(connName, flight)
p.procs[connName] = rec
}
p.mu.Unlock()
}
}
if err == nil {
c, err = p.launch(rec, cfg, cb, launcher, flight.hostHub)
}
p.mu.Lock()
if failure := p.launchFailureLocked(flight.hostHub != nil); failure != nil {
err = failure
}
if err == nil && (p.closed || !recordHealthy(rec) || p.procs[connName] != rec) {
err = fmt.Errorf("service %s exited during startup or pool shut down", connName)
}
if err == nil {
rec.published = true
} else {
rec.retiring = true
p.mu.Unlock()
if launcher != nil {
err = fmt.Errorf("service %s unavailable (Bubblewrap launch): %w", connName, err)
slog.Warn("sandboxed service unavailable", "service", connName, "error", err)
}
p.stopRecord(rec)
p.mu.Lock()
started := rec.cmd != nil
p.mu.Unlock()
if !started {
p.cleanupRecord(rec, cb)
}
p.mu.Lock()
}
flight.conn, flight.err = c, err
if err != nil {
flight.conn = nil
flight.retryAfter = time.Now().Add(processRetryDelay)
}
close(flight.done)
p.releaseFlightLocked(connName, flight)
p.mu.Unlock()
}
func (rec *childRecord) markFinished() {
rec.finishOnce.Do(func() { close(rec.finished) })
}
func (p *ProcessPool) spawnDirectProcess(rec *childRecord, cmd *serviceChild, startupTimeout time.Duration, cb SpawnCallbacks, launcher *bubblewrapLauncher) (*Connection, error) {
sandboxed := launcher != nil
connName := rec.name
// Own the pipe endpoints explicitly. cmd.Wait therefore never owns or
// closes the daemon's readers and may reap the direct child independently
// of descendants which inherited its stdout/stderr descriptors.
stdinR, stdinW, err := os.Pipe()
if err != nil {
return nil, fmt.Errorf("stdin pipe: %w", err)
}
stdoutR, stdoutW, err := os.Pipe()
if err != nil {
stdinR.Close()
stdinW.Close()
return nil, fmt.Errorf("stdout pipe: %w", err)
}
stderrR, stderrW, err := os.Pipe()
if err != nil {
stdinR.Close()
stdinW.Close()
stdoutR.Close()
stdoutW.Close()
return nil, fmt.Errorf("stderr pipe: %w", err)
}
closeAll := func() {
stdinR.Close()
stdinW.Close()
stdoutR.Close()
stdoutW.Close()
stderrR.Close()
stderrW.Close()
}
cmd.Stdin, cmd.Stdout, cmd.Stderr = stdinR, stdoutW, stderrW
err = cmd.start(startupTimeout)
if err != nil {
closeAll()
return nil, fmt.Errorf("starting service process: %w", err)
}
// The child-side copies must not keep EOF from the daemon's readers.
_ = stdinR.Close()
_ = stdoutW.Close()
_ = stderrW.Close()
p.mu.Lock()
rec.cmd, rec.stdoutR, rec.stderrR = cmd, stdoutR, stderrR
closed := p.closed
p.mu.Unlock()
if closed {
_ = cmd.stop()
}
slog.Info("service process spawned", "service", connName, "pid", cmd.Process.Pid)
stderrDone := make(chan struct{})
go func() {
logProcessStderr(connName, cmd.Process.Pid, stderrR)
close(stderrDone)
}()
launchConfig := cloneServiceConfig(rec.serviceConfig)
c := newProcessConnection(connName, cmd.Process, launchConfig, cb.connectionID)
c.sandboxedProvider = sandboxed
helloCh, announceCh := c.helloCh, c.announceCh
closeFn := func() error {
_ = stdinW.Close()
_ = stdoutR.Close()
if cmd.Process != nil {
return cmd.stop()
}
return nil
}
opts := ezagentapi.ServiceOptions{}
if cb.ServiceOptions != nil {
opts = cb.ServiceOptions(c)
}
ec := ezagentapi.AcceptServiceConn(bufio.NewReader(stdoutR), stdinW, closeFn, opts)
c.apiConn = ec
p.mu.Lock()
rec.conn = c
p.mu.Unlock()
ecDone := make(chan struct{})
registered := make(chan struct{})
var waitErr error // Published by closing rec.done; contains OS wait status only.
exitError := func(phase string) error {
err := fmt.Errorf("service %s exited %s", connName, phase)
if !sandboxed {
return err
}
if waitErr != nil {
err = fmt.Errorf("%w: %w", err, waitErr)
}
return err
}
// EOF is a failed direct service even if the child keeps running. Watch the
// transport, not Wait(), which also joins potentially blocked callbacks.
go func() {
<-ec.Closed()
p.mu.Lock()
rec.retiring = true
p.mu.Unlock()
_ = ec.Close()
_ = cmd.stop()
<-rec.done
slog.Info("service process connection closed", "service", connName, "conn_id", c.ID, "pid", cmd.Process.Pid, "wait_error", waitErr)
}()
// Exactly one owner waits immediately. Reaping does not depend on pipe EOF.
go func() {
waitErr = cmd.wait()
close(rec.done)
// Allow final buffered JSONL/stderr data to drain normally, but inherited
// descendant descriptors may not retain this lifecycle indefinitely.
timer := time.NewTimer(p.outputDrainTimeout)
ecDrainDone, stderrDrainDone := ecDone, stderrDone
for ecDrainDone != nil || stderrDrainDone != nil {
select {
case <-ecDrainDone:
ecDrainDone = nil
case <-stderrDrainDone:
stderrDrainDone = nil
case <-timer.C:
if ecDrainDone != nil {
_ = stdoutR.Close()
_ = ec.Close()
}
if stderrDrainDone != nil {
_ = stderrR.Close()
}
ecDrainDone, stderrDrainDone = nil, nil
}
}
if !timer.Stop() {
select {
case <-timer.C:
default:
}
}
<-registered
p.cleanupRecord(rec, cb)
rec.markFinished()
}()
// Registration happens-before cleanup even if Wait returned immediately.
if cb.RegisterConn != nil {
cb.RegisterConn(c)
}
close(registered)
// Publish before accepting capability claims or metadata from this instance.
go func() {
if err := ec.Start(); err != nil {
slog.Warn("service process connection ended during startup", "service", connName, "pid", cmd.Process.Pid, "error", err)
}
_ = ec.Wait()
close(ecDone)
}()
select {
case <-helloCh:
case <-rec.done:
return nil, exitError("before hello")
case <-time.After(startupTimeout):
_ = cmd.stop()
return nil, fmt.Errorf("service %s failed to complete hello handshake", connName)
}
select {
case <-announceCh:
case <-rec.done:
if sandboxed && !c.helloDone.Load() {
return nil, exitError("before hello")
}
return nil, exitError("during handshake")
case <-time.After(5 * time.Second):
}
if !c.helloDone.Load() {
if sandboxed {
select {
case <-rec.done:
return nil, exitError("before hello")
default:
}
}
_ = cmd.stop()
return nil, fmt.Errorf("service %s failed to complete handshake", connName)
}
select {
case <-rec.done:
return nil, exitError("during handshake")
default:
}
return c, nil
}
// directChildEnvironment preserves ordinary service settings, including XDG,
// locale, and sanitized proxy-routing variables, but does not pass common
// provider credentials into every configured subprocess. This is exposure
// reduction, not a process sandbox. AGENTCLI is rebuilt from the running
// installation.
func directChildEnvironment(credentialNames ...string) []string {
env := filterChildEnvironment(os.Environ(), credentialNames...)
serviceExe, err := physicalServiceExecutable()
if err != nil {
return env
}
if agentCLI := agentCLIForServiceExecutable(serviceExe); agentCLI != "" {
env = append(env, "AGENTCLI="+agentCLI)
}
return env
}
func spawnCredentialEnvironmentNames(cb SpawnCallbacks) []string {
if cb.CredentialEnvironmentNames == nil {
return nil
}
return cb.CredentialEnvironmentNames()
}
func filterChildEnvironment(env []string, credentialNames ...string) []string {
configured := make(map[string]bool, len(credentialNames))
for _, name := range credentialNames {
configured[strings.ToUpper(name)] = true
}
out := make([]string, 0, len(env))
for _, entry := range env {
name, value, found := strings.Cut(entry, "=")
if !found || configured[strings.ToUpper(name)] || childEnvironmentCredential(name) {
continue
}
if childProxyEnvironment(name) {
var ok bool
value, ok = stripProxyCredentials(value)
if !ok {
continue
}
entry = name + "=" + value
}
out = append(out, entry)
}
return out
}
func childEnvironmentCredential(name string) bool {
upper := strings.ToUpper(name)
switch upper {
case "AGENTCLI", builtinconfig.SandboxEnv, builtinconfig.SandboxNetworkEnv,
"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY",
"AZURE_OPENAI_API_KEY", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN",
"GITHUB_TOKEN", "GH_TOKEN":
return true
}
for _, suffix := range []string{"_API_KEY", "_SECRET_KEY", "_ACCESS_TOKEN", "_REFRESH_TOKEN", "_AUTH_TOKEN", "_TOKEN", "_PASSWORD", "_CREDENTIALS", "_SECRET"} {
if strings.HasSuffix(upper, suffix) {
return true
}
}
return false
}
func childProxyEnvironment(name string) bool {
switch strings.ToUpper(name) {
case "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY":
return true
default:
return false
}
}
func stripProxyCredentials(value string) (string, bool) {
if value == "" || !strings.Contains(value, "@") {
return value, true
}
prefix := ""
parseValue := value
if !strings.Contains(value, "://") {
prefix = "http://"
parseValue = prefix + value
}
parsed, err := url.Parse(parseValue)
if err != nil || parsed.Host == "" || parsed.User == nil {
return "", false
}
parsed.User = nil
safe := parsed.String()
if prefix != "" {
safe = strings.TrimPrefix(safe, prefix)
}
return safe, true
}
func agentCLIForServiceExecutable(serviceExe string) string {
if serviceExe == "" {
return ""
}
candidate := filepath.Join(filepath.Dir(serviceExe), "ez-agent")
info, err := os.Stat(candidate)
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 {
return ""
}
abs, err := filepath.Abs(candidate)
if err != nil {
return ""
}
return abs
}
func removeEnvironmentKey(env []string, key string) []string {
prefix := key + "="
out := make([]string, 0, len(env))
for _, entry := range env {
if !strings.HasPrefix(entry, prefix) {
out = append(out, entry)
}
}
return out
}
func logProcessStderr(connName string, pid int, r io.Reader) {
scanner := bufio.NewScanner(r)
// Child diagnostics can include structured log records and provider errors.
// Keep the scanner from silently stopping at its small default token limit.
scanner.Buffer(make([]byte, 64*1024), 1024*1024)
for scanner.Scan() {
slog.Info("service process stderr", "service", connName, "pid", pid, "message", scanner.Text())
}
if err := scanner.Err(); err != nil {
slog.Warn("service process stderr read failed", "service", connName, "pid", pid, "error", err)
}
}
// backgroundServicePIDs snapshots live background children for socket accept.
// It includes children that can connect before their startup flight publishes.
func (p *ProcessPool) backgroundServicePIDs() map[int]struct{} {
p.backgroundStart.Lock()
defer p.backgroundStart.Unlock()
p.mu.Lock()
defer p.mu.Unlock()
var pids map[int]struct{}
for _, rec := range p.procs {
if rec.serviceConfig.Direct || rec.cmd == nil {
continue
}
select {
case <-rec.done:
continue
default:
}
if pids == nil {
pids = make(map[int]struct{})
}
pids[rec.cmd.owner().Pid] = struct{}{}
}
return pids
}
func (p *ProcessPool) Get(connName string) *Connection {
p.mu.Lock()
defer p.mu.Unlock()
if p.sandboxFailureLocked() != nil {
return nil
}
if rec := p.procs[connName]; rec != nil && rec.published && recordHealthy(rec) {
return rec.conn
}
return nil
}
func (p *ProcessPool) Remove(c *Connection) {
p.mu.Lock()
for _, rec := range p.procs {
if rec.conn == c {
// Keep ownership until the reaper and cleanup callback finish. A
// replacement must not overtake cleanup of this generation.
rec.retiring = true
p.mu.Unlock()
p.stopRecord(rec)
return
}
}
p.mu.Unlock()
}
func (p *ProcessPool) Shutdown() {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return
}
p.closed = true
system := p.sandboxSystem
if p.sandboxCancel != nil {
p.sandboxCancel()
}
if launcher := p.bubblewrap.Load(); launcher != nil && launcher.network != nil {
defer launcher.network.close()
}
slog.Info("process pool shutting down", "process_count", len(p.procs))
recs := make([]*childRecord, 0, len(p.procs))
for _, rec := range p.procs {
recs = append(recs, rec)
}
p.mu.Unlock()
if system != nil {
system.close()
}
for _, rec := range recs {
p.stopRecord(rec)
}
// Every admitted record has a lifecycle completion channel, including a
// spawn that has not reached cmd.Start yet. Waiting on all records prevents
// daemon exit from racing the eventual kill and cmd.Wait owner.
timer := time.NewTimer(2 * time.Second)
defer timer.Stop()
for _, rec := range recs {
select {
case <-rec.finished:
case <-timer.C:
return
}
}
}
// The first decoded config can supply a startup policy after NewServer.
func (p *ProcessPool) installBubblewrap(launcher *bubblewrapLauncher) {
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
if launcher.network != nil {
launcher.network.close()
}
return
}
p.bubblewrap.Store(launcher)
p.watchPrivateNetwork(launcher)
}
func (l *bubblewrapLauncher) privateNetworkHelper() *sandboxPasta {
if l != nil && l.network != nil {
return l.network.pasta
}
return nil
}
func (p *ProcessPool) sandboxFailureLocked() error {
if helper := p.bubblewrap.Load().privateNetworkHelper(); helper != nil {
if err := helper.failure(); err != nil {
return fmt.Errorf("private-localhost network unavailable until daemon restart: %w", err)
}
}
return p.sandboxSystem.failure()
}
// sandboxUnavailableReason reports a recorded startup policy, setup or
// shared-system failure; nil means the sandbox has not failed so far.
func (p *ProcessPool) sandboxUnavailableReason() error {
l := p.bubblewrap.Load()
if l == nil {
return nil
}
if l.err != nil {
return l.err
}
p.mu.Lock()
defer p.mu.Unlock()
if p.sandboxErr != nil {
return p.sandboxErr
}
return p.sandboxFailureLocked()
}
func (p *ProcessPool) launchFailureLocked(hostHub bool) error {
if hostHub {
return nil
}
return p.sandboxFailureLocked()
}
func (p *ProcessPool) watchPrivateNetwork(launcher *bubblewrapLauncher) {
helper := launcher.privateNetworkHelper()
if helper == nil {
return
}
go func() {
<-helper.done
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return
}
system := p.sandboxSystem
p.mu.Unlock()
slog.Warn("Bubblewrap private-localhost network lost; restart the daemon", "error", helper.failure())
if system != nil {
system.close()
}
}()
}
func (p *ProcessPool) sharedSandbox(l *bubblewrapLauncher, env []string) (*sandboxSystem, error) {
p.sandboxOnce.Do(func() {
var setupErr error
defer func() { p.mu.Lock(); p.sandboxErr = setupErr; p.mu.Unlock() }()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p.mu.Lock()
if p.closed {
p.mu.Unlock()
setupErr = fmt.Errorf("process pool is shut down")
return
}
p.sandboxCancel = cancel
p.mu.Unlock()
cmd, err := l.keeperCommand(p.restrictedSocket.Load(), env)
if err != nil {
setupErr = fmt.Errorf("setting up shared Bubblewrap system: %w", err)
return
}
defer closeSandboxFiles(cmd)
system, err := startSandboxSystem(ctx, cmd, 5*time.Second, l.network != nil)
if err != nil {
setupErr = err
return
}
p.mu.Lock()
failure := p.sandboxFailureLocked()
if p.closed || failure != nil {
p.mu.Unlock()
system.close()
setupErr = failure
return
}
p.sandboxSystem = system
p.mu.Unlock()
go p.watchSandboxSystem(system)
})
if p.sandboxErr != nil {
return nil, p.sandboxErr
}
p.mu.Lock()
defer p.mu.Unlock()
if p.closed {
return nil, fmt.Errorf("process pool is shut down")
}
if err := p.sandboxFailureLocked(); err != nil {
return nil, err
}
return p.sandboxSystem, nil
}
func (p *ProcessPool) watchSandboxSystem(system *sandboxSystem) {
<-system.done
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return
}
records := make([]*childRecord, 0, len(p.procs))
for _, rec := range p.procs {
if rec.hostHub {
continue
}
rec.retiring = true
records = append(records, rec)
}
p.mu.Unlock()
slog.Warn("shared Bubblewrap system lost", "error", system.failure())
system.close()
for _, rec := range records {
p.stopRecord(rec)
}
}
func (p *ProcessPool) stopRecord(rec *childRecord) {
p.mu.Lock()
c, cmd, stdoutR, stderrR := rec.conn, rec.cmd, rec.stdoutR, rec.stderrR
p.mu.Unlock()
if stdoutR != nil {
_ = stdoutR.Close()
}
if stderrR != nil {
_ = stderrR.Close()
}
if c != nil && c.apiConn != nil {
_ = c.apiConn.Close()
}
if cmd != nil && cmd.Process != nil {
_ = cmd.stop()
}
}
func (p *ProcessPool) cleanupRecord(rec *childRecord, cb SpawnCallbacks) {
rec.once.Do(func() {
p.mu.Lock()
c := rec.conn
rec.retiring = true
peers := rec.backgroundPeers
rec.backgroundPeers = nil
p.mu.Unlock()
for peer := range peers {
_ = peer.Close()
}
if c != nil && cb.CleanupConn != nil {
cb.CleanupConn(c)
}
p.mu.Lock()
if rec.finished != nil {
rec.markFinished()
}
if p.procs[rec.name] == rec {
delete(p.procs, rec.name)
}
p.mu.Unlock()
})
}
func (p *ProcessPool) dropBackgroundPeer(rec *childRecord, conn net.Conn) {
p.mu.Lock()
delete(rec.backgroundPeers, conn)
p.mu.Unlock()
}