ollie/toolsrv/spawn.go

244 lines
5.5 KiB
Go

// spawn.go - Process spawning and lifecycle management for toolsrv.
package toolsrv
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
)
// Process represents a running toolsrv process.
type Process struct {
Cmd *exec.Cmd
SocketPath string
Secret string
Info ProcessInfo
cancel context.CancelFunc
}
// ProcessInfo contains metadata about the toolsrv process.
type ProcessInfo struct {
Platform string
IsGitRepo bool
}
// Option configures spawning behavior.
type Option func(*spawnConfig)
type spawnConfig struct {
yolo bool
}
// WithYolo disables sandbox enforcement.
func WithYolo() Option {
return func(c *spawnConfig) { c.yolo = true }
}
// Spawn starts a local toolsrv process.
func Spawn(ctx context.Context, cwd string, opts ...Option) (*Process, error) {
cfg := &spawnConfig{}
for _, opt := range opts {
opt(cfg)
}
// Generate socket path and secret
socketPath := filepath.Join(os.TempDir(), fmt.Sprintf("toolsrv-%d-%s.sock", os.Getpid(), randomHex(8)))
secret := randomHex(32)
// Find toolsrv binary
toolsrvPath, err := findToolsrv()
if err != nil {
return nil, fmt.Errorf("find toolsrv: %w", err)
}
// Build command
args := []string{"serve", "--cwd", cwd, "--listen", socketPath}
if cfg.yolo {
args = append(args, "--yolo")
}
procCtx, cancel := context.WithCancel(ctx)
cmd := exec.CommandContext(procCtx, toolsrvPath, args...)
// Note: secret is NOT passed via env var. It's established on first
// connection via 9P Tauth (socket permissions + SSH handle security).
cmd.Stderr = os.Stderr // Let server errors go to stderr for debugging
if err := cmd.Start(); err != nil {
cancel()
return nil, fmt.Errorf("start toolsrv: %w", err)
}
// Wait for socket to be ready
if err := waitForSocket(socketPath, 5*time.Second); err != nil {
cancel()
cmd.Process.Kill()
return nil, fmt.Errorf("wait for socket: %w", err)
}
return &Process{
Cmd: cmd,
SocketPath: socketPath,
Secret: secret,
Info: ProcessInfo{
Platform: "linux",
IsGitRepo: false, // Caller can override
},
cancel: cancel,
}, nil
}
// Kill terminates the process.
func (p *Process) Kill() error {
if p.cancel != nil {
p.cancel()
}
if p.Cmd != nil && p.Cmd.Process != nil {
return p.Cmd.Process.Kill()
}
return nil
}
// Close terminates the process (alias for Kill).
func (p *Process) Close() error {
return p.Kill()
}
// Wait waits for the process to exit.
func (p *Process) Wait() error {
if p.Cmd != nil {
return p.Cmd.Wait()
}
return nil
}
// RemoteConfig configures remote toolsrv spawning.
type RemoteConfig struct {
SSHTarget string // user@host or host
CWD string
}
// SpawnRemote starts a remote toolsrv process via SSH.
func SpawnRemote(ctx context.Context, cfg RemoteConfig) (*Process, error) {
// For now, return an error - remote spawning requires SSH bootstrap
return nil, fmt.Errorf("remote spawning not yet implemented for 9P")
}
// ProcessKeeper manages process lifecycle with automatic respawning.
type ProcessKeeper struct {
ctx context.Context
proc *Process
respawn func(context.Context) (*Process, error)
mu sync.Mutex
}
// NewProcessKeeper creates a new process keeper.
func NewProcessKeeper(ctx context.Context, proc *Process, respawn func(context.Context) (*Process, error)) *ProcessKeeper {
return &ProcessKeeper{
ctx: ctx,
proc: proc,
respawn: respawn,
}
}
// SetContext updates the context used for respawning.
func (pk *ProcessKeeper) SetContext(ctx context.Context) {
pk.mu.Lock()
defer pk.mu.Unlock()
pk.ctx = ctx
}
// Dial connects to the managed process, respawning if necessary.
func (pk *ProcessKeeper) Dial() (*Conn, error) {
pk.mu.Lock()
defer pk.mu.Unlock()
// Try to connect to existing process
if pk.proc != nil {
conn, err := Dial(pk.proc.SocketPath, pk.proc.Secret)
if err == nil {
// Save the secret if this was first connection
if pk.proc.Secret == "" {
pk.proc.Secret = conn.Secret()
}
return conn, nil
}
// Process may have died, try to respawn
}
if pk.respawn != nil {
proc, err := pk.respawn(pk.ctx)
if err != nil {
return nil, fmt.Errorf("respawn: %w", err)
}
pk.proc = proc
conn, err := Dial(proc.SocketPath, proc.Secret)
if err != nil {
return nil, err
}
return conn, nil
}
return nil, fmt.Errorf("no process available")
}
// Close terminates the managed process.
func (pk *ProcessKeeper) Close() error {
pk.mu.Lock()
defer pk.mu.Unlock()
if pk.proc != nil {
return pk.proc.Kill()
}
return nil
}
// --- Helpers ---
func randomHex(n int) string {
b := make([]byte, n)
rand.Read(b)
return hex.EncodeToString(b)
}
func findToolsrv() (string, error) {
// Check if toolsrv is in PATH
if path, err := exec.LookPath("toolsrv"); err == nil {
return path, nil
}
// Check common locations
home, _ := os.UserHomeDir()
candidates := []string{
filepath.Join(home, ".config", "ollie", "bin", "toolsrv"),
filepath.Join(home, "go", "bin", "toolsrv"),
"/usr/local/bin/toolsrv",
}
for _, p := range candidates {
if _, err := os.Stat(p); err == nil {
return p, nil
}
}
return "", fmt.Errorf("toolsrv binary not found in PATH or common locations")
}
func waitForSocket(path string, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
conn, err := net.DialTimeout("unix", path, 100*time.Millisecond)
if err == nil {
conn.Close()
return nil
}
time.Sleep(50 * time.Millisecond)
}
return fmt.Errorf("timeout waiting for socket %s", path)
}