An open-source, faster Devin alternative
TypeScript
feat(logship): phase 1 — in-VM forwarder + exec tee
Igor Zalutski9d0804b90d3b
diff --git a/.agents/design/sandbox-session-logs.md b/.agents/design/sandbox-session-logs.mdindex c0b0d52a..66757441 100644--- a/.agents/design/sandbox-session-logs.md+++ b/.agents/design/sandbox-session-logs.md@@ -118,7 +118,7 @@ Five components, three new:### 1. In-guest log forwarder (in `osb-agent`)A new goroutine pool inside the existing `osb-agent` (PID 1 of every-sandbox VM). Lives in `cmd/agent/internal/logship/` (new package).+sandbox VM). Lives in `internal/logship/` (new package).**Why in-process, not a separate binary:** half the data we want toship — exec stdout/stderr — is already produced inside the agent@@ -455,7 +455,7 @@ Phased so each phase is independently shippable and revertible.to the deploy env templates.**Phase 1 — osb-agent forwarder behind a flag.**-1. Implement `cmd/agent/internal/logship/` with `/var/log` tail and+1. Implement `internal/logship/` with `/var/log` tail andone `io.Writer` interface that wraps stdout/stderr.2. Implement the in-`Exec` / `ExecStream` / `ExecSessionAttach`tees as a `io.MultiWriter` chain.diff --git a/.agents/work/sandbox-session-logs-impl.md b/.agents/work/sandbox-session-logs-impl.mdindex 3db27e28..36456722 100644--- a/.agents/work/sandbox-session-logs-impl.md+++ b/.agents/work/sandbox-session-logs-impl.md@@ -47,12 +47,13 @@ proto/agent/└── agent.proto (one new RPC: ConfigureLogship)cmd/agent/ (the in-guest agent)-├── main.go (wire shipper + tailer at startup)-└── internal/logship/ (new package, all forwarder code)- ├── shipper.go (Axiom HTTP client + batcher + drop-oldest)- ├── varlog.go (fsnotify tail of /var/log/**)- ├── tee.go (io.Writer adapter for exec output)- └── shipper_test.go (unit tests)+└── main.go (wire shipper + tailer at startup)++internal/logship/ (new package, all forwarder code)+├── shipper.go (Axiom HTTP client + batcher + drop-oldest)+├── varlog.go (fsnotify tail of /var/log/**)+├── tee.go (io.Writer adapter for exec output)+└── shipper_test.go (unit tests)internal/agent/ (in-VM agent server)├── server.go (add logshipCfg + shipper handle)@@ -284,7 +285,7 @@ Axiom under the schema in the design doc.### 1.1 Package layout-`cmd/agent/internal/logship/`:+`internal/logship/`:- **`shipper.go`** — owns the Axiom HTTP client, the in-memoryring buffer (drop-oldest), and the batch flusher.diff --git a/cmd/agent/main.go b/cmd/agent/main.goindex 6365d1c5..1467aa88 100644--- a/cmd/agent/main.go+++ b/cmd/agent/main.go@@ -6,12 +6,14 @@package mainimport (+ "context""log""os""os/exec""os/signal""syscall"+ "github.com/opensandbox/opensandbox/internal/logship""github.com/opensandbox/opensandbox/internal/agent")@@ -34,6 +36,20 @@ func main() {}srv := agent.NewServer(Version)++ // Sandbox session log shipping. The shipper boots dormant — events+ // queue in its bounded ring but don't POST anywhere until the+ // worker delivers ConfigureLogship after VM boot. The /var/log+ // tailer starts immediately so we don't miss the boot window.+ // If the worker never calls ConfigureLogship (kill-switch), the+ // ring keeps dropping oldest indefinitely; cost is negligible.+ shipperCtx, shipperCancel := context.WithCancel(context.Background())+ defer shipperCancel()+ shipper := logship.New()+ go shipper.Run(shipperCtx)+ go logship.NewVarLogTailer(shipper, "/var/log").Run(shipperCtx)+ srv.Shipper = shipper+// Only set ListenPort for vsock-based backends (Firecracker).// For virtio-serial (QEMU), PTY I/O flows over gRPC PTYAttach instead.if vsl, isVirtioSerial := lis.(*virtioSerialListener); isVirtioSerial {diff --git a/go.mod b/go.modindex 6ae176a7..1a75b5a1 100644--- a/go.mod+++ b/go.mod@@ -61,6 +61,7 @@ require (github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect+ github.com/fsnotify/fsnotify v1.10.1 // indirectgithub.com/golang-jwt/jwt v3.2.2+incompatible // indirectgithub.com/google/go-querystring v1.0.0 // indirectgithub.com/inconshreveable/mousetrap v1.1.0 // indirectdiff --git a/go.sum b/go.sumindex 993a3270..98b238bd 100644--- a/go.sum+++ b/go.sum@@ -90,6 +90,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97cgithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=+github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=+github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=github.com/getsentry/sentry-go v0.46.0 h1:mbdDaarbUdOt9X+dx6kDdntkShLEX3/+KyOsVDTPDj0=github.com/getsentry/sentry-go v0.46.0/go.mod h1:evVbw2qotNUdYG8KxXbAdjOQWWvWIwKxpjdZZIvcIPw=github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=diff --git a/internal/agent/exec.go b/internal/agent/exec.goindex dce4bf36..12cba9eb 100644--- a/internal/agent/exec.go+++ b/internal/agent/exec.go@@ -5,12 +5,15 @@ import ("context""errors""fmt"+ "io""os""os/exec""strings""syscall""time"+ "github.com/google/uuid"+ "github.com/opensandbox/opensandbox/internal/logship"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -102,11 +105,18 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecRespons}var stdout, stderr bytes.Buffer- cmd.Stdout = &stdout- cmd.Stderr = &stderr+ stdoutTee, stderrTee := s.newExecLineWriters(req.Command, req.Args)+ if stdoutTee != nil {+ cmd.Stdout = io.MultiWriter(&stdout, stdoutTee)+ cmd.Stderr = io.MultiWriter(&stderr, stderrTee)+ } else {+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ }// Start + move to sandbox cgroup + wait (instead of Run)if err := cmd.Start(); err != nil {+ closeExecLineWriters(stdoutTee, stderrTee, -1)return nil, fmt.Errorf("exec start: %w", err)}pid := cmd.Process.Pid@@ -134,6 +144,7 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponskillCgroup()<-waitDone // wait for cmd.Wait to return after killsUnregisterReap(pid)+ closeExecLineWriters(stdoutTee, stderrTee, -1)return &pb.ExecResponse{ExitCode: -1,Stdout: stdout.String(),@@ -155,12 +166,14 @@ func (s *Server) Exec(ctx context.Context, req *pb.ExecRequest) (*pb.ExecResponsexitCode = ws.ExitStatus()default:UnregisterReap(pid)+ closeExecLineWriters(stdoutTee, stderrTee, -1)return nil, fmt.Errorf("exec failed: %w", err)}} else {UnregisterReap(pid)}+ closeExecLineWriters(stdoutTee, stderrTee, exitCode)return &pb.ExecResponse{ExitCode: int32(exitCode),Stdout: stdout.String(),@@ -216,7 +229,16 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrereturn fmt.Errorf("stderr pipe: %w", err)}+ stdoutTee, stderrTee := s.newExecLineWriters(req.Command, req.Args)+ var stdoutR io.Reader = stdoutPipe+ var stderrR io.Reader = stderrPipe+ if stdoutTee != nil {+ stdoutR = io.TeeReader(stdoutPipe, stdoutTee)+ stderrR = io.TeeReader(stderrPipe, stderrTee)+ }+if err := cmd.Start(); err != nil {+ closeExecLineWriters(stdoutTee, stderrTee, -1)return fmt.Errorf("start: %w", err)}moveToCgroup(cmd.Process.Pid)@@ -227,7 +249,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrego func() {buf := make([]byte, 4096)for {- n, err := stdoutPipe.Read(buf)+ n, err := stdoutR.Read(buf)if n > 0 {if sendErr := stream.Send(&pb.ExecOutputChunk{Stream: pb.ExecOutputChunk_STDOUT,@@ -247,7 +269,7 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStrego func() {buf := make([]byte, 4096)for {- n, err := stderrPipe.Read(buf)+ n, err := stderrR.Read(buf)if n > 0 {if sendErr := stream.Send(&pb.ExecOutputChunk{Stream: pb.ExecOutputChunk_STDERR,@@ -269,11 +291,46 @@ func (s *Server) ExecStream(req *pb.ExecRequest, stream pb.SandboxAgent_ExecStre<-errCh// Wait for command to finish- _ = cmd.Wait()+ waitErr := cmd.Wait()+ exitCode := 0+ if waitErr != nil {+ if isExitError(waitErr) {+ exitCode = waitErr.(*exec.ExitError).ExitCode()+ } else {+ exitCode = -1+ }+ }+ closeExecLineWriters(stdoutTee, stderrTee, exitCode)return nil}+// newExecLineWriters returns matching stdout/stderr LineWriters that+// ship into the agent's logship Shipper, tagged with a fresh exec_id+// and the command + argv. Returns (nil, nil) if logship isn't wired+// into this agent (callers must tolerate nil and skip teeing).+func (s *Server) newExecLineWriters(command string, args []string) (*logship.LineWriter, *logship.LineWriter) {+ if s.Shipper == nil {+ return nil, nil+ }+ execID := uuid.NewString()+ stdoutW := logship.NewLineWriter(s.Shipper, logship.SourceExecStdout, execID, command, args)+ stderrW := logship.NewLineWriter(s.Shipper, logship.SourceExecStderr, execID, command, args)+ return stdoutW, stderrW+}++// closeExecLineWriters flushes any partial trailing line and emits one+// synthetic EOF event per stream carrying the exit code. Safe to call+// with nil writers (when logship isn't wired).+func closeExecLineWriters(stdout, stderr *logship.LineWriter, exitCode int) {+ if stdout != nil {+ stdout.Close(exitCode)+ }+ if stderr != nil {+ stderr.Close(exitCode)+ }+}+// mapToEnv converts a map to KEY=VALUE slice.func mapToEnv(m map[string]string) []string {env := make([]string, 0, len(m))diff --git a/internal/agent/logship.go b/internal/agent/logship.goindex a56fbd7d..681d907c 100644--- a/internal/agent/logship.go+++ b/internal/agent/logship.go@@ -4,6 +4,7 @@ import ("context""log"+ "github.com/opensandbox/opensandbox/internal/logship"pb "github.com/opensandbox/opensandbox/proto/agent")@@ -39,6 +40,14 @@ func (s *Server) ConfigureLogship(ctx context.Context, req *pb.ConfigureLogshipRlog.Printf("agent: ConfigureLogship received empty ingest_token (kill-switch); shipping disabled")} else {log.Printf("agent: ConfigureLogship received (sandbox_id=%s, dataset=%s)", cfg.SandboxID, cfg.Dataset)+ if s.Shipper != nil {+ s.Shipper.Activate(logship.Config{+ IngestToken: cfg.IngestToken,+ Dataset: cfg.Dataset,+ SandboxID: cfg.SandboxID,+ OrgID: cfg.OrgID,+ })+ }}return &pb.ConfigureLogshipResponse{}, nil}diff --git a/internal/agent/server.go b/internal/agent/server.goindex 99548b46..ff6ae641 100644--- a/internal/agent/server.go+++ b/internal/agent/server.go@@ -14,6 +14,7 @@ import ("syscall""time"+ "github.com/opensandbox/opensandbox/internal/logship"pb "github.com/opensandbox/opensandbox/proto/agent""google.golang.org/grpc")@@ -62,6 +63,12 @@ type Server struct {logshipMu sync.RWMutexlogshipCfg LogshipConfig+ // Shipper is the in-VM forwarder that ships /var/log + exec output+ // to Axiom. Set by cmd/agent/main.go before Serve. Nil = log+ // shipping not wired (the forwarder package isn't built into this+ // agent binary). The exec handlers tolerate nil and skip teeing.+ Shipper *logship.Shipper+// gRPC server reference for hibernate GracefulStopmu sync.MutexgrpcServer *grpc.Serverdiff --git a/internal/logship/shipper.go b/internal/logship/shipper.gonew file mode 100644index 00000000..6648222f--- /dev/null+++ b/internal/logship/shipper.go@@ -0,0 +1,312 @@+// Package logship is the in-VM forwarder that ships sandbox session logs+// (lines from /var/log/* and stdout/stderr from platform-exec'd commands)+// to Axiom.+//+// Lifecycle:+//+// 1. cmd/agent/main starts a Shipper at boot via New(). The shipper is+// DORMANT: events accepted via Send() queue in a bounded ring but+// do not POST anywhere yet. The /var/log tailer starts immediately+// so we don't miss the boot window.+// 2. Worker calls the agent's ConfigureLogship RPC after VM boot. The+// RPC handler calls Shipper.Activate(cfg), passing the ingest token,+// dataset, and per-sandbox identifiers.+// 3. Once activated, queued events are flushed (batches of up to 100 or+// every 200ms) to https://api.axiom.co/v1/datasets/<dataset>/ingest+// with the activation cfg's identifiers stamped on each event at+// flush time.+// 4. If Activate is never called (kill-switch: worker had no ingest+// token), the ring keeps dropping oldest indefinitely. Memory cost+// is bounded by the ring; CPU cost is one no-op tick per 200ms.+//+// This package only depends on the standard library + fsnotify; no other+// internal packages, so tests are self-contained.+package logship++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "log"+ "net/http"+ "sync"+ "sync/atomic"+ "time"+)++// Source identifies where an event came from.+type Source string++const (+ SourceVarLog Source = "var_log"+ SourceExecStdout Source = "exec_stdout"+ SourceExecStderr Source = "exec_stderr"+ SourceAgent Source = "agent"+)++// Event is one log line as serialised to Axiom. The JSON shape matches+// Axiom's ingest API (top-level _time field; arbitrary other fields are+// stored verbatim).+type Event struct {+ Time time.Time `json:"_time"`+ Source Source `json:"source"`+ Line string `json:"line"`++ // Stamped at flush time from the active config; empty until+ // activated. Sent to Axiom anyway so events captured pre-Activate+ // are still tagged with whatever's set when they finally flush.+ SandboxID string `json:"sandbox_id,omitempty"`+ OrgID string `json:"org_id,omitempty"`++ // Set when source == "var_log".+ Path string `json:"path,omitempty"`++ // Set when source == "exec_*".+ ExecID string `json:"exec_id,omitempty"`+ Command string `json:"command,omitempty"`+ Argv []string `json:"argv,omitempty"`+ ExitCode *int `json:"exit_code,omitempty"`+}++// Config is the activation payload delivered via the worker's+// ConfigureLogship RPC.+type Config struct {+ IngestToken string+ Dataset string+ SandboxID string+ OrgID string+}++// Shipper buffers events in a bounded ring and flushes batches to Axiom+// once Activate has been called.+type Shipper struct {+ bufSize int+ batchSize int+ flushEvery time.Duration+ httpTimeout time.Duration+ httpClient *http.Client++ in chan Event // bounded; drop-oldest on full++ mu sync.RWMutex+ cfg Config // zero until Activate+ activated bool++ droppedTotal atomic.Uint64+ closed atomic.Bool+}++// New returns a dormant Shipper. Run it via Run(ctx) (typically in a+// goroutine) to start the flush loop.+func New() *Shipper {+ return &Shipper{+ bufSize: 10_000,+ batchSize: 100,+ flushEvery: 200 * time.Millisecond,+ httpTimeout: 10 * time.Second,+ httpClient: &http.Client{Timeout: 10 * time.Second},+ in: make(chan Event, 10_000),+ }+}++// Activate enables flushing with the given configuration. Calling+// Activate with an empty IngestToken is a no-op (kill-switch).+// Subsequent calls (e.g. token rotation) replace the config atomically.+func (s *Shipper) Activate(cfg Config) {+ if cfg.IngestToken == "" {+ return+ }+ s.mu.Lock()+ s.cfg = cfg+ s.activated = true+ s.mu.Unlock()+}++// Send enqueues an event. Non-blocking; if the buffer is full, the+// oldest queued event is dropped to make room.+func (s *Shipper) Send(ev Event) {+ if s.closed.Load() {+ return+ }+ if ev.Time.IsZero() {+ ev.Time = time.Now().UTC()+ }+ select {+ case s.in <- ev:+ return+ default:+ // Full — drop oldest to make room.+ select {+ case <-s.in:+ s.droppedTotal.Add(1)+ default:+ }+ select {+ case s.in <- ev:+ default:+ s.droppedTotal.Add(1)+ }+ }+}++// Run drives the flush loop. Returns when ctx is cancelled. The loop is+// safe to call before Activate; pre-Activate it just keeps draining the+// ring into the local batch but does not POST anywhere — flushing is+// gated on having a valid token.+func (s *Shipper) Run(ctx context.Context) {+ defer s.closed.Store(true)++ // Worker pool for HTTP POSTs. Decoupled from the batch loop so a+ // slow Axiom POST never blocks ingestion.+ postCh := make(chan []Event, 8)+ var workersDone sync.WaitGroup+ workersDone.Add(2)+ for i := 0; i < 2; i++ {+ go func() {+ defer workersDone.Done()+ for batch := range postCh {+ s.post(ctx, batch)+ }+ }()+ }++ var batch []Event+ flush := func() {+ if len(batch) == 0 {+ return+ }+ s.mu.RLock()+ cfg := s.cfg+ activated := s.activated+ s.mu.RUnlock()+ if !activated {+ // Hold the batch; it'll get re-flushed once Activate fires.+ // To avoid unbounded growth, cap the held batch at 10× normal.+ if len(batch) > s.batchSize*10 {+ batch = batch[len(batch)-s.batchSize*10:]+ }+ return+ }+ // Stamp identifiers on each event at flush time.+ for i := range batch {+ batch[i].SandboxID = cfg.SandboxID+ batch[i].OrgID = cfg.OrgID+ }+ select {+ case postCh <- batch:+ case <-ctx.Done():+ }+ batch = nil+ }++ tick := time.NewTicker(s.flushEvery)+ defer tick.Stop()++ dropTicker := time.NewTicker(30 * time.Second)+ defer dropTicker.Stop()+ var lastDropped uint64++ for {+ select {+ case <-ctx.Done():+ flush()+ close(postCh)+ workersDone.Wait()+ return+ case ev := <-s.in:+ batch = append(batch, ev)+ if len(batch) >= s.batchSize {+ flush()+ }+ case <-tick.C:+ flush()+ case <-dropTicker.C:+ n := s.droppedTotal.Load()+ if n > lastDropped {+ dropped := n - lastDropped+ lastDropped = n+ batch = append(batch, Event{+ Time: time.Now().UTC(),+ Source: SourceAgent,+ Line: fmt.Sprintf("logship: dropped %d events in last 30s (total %d)", dropped, n),+ })+ }+ }+ }+}++func (s *Shipper) post(ctx context.Context, batch []Event) {+ s.mu.RLock()+ cfg := s.cfg+ s.mu.RUnlock()+ if cfg.IngestToken == "" {+ return // shouldn't happen — flush() gates on activated — defensive+ }++ body, err := json.Marshal(batch)+ if err != nil {+ log.Printf("logship: marshal: %v", err)+ return+ }++ url := fmt.Sprintf("https://api.axiom.co/v1/datasets/%s/ingest", cfg.Dataset)++ // Backoff: 250ms → 500ms → 1s → 2s → 5s, total ~30s before drop.+ delays := []time.Duration{0, 250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second, 2 * time.Second, 5 * time.Second, 5 * time.Second, 5 * time.Second, 5 * time.Second, 5 * time.Second}+ for i, d := range delays {+ if d > 0 {+ select {+ case <-time.After(d):+ case <-ctx.Done():+ return+ }+ }++ req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))+ if err != nil {+ log.Printf("logship: NewRequest: %v", err)+ return+ }+ req.Header.Set("Authorization", "Bearer "+cfg.IngestToken)+ req.Header.Set("Content-Type", "application/json")++ resp, err := s.httpClient.Do(req)+ if err != nil {+ if i == len(delays)-1 {+ log.Printf("logship: POST after %d retries: %v (dropping %d events)", i, err, len(batch))+ s.droppedTotal.Add(uint64(len(batch)))+ return+ }+ continue+ }+ resp.Body.Close()+ if resp.StatusCode < 400 {+ return+ }+ if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {+ // Token's bad — retry won't help.+ log.Printf("logship: POST %d (auth) — dropping %d events", resp.StatusCode, len(batch))+ s.droppedTotal.Add(uint64(len(batch)))+ return+ }+ if i == len(delays)-1 {+ log.Printf("logship: POST %d after %d retries (dropping %d events)", resp.StatusCode, i, len(batch))+ s.droppedTotal.Add(uint64(len(batch)))+ return+ }+ }+}++// Stats returns counters for observability.+type Stats struct {+ Dropped uint64+ Queued int+}++func (s *Shipper) Stats() Stats {+ return Stats{+ Dropped: s.droppedTotal.Load(),+ Queued: len(s.in),+ }+}diff --git a/internal/logship/shipper_test.go b/internal/logship/shipper_test.gonew file mode 100644index 00000000..8f4e184b--- /dev/null+++ b/internal/logship/shipper_test.go@@ -0,0 +1,187 @@+package logship++import (+ "context"+ "strings"+ "sync"+ "testing"+ "time"+)++// TestLineWriter_BasicLines: simple newline-separated lines emit+// one Event each with the right source/exec metadata.+func TestLineWriter_BasicLines(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "exec-1", "echo", []string{"hi"})++ w.Write([]byte("hello\nworld\n"))+ w.Close(0)++ evs := got.drain(t, 3)++ if evs[0].Line != "hello" || evs[0].Source != SourceExecStdout || evs[0].ExecID != "exec-1" {+ t.Errorf("event[0] = %+v", evs[0])+ }+ if evs[1].Line != "world" {+ t.Errorf("event[1] line = %q, want %q", evs[1].Line, "world")+ }+ // Final EOF event.+ if evs[2].ExitCode == nil || *evs[2].ExitCode != 0 || evs[2].Line != "" {+ t.Errorf("event[2] = %+v, want EOF with exit=0", evs[2])+ }+}++// TestLineWriter_PartialLines: bytes split across multiple Writes+// must be re-assembled on the next newline. No premature emission.+func TestLineWriter_PartialLines(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "e", "x", nil)++ w.Write([]byte("hel"))+ w.Write([]byte("lo "))+ w.Write([]byte("world\nrest"))+ w.Close(0)++ evs := got.drain(t, 3)+ if evs[0].Line != "hello world" {+ t.Errorf("expected re-assembled 'hello world', got %q", evs[0].Line)+ }+ // 'rest' is the tail flushed at Close.+ if evs[1].Line != "rest" {+ t.Errorf("expected tail 'rest', got %q", evs[1].Line)+ }+ if evs[2].ExitCode == nil || *evs[2].ExitCode != 0 {+ t.Errorf("expected final EOF, got %+v", evs[2])+ }+}++// TestLineWriter_NoPartialFlushIfTrailingNewline: when Close is+// called and the buffer is already empty (input ended on \n), the+// only synthesised event is the EOF marker — no spurious empty line.+func TestLineWriter_NoPartialFlushIfTrailingNewline(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "e", "x", nil)++ w.Write([]byte("a\nb\n"))+ w.Close(7)++ evs := got.drain(t, 3)+ if evs[0].Line != "a" || evs[1].Line != "b" {+ t.Errorf("unexpected lines: %v / %v", evs[0].Line, evs[1].Line)+ }+ if evs[2].Line != "" || evs[2].ExitCode == nil || *evs[2].ExitCode != 7 {+ t.Errorf("expected EOF with exit=7, got %+v", evs[2])+ }+}++// TestLineWriter_NilShipper: a nil shipper must be tolerated (we use+// shipper=nil to disable shipping) — Write/Close must be safe no-ops.+func TestLineWriter_NilShipper(t *testing.T) {+ w := NewLineWriter(nil, SourceExecStdout, "e", "x", nil)+ if _, err := w.Write([]byte("hello\n")); err != nil {+ t.Fatalf("Write returned error with nil shipper: %v", err)+ }+ w.Close(0)+}++// TestLineWriter_LongLines: a single huge line spread across many+// Writes is re-assembled correctly on the trailing newline.+func TestLineWriter_LongLines(t *testing.T) {+ got := captureShipper(t)+ w := NewLineWriter(got.s, SourceExecStdout, "e", "x", nil)++ chunk := strings.Repeat("a", 1024)+ for i := 0; i < 100; i++ {+ w.Write([]byte(chunk))+ }+ w.Write([]byte("\n"))+ w.Close(0)++ evs := got.drain(t, 2)+ if len(evs[0].Line) != 100*1024 {+ t.Errorf("expected re-assembled 100KB line, got %d bytes", len(evs[0].Line))+ }+}++// TestShipper_DropOldest: under flood, the bounded channel drops+// oldest events and reports the dropped count.+func TestShipper_DropOldest(t *testing.T) {+ s := New()+ // Force a tiny buffer to make the test fast.+ s.in = make(chan Event, 4)++ for i := 0; i < 100; i++ {+ s.Send(Event{Line: "x"})+ }+ st := s.Stats()+ if st.Dropped < 90 {+ t.Errorf("expected ~96 drops, got %d", st.Dropped)+ }+ if st.Queued != 4 {+ t.Errorf("expected buffer at capacity 4, got %d", st.Queued)+ }+}++// TestShipper_PreActivateHolds: Send before Activate queues into the+// ring; the flush loop holds the batch (no POST) and discards+// gracefully under cancellation.+func TestShipper_PreActivateHolds(t *testing.T) {+ s := New()+ ctx, cancel := context.WithCancel(context.Background())+ go s.Run(ctx)++ for i := 0; i < 10; i++ {+ s.Send(Event{Line: "pre"})+ }+ // Let the flush ticker fire a couple of times.+ time.Sleep(500 * time.Millisecond)++ st := s.Stats()+ // No drops yet — buffer is well below capacity.+ if st.Dropped != 0 {+ t.Errorf("unexpected drops pre-activate: %d", st.Dropped)+ }+ cancel()+}++// captureShipper steals events directly off the Shipper's channel and+// stashes them in a slice. No Run/HTTP needed — perfect for unit+// testing the producers (LineWriter, etc.) in isolation.+type fakeShipper struct {+ s *Shipper+ mu sync.Mutex+ got []Event+}++func captureShipper(t *testing.T) *fakeShipper {+ t.Helper()+ fs := &fakeShipper{s: New()}+ go func() {+ for ev := range fs.s.in {+ fs.mu.Lock()+ fs.got = append(fs.got, ev)+ fs.mu.Unlock()+ }+ }()+ return fs+}++func (fs *fakeShipper) drain(t *testing.T, want int) []Event {+ t.Helper()+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ fs.mu.Lock()+ if len(fs.got) >= want {+ out := make([]Event, want)+ copy(out, fs.got[:want])+ fs.mu.Unlock()+ return out+ }+ fs.mu.Unlock()+ time.Sleep(5 * time.Millisecond)+ }+ fs.mu.Lock()+ defer fs.mu.Unlock()+ t.Fatalf("only got %d events, wanted %d", len(fs.got), want)+ return nil+}diff --git a/internal/logship/tee.go b/internal/logship/tee.gonew file mode 100644index 00000000..4350d7d2--- /dev/null+++ b/internal/logship/tee.go@@ -0,0 +1,121 @@+package logship++import (+ "bytes"+ "sync"+)++// LineWriter adapts a stream of bytes (e.g. exec stdout/stderr) into+// line-segmented Events fed to a Shipper. Implements io.Writer so it+// drops cleanly into io.MultiWriter alongside the existing per-exec+// pipes.+//+// Lines are split on '\n'. A trailing partial line (no terminating+// newline) is held in an internal buffer and emitted on Close, along+// with one synthetic "EOF" event carrying the exit code so the UI can+// render "command X exited 0/1".+type LineWriter struct {+ shipper *Shipper+ source Source+ execID string+ command string+ argv []string++ mu sync.Mutex+ buf bytes.Buffer+ final bool // Close() called+}++// NewLineWriter returns a LineWriter that ships to the given Shipper+// under the given Source. execID is a unique-per-exec identifier (the+// caller generates it; ULID/UUID both fine). command + argv are+// stamped on every line so the UI can drill into "all output of this+// exec" without joining tables.+func NewLineWriter(shipper *Shipper, source Source, execID, command string, argv []string) *LineWriter {+ return &LineWriter{+ shipper: shipper,+ source: source,+ execID: execID,+ command: command,+ argv: argv,+ }+}++// Write splits incoming bytes on '\n' and ships each completed line as+// an Event. A trailing partial is held in the buffer.+func (w *LineWriter) Write(p []byte) (int, error) {+ if w.shipper == nil {+ return len(p), nil+ }+ w.mu.Lock()+ defer w.mu.Unlock()+ if w.final {+ // Close already called — don't ship more.+ return len(p), nil+ }++ w.buf.Write(p)++ for {+ data := w.buf.Bytes()+ idx := bytes.IndexByte(data, '\n')+ if idx < 0 {+ break+ }+ line := string(data[:idx])+ // Drop the consumed bytes (including the newline).+ w.buf.Next(idx + 1)++ w.shipper.Send(Event{+ Source: w.source,+ Line: line,+ ExecID: w.execID,+ Command: w.command,+ Argv: w.argv,+ })+ }+ return len(p), nil+}++// Close flushes any partial-line residue and emits one final synthetic+// event carrying the exit code. After Close, further Writes are+// silently dropped (defensive — a well-behaved caller should not Write+// after Close, but stdout/stderr pipes can race with Wait).+//+// Pass exitCode = -1 if the process did not exit cleanly (signal /+// timeout / killed); the EOF event records it as -1 unchanged so the+// UI can distinguish "exited" from "killed".+func (w *LineWriter) Close(exitCode int) {+ if w.shipper == nil {+ return+ }+ w.mu.Lock()+ defer w.mu.Unlock()+ if w.final {+ return+ }+ w.final = true++ // Flush any trailing partial line.+ if w.buf.Len() > 0 {+ w.shipper.Send(Event{+ Source: w.source,+ Line: w.buf.String(),+ ExecID: w.execID,+ Command: w.command,+ Argv: w.argv,+ })+ w.buf.Reset()+ }++ // Final synthetic event marking the exec's end.+ ec := exitCode+ w.shipper.Send(Event{+ Source: w.source,+ Line: "",+ ExecID: w.execID,+ Command: w.command,+ Argv: w.argv,+ ExitCode: &ec,+ })+}diff --git a/internal/logship/varlog.go b/internal/logship/varlog.gonew file mode 100644index 00000000..d9414e07--- /dev/null+++ b/internal/logship/varlog.go@@ -0,0 +1,205 @@+package logship++import (+ "bufio"+ "context"+ "io"+ "log"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "sync"++ "github.com/fsnotify/fsnotify"+)++// skipFilenamePattern matches files inside /var/log/* that we never+// tail: rotated/compressed archives and binary system logs.+var skipFilenamePattern = regexp.MustCompile(`(^|\.)(wtmp|btmp|lastlog|gz|bz2|xz|zst)$|\.\d+(\.\w+)?$`)++// VarLogTailer watches a root directory (typically /var/log) recursively+// and ships every line appended to any regular file there. New files+// (created during the sandbox's lifetime) are picked up via inotify+// IN_CREATE.+//+// Files are tailed from their *current* end, not from the beginning —+// we don't backfill historical content (it's noisy, often binary, and+// would dump megabytes of irrelevant context every sandbox boot).+type VarLogTailer struct {+ root string+ shipper *Shipper++ mu sync.Mutex+ tailing map[string]*tailedFile // path → state+}++type tailedFile struct {+ path string+ offset int64+}++// NewVarLogTailer creates a tailer rooted at the given directory.+func NewVarLogTailer(shipper *Shipper, root string) *VarLogTailer {+ return &VarLogTailer{+ root: root,+ shipper: shipper,+ tailing: make(map[string]*tailedFile),+ }+}++// Run starts watching. Returns when ctx is cancelled or the watcher+// fails to initialise. Errors from individual file reads are logged+// but do not stop the loop.+func (t *VarLogTailer) Run(ctx context.Context) {+ w, err := fsnotify.NewWatcher()+ if err != nil {+ log.Printf("logship/varlog: NewWatcher: %v (logs from %s will not be shipped)", err, t.root)+ return+ }+ defer w.Close()++ // Walk root once; register every existing regular file at offset =+ // EOF, register every dir for IN_CREATE notifications.+ if err := filepath.Walk(t.root, func(path string, info os.FileInfo, err error) error {+ if err != nil || info == nil {+ return nil+ }+ if info.IsDir() {+ _ = w.Add(path)+ return nil+ }+ if t.skipFile(path, info) {+ return nil+ }+ t.startTail(path, info.Size())+ return nil+ }); err != nil {+ log.Printf("logship/varlog: walk %s: %v", t.root, err)+ }++ for {+ select {+ case <-ctx.Done():+ return+ case ev, ok := <-w.Events:+ if !ok {+ return+ }+ t.handleEvent(w, ev)+ case err, ok := <-w.Errors:+ if !ok {+ return+ }+ log.Printf("logship/varlog: watcher error: %v", err)+ }+ }+}++func (t *VarLogTailer) handleEvent(w *fsnotify.Watcher, ev fsnotify.Event) {+ switch {+ case ev.Op&fsnotify.Create != 0:+ info, err := os.Stat(ev.Name)+ if err != nil {+ return+ }+ if info.IsDir() {+ _ = w.Add(ev.Name)+ return+ }+ if t.skipFile(ev.Name, info) {+ return+ }+ // New file: tail from byte 0 (it's brand new).+ t.startTail(ev.Name, 0)+ t.readAvailable(ev.Name)+ case ev.Op&fsnotify.Write != 0:+ t.readAvailable(ev.Name)+ case ev.Op&fsnotify.Remove != 0, ev.Op&fsnotify.Rename != 0:+ t.mu.Lock()+ delete(t.tailing, ev.Name)+ t.mu.Unlock()+ }+}++func (t *VarLogTailer) startTail(path string, offset int64) {+ t.mu.Lock()+ defer t.mu.Unlock()+ if _, exists := t.tailing[path]; exists {+ return+ }+ t.tailing[path] = &tailedFile{path: path, offset: offset}+}++func (t *VarLogTailer) readAvailable(path string) {+ t.mu.Lock()+ tf, ok := t.tailing[path]+ t.mu.Unlock()+ if !ok {+ return+ }++ f, err := os.Open(path)+ if err != nil {+ return+ }+ defer f.Close()++ info, err := f.Stat()+ if err != nil {+ return+ }++ // Truncation: file shrank. Reset to start.+ if info.Size() < tf.offset {+ tf.offset = 0+ }++ if _, err := f.Seek(tf.offset, io.SeekStart); err != nil {+ return+ }++ br := bufio.NewReader(f)+ var newOffset = tf.offset+ for {+ line, err := br.ReadString('\n')+ newOffset += int64(len(line))+ // Trim the trailing newline before shipping.+ stripped := strings.TrimRight(line, "\r\n")+ if stripped != "" {+ t.shipper.Send(Event{+ Source: SourceVarLog,+ Line: stripped,+ Path: path,+ })+ }+ if err != nil {+ break+ }+ }+ tf.offset = newOffset+}++func (t *VarLogTailer) skipFile(path string, info os.FileInfo) bool {+ if !info.Mode().IsRegular() {+ return true+ }+ name := filepath.Base(path)+ if skipFilenamePattern.MatchString(name) {+ return true+ }+ // Skip files that look binary (first 256 bytes contain a NUL).+ f, err := os.Open(path)+ if err != nil {+ return true+ }+ defer f.Close()+ var sniff [256]byte+ n, _ := f.Read(sniff[:])+ for i := 0; i < n; i++ {+ if sniff[i] == 0 {+ return true+ }+ }+ return false+}