Files
Reims-Go/internal/plugin/sidecar.go
T

530 lines
13 KiB
Go

package plugin
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"sync"
"sync/atomic"
"time"
)
// SidecarOptions configures an L3 (or future L2) supervised child process (§8).
type SidecarOptions struct {
PluginID string
ExePath string
Args []string
DataDir string
Broker *Broker
Registry *Registry
IdleTimeout time.Duration // 0 = no idle shutdown
MemLimitBytes uintptr // optional Windows Job Object memory cap (L2)
MaxRestarts int // circuit breaker threshold (default 3)
ExtraHandlers map[string]RPCRequestHandler
}
type sidecarInstance struct {
cmd *exec.Cmd
job *sidecarJob
rpc *RPCConn
stdin io.WriteCloser
exited chan struct{}
inFlight atomic.Int32
}
// SidecarSupervisor manages the lifecycle of one per-plugin Sidecar process:
// lazy start, Windows Job Object containment, Content-Length JSON-RPC 2.0
// handshake, stderr log collection, exponential backoff restart + circuit
// breaker, graceful reload, and idle reclamation (§8).
type SidecarSupervisor struct {
opts SidecarOptions
startMu sync.Mutex
mu sync.Mutex
cur *sidecarInstance
stopped bool
crashCount int
lastCrash time.Time
lastActivity time.Time
idleCancel context.CancelFunc
capabilities map[string]any
}
func NewSidecarSupervisor(opts SidecarOptions) *SidecarSupervisor {
if opts.MaxRestarts <= 0 {
opts.MaxRestarts = 3
}
return &SidecarSupervisor{
opts: opts,
lastActivity: time.Now(),
}
}
// EnsureStarted lazily launches the Sidecar process and performs the
// `plugin/initialize` handshake (§8).
func (s *SidecarSupervisor) EnsureStarted(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
return errors.New("sidecar supervisor stopped")
}
if s.cur != nil {
select {
case <-s.cur.exited:
s.cur = nil
default:
s.lastActivity = time.Now()
s.mu.Unlock()
return nil
}
}
if s.crashCount >= s.opts.MaxRestarts {
s.mu.Unlock()
return fmt.Errorf("sidecar %s circuit-broken after %d crashes", s.opts.PluginID, s.crashCount)
}
// Exponential backoff after prior crash.
backoff := time.Duration(0)
if s.crashCount > 0 {
backoff = time.Duration(200*(1<<(s.crashCount-1))) * time.Millisecond
if elapsed := time.Since(s.lastCrash); elapsed < backoff {
backoff -= elapsed
} else {
backoff = 0
}
}
s.mu.Unlock()
if backoff > 0 {
select {
case <-time.After(backoff):
case <-ctx.Done():
return ctx.Err()
}
}
inst, caps, err := s.spawnInstance(ctx)
if err != nil {
// Count start/handshake failures toward circuit breaker so broken sidecars
// don't spin infinitely on every hook call (M10).
s.mu.Lock()
if !s.stopped {
s.crashCount++
s.lastCrash = time.Now()
crashes := s.crashCount
s.mu.Unlock()
if crashes >= s.opts.MaxRestarts && s.opts.Registry != nil {
s.opts.Registry.MarkFailed(s.opts.PluginID, fmt.Sprintf("sidecar failed to start %d times: %v", crashes, err))
}
} else {
s.mu.Unlock()
}
return err
}
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
s.terminateInstance(inst)
return errors.New("sidecar stopped during startup")
}
s.cur = inst
s.capabilities = caps
s.lastActivity = time.Now()
if s.opts.IdleTimeout > 0 && s.idleCancel == nil {
idleCtx, cancel := context.WithCancel(context.Background())
s.idleCancel = cancel
go s.idleWatchLoop(idleCtx)
}
s.mu.Unlock()
return nil
}
func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance, map[string]any, error) {
if s.opts.DataDir != "" {
if err := os.MkdirAll(s.opts.DataDir, 0o755); err != nil {
return nil, nil, err
}
}
cmd := exec.Command(s.opts.ExePath, s.opts.Args...)
cmd.Dir = s.opts.DataDir
configureSidecarCmd(cmd)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
_ = stdin.Close()
return nil, nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
_ = stdin.Close()
_ = stdout.Close()
return nil, nil, err
}
job, err := newSidecarJob(s.opts.MemLimitBytes)
if err != nil {
_ = stdin.Close()
_ = stdout.Close()
_ = stderr.Close()
return nil, nil, err
}
if err := cmd.Start(); err != nil {
_ = stdin.Close()
_ = stdout.Close()
_ = stderr.Close()
job.Close()
return nil, nil, fmt.Errorf("start sidecar %s: %w", s.opts.PluginID, err)
}
if err := job.Assign(cmd.Process.Pid); err != nil {
_ = cmd.Process.Kill()
_ = cmd.Wait()
job.Close()
return nil, nil, fmt.Errorf("assign sidecar %s to job: %w", s.opts.PluginID, err)
}
rpcConn := NewRPCConn(stdout, stdin)
s.registerReverseHostAPI(rpcConn)
inst := &sidecarInstance{
cmd: cmd,
job: job,
rpc: rpcConn,
stdin: stdin,
exited: make(chan struct{}),
}
// Collect stderr into rotated plugin audit log using bufio.Reader so lines
// >64 KiB are truncated and drained instead of wedging the pipe (M10, §8).
go func() {
const maxLineBytes = 8 * 1024
br := bufio.NewReaderSize(stderr, 16*1024)
var buf []byte
truncated := false
for {
chunk, isPrefix, err := br.ReadLine()
if len(chunk) > 0 {
if len(buf) < maxLineBytes {
remain := maxLineBytes - len(buf)
if len(chunk) > remain {
buf = append(buf, chunk[:remain]...)
truncated = true
} else {
buf = append(buf, chunk...)
}
} else {
truncated = true
}
}
if !isPrefix && (len(buf) > 0 || err != nil) {
if len(buf) > 0 && s.opts.Broker != nil {
line := string(buf)
if truncated {
line += "…(truncated)"
}
s.opts.Broker.Audit(s.opts.PluginID, "STDERR", line)
}
buf = buf[:0]
truncated = false
}
if err != nil {
return
}
}
}()
// Reap via process handle (cmd.Wait), NOT pipe EOF (§8).
go func() {
err := cmd.Wait()
rpcConn.Close()
job.Close()
close(inst.exited)
s.onInstanceExit(inst, err)
}()
// Handshake: plugin/initialize exchanging pluginApi version & capabilities.
initCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var initResp struct {
PluginAPI string `json:"pluginApi"`
Capabilities map[string]any `json:"capabilities"`
}
err = rpcConn.Call(initCtx, "plugin/initialize", map[string]any{
"pluginId": s.opts.PluginID,
"pluginApi": PluginAPIVersion,
"dataDir": s.opts.DataDir,
}, &initResp)
if err != nil {
s.terminateInstance(inst)
return nil, nil, fmt.Errorf("sidecar %s handshake failed: %w", s.opts.PluginID, err)
}
return inst, initResp.Capabilities, nil
}
func (s *SidecarSupervisor) registerReverseHostAPI(conn *RPCConn) {
pid := s.opts.PluginID
broker := s.opts.Broker
conn.Handle("host/notify", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
Title string `json:"title"`
Body string `json:"body"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"ok": true}, broker.Notify(pid, req.Title, req.Body)
})
conn.Handle("host/audit", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker != nil {
if !broker.allowRate(pid, 120) {
return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid)
}
var req struct {
Message string `json:"message"`
}
_ = json.Unmarshal(raw, &req)
broker.Audit(pid, "PLUGIN", req.Message)
}
return map[string]any{"ok": true}, nil
})
conn.Handle("host/vm.spawn", func(ctx context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
VMName string `json:"vm_name"`
ExePath string `json:"exe_path"`
Args []string `json:"args"`
WorkDir string `json:"work_dir"`
Env []string `json:"env"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
vmPID, err := broker.SpawnManagedVMProcess(ctx, pid, req.VMName, req.ExePath, req.Args, req.WorkDir, req.Env)
if err != nil {
return nil, err
}
return map[string]any{"pid": vmPID}, nil
})
conn.Handle("host/vm.stop", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
var req struct {
PID int `json:"pid"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"ok": true}, broker.StopManagedVMProcess(pid, req.PID)
})
conn.Handle("host/vm.isRunning", func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return map[string]any{"running": false}, nil
}
var req struct {
PID int `json:"pid"`
}
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
return map[string]any{"running": broker.IsManagedProcessRunningForPlugin(pid, req.PID)}, nil
})
for method, h := range s.opts.ExtraHandlers {
conn.Handle(method, h)
}
}
func (s *SidecarSupervisor) onInstanceExit(inst *sidecarInstance, exitErr error) {
s.mu.Lock()
isCurrent := s.cur == inst
stopped := s.stopped
if isCurrent {
s.cur = nil
}
if !stopped && isCurrent {
s.crashCount++
s.lastCrash = time.Now()
crashes := s.crashCount
s.mu.Unlock()
if s.opts.Broker != nil {
s.opts.Broker.Audit(s.opts.PluginID, "CRASH", fmt.Sprintf("sidecar exited unexpectedly (count=%d): %v", crashes, exitErr))
}
if crashes >= s.opts.MaxRestarts && s.opts.Registry != nil {
s.opts.Registry.MarkFailed(s.opts.PluginID, fmt.Sprintf("sidecar crashed %d times: %v", crashes, exitErr))
}
return
}
s.mu.Unlock()
}
// Call lazily starts the Sidecar if needed and invokes a JSON-RPC 2.0 method.
func (s *SidecarSupervisor) Call(ctx context.Context, method string, params any, out any) error {
if err := s.EnsureStarted(ctx); err != nil {
return err
}
s.mu.Lock()
inst := s.cur
s.lastActivity = time.Now()
s.mu.Unlock()
if inst == nil {
return errors.New("sidecar not running")
}
inst.inFlight.Add(1)
defer inst.inFlight.Add(-1)
return inst.rpc.Call(ctx, method, params, out)
}
// Reload performs zero-downtime replacement: spawns new Sidecar, swaps pointer,
// drains in-flight requests on old Sidecar, then terminates old Job Object (§8).
func (s *SidecarSupervisor) Reload(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
return errors.New("sidecar supervisor stopped")
}
s.mu.Unlock()
newInst, caps, err := s.spawnInstance(ctx)
if err != nil {
return err
}
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
s.terminateInstance(newInst)
return errors.New("sidecar stopped during reload")
}
old := s.cur
s.cur = newInst
s.capabilities = caps
s.crashCount = 0
s.lastActivity = time.Now()
if s.opts.IdleTimeout > 0 && s.idleCancel == nil {
idleCtx, cancel := context.WithCancel(context.Background())
s.idleCancel = cancel
go s.idleWatchLoop(idleCtx)
}
s.mu.Unlock()
if old != nil {
go func() {
deadline := time.Now().Add(5 * time.Second)
for old.inFlight.Load() > 0 && time.Now().Before(deadline) {
time.Sleep(25 * time.Millisecond)
}
s.terminateInstance(old)
}()
}
return nil
}
// IsRunning reports whether a Sidecar child process is currently alive.
func (s *SidecarSupervisor) IsRunning() bool {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil {
return false
}
select {
case <-inst.exited:
return false
default:
return true
}
}
// PID returns the current Sidecar child process ID (0 if not running).
func (s *SidecarSupervisor) PID() int {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil || inst.cmd == nil || inst.cmd.Process == nil {
return 0
}
return inst.cmd.Process.Pid
}
func (s *SidecarSupervisor) idleWatchLoop(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.mu.Lock()
inst := s.cur
idle := time.Since(s.lastActivity)
timeout := s.opts.IdleTimeout
if inst != nil && timeout > 0 && idle >= timeout && inst.inFlight.Load() == 0 {
s.cur = nil
s.mu.Unlock()
s.terminateInstance(inst)
} else {
s.mu.Unlock()
}
}
}
}
func (s *SidecarSupervisor) terminateInstance(inst *sidecarInstance) {
if inst == nil {
return
}
_ = inst.rpc.Notify(context.Background(), "plugin/shutdown", nil)
_ = inst.stdin.Close()
select {
case <-inst.exited:
case <-time.After(800 * time.Millisecond):
inst.job.Close()
select {
case <-inst.exited:
case <-time.After(1 * time.Second):
}
}
inst.job.Close()
inst.rpc.Close()
}
// Stop terminates the Sidecar and its entire Job Object process tree cleanly.
func (s *SidecarSupervisor) Stop() {
s.mu.Lock()
s.stopped = true
inst := s.cur
s.cur = nil
cancel := s.idleCancel
s.idleCancel = nil
s.mu.Unlock()
if cancel != nil {
cancel()
}
s.terminateInstance(inst)
}