Separates what a VM IS (durable intent + identity + deterministic
derived paths — `VMRuntime`) from what is CURRENTLY TRUE about it
(firecracker PID, tap device, loop devices, dm-snapshot target — new
`VMHandles`). The durable state lives in the SQLite `vms` row; the
transient state lives in an in-memory cache on the daemon plus a
per-VM `handles.json` scratch file inside VMDir, rebuilt at startup
from OS inspection. Nothing kernel-level rides the SQLite schema
anymore.
Why:
Persisting ephemeral process handles to SQLite forced reconcile to
treat "running with a stale PID" as a first-class case and mix it
with real state transitions. The schema described what we last
observed, not what the VM is. Every time the observation model
shifted (tap pool, DM naming, pgrep fallback) the reconcile logic
grew a new branch. Splitting lets each layer own what it's good at:
durable records describe intent, in-memory cache + scratch file
describe momentary reality.
Shape:
- `model.VMHandles` = PID, TapDevice, BaseLoop, COWLoop, DMName,
DMDev. Never in SQLite.
- `VMRuntime` keeps: State, GuestIP, APISockPath, VSockPath,
VSockCID, LogPath, MetricsPath, DNSName, VMDir, SystemOverlay,
WorkDiskPath, LastError. All durable or deterministic.
- `handleCache` on `*Daemon` — mutex-guarded map + scratch-file
plumbing (`writeHandlesFile` / `readHandlesFile` /
`rediscoverHandles`). See `internal/daemon/vm_handles.go`.
- `d.vmAlive(vm)` replaces the 20+ inline
`vm.State==Running && ProcessRunning(vm.Runtime.PID, apiSock)`
spreads. Single source of truth for liveness.
- Startup reconcile: per running VM, load the scratch file, pgrep
the api sock, either keep (cache seeded from scratch) or demote
to stopped (scratch handles passed to cleanupRuntime first so DM
/ loops / tap actually get torn down).
Verification:
- `go test ./...` green.
- Live: `banger vm run --name handles-test -- cat /etc/hostname`
starts; `handles.json` appears in VMDir with the expected PID,
tap, loops, DM.
- `kill -9 $(pgrep bangerd)` while the VM is running, re-invoke the
CLI, daemon auto-starts, reconcile recognises the VM as alive,
`banger vm ssh` still connects, `banger vm delete` cleans up.
Tests added:
- vm_handles_test.go: scratch-file roundtrip, missing/corrupt file
behaviour, cache concurrency, rediscoverHandles prefers pgrep
over scratch, returns scratch contents even when process is
dead (so cleanup can tear down kernel state).
- vm_test.go: reconcile test rewritten to exercise the new flow
(write scratch → reconcile reads it → verifies process is gone →
issues dmsetup/losetup teardown).
ARCHITECTURE.md updated; `handles` added to Daemon field docs.
120 lines
4 KiB
Go
120 lines
4 KiB
Go
package daemon
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"banger/internal/api"
|
|
sess "banger/internal/daemon/session"
|
|
"banger/internal/guest"
|
|
"banger/internal/model"
|
|
"banger/internal/system"
|
|
)
|
|
|
|
func (d *Daemon) GuestSessionLogs(ctx context.Context, params api.GuestSessionLogsParams) (api.GuestSessionLogsResult, error) {
|
|
vm, err := d.FindVM(ctx, params.VMIDOrName)
|
|
if err != nil {
|
|
return api.GuestSessionLogsResult{}, err
|
|
}
|
|
session, err := d.findGuestSession(ctx, vm.ID, params.SessionIDOrName)
|
|
if err != nil {
|
|
return api.GuestSessionLogsResult{}, err
|
|
}
|
|
streamName := strings.TrimSpace(params.Stream)
|
|
if streamName == "" {
|
|
streamName = "stdout"
|
|
}
|
|
tailLines := params.TailLines
|
|
if tailLines <= 0 {
|
|
tailLines = sess.LogTailLineDefault
|
|
}
|
|
path := session.StdoutLogPath
|
|
if streamName == "stderr" {
|
|
path = session.StderrLogPath
|
|
}
|
|
content, err := d.readGuestSessionLog(ctx, vm, session, streamName, tailLines)
|
|
if err != nil {
|
|
return api.GuestSessionLogsResult{}, err
|
|
}
|
|
return api.GuestSessionLogsResult{Session: session, Stream: streamName, Path: path, Content: content}, nil
|
|
}
|
|
|
|
func (d *Daemon) SendToGuestSession(ctx context.Context, params api.GuestSessionSendParams) (api.GuestSessionSendResult, error) {
|
|
vm, err := d.FindVM(ctx, params.VMIDOrName)
|
|
if err != nil {
|
|
return api.GuestSessionSendResult{}, err
|
|
}
|
|
session, err := d.findGuestSession(ctx, vm.ID, params.SessionIDOrName)
|
|
if err != nil {
|
|
return api.GuestSessionSendResult{}, err
|
|
}
|
|
if session.StdinMode != model.GuestSessionStdinPipe {
|
|
return api.GuestSessionSendResult{}, errors.New("session does not have a stdin pipe")
|
|
}
|
|
if session.Status != model.GuestSessionStatusRunning {
|
|
return api.GuestSessionSendResult{}, fmt.Errorf("session is not running (status=%s)", session.Status)
|
|
}
|
|
if !d.vmAlive(vm) {
|
|
return api.GuestSessionSendResult{}, fmt.Errorf("vm %q is not running", vm.Name)
|
|
}
|
|
if len(params.Payload) == 0 {
|
|
return api.GuestSessionSendResult{Session: session}, nil
|
|
}
|
|
client, err := d.dialGuest(ctx, net.JoinHostPort(vm.Runtime.GuestIP, "22"))
|
|
if err != nil {
|
|
return api.GuestSessionSendResult{}, fmt.Errorf("dial guest: %w", err)
|
|
}
|
|
defer client.Close()
|
|
tmpPath := fmt.Sprintf("/tmp/banger-send-%s.bin", session.ID[:8])
|
|
var uploadLog bytes.Buffer
|
|
if err := client.UploadFile(ctx, tmpPath, 0o600, params.Payload, &uploadLog); err != nil {
|
|
return api.GuestSessionSendResult{}, fmt.Errorf("upload payload: %w", err)
|
|
}
|
|
sendScript := fmt.Sprintf(
|
|
"set -euo pipefail\ncat %s >> %s\nrm -f %s\n",
|
|
sess.ShellQuote(tmpPath),
|
|
sess.ShellQuote(sess.StdinPipePath(session.ID)),
|
|
sess.ShellQuote(tmpPath),
|
|
)
|
|
var sendLog bytes.Buffer
|
|
if err := client.RunScript(ctx, sendScript, &sendLog); err != nil {
|
|
return api.GuestSessionSendResult{}, fmt.Errorf("send to session: %w: %s", err, strings.TrimSpace(sendLog.String()))
|
|
}
|
|
return api.GuestSessionSendResult{Session: session, BytesWritten: len(params.Payload)}, nil
|
|
}
|
|
|
|
func (d *Daemon) readGuestSessionLog(ctx context.Context, vm model.VMRecord, session model.GuestSession, stream string, tailLines int) (string, error) {
|
|
if d.vmAlive(vm) {
|
|
client, err := guest.Dial(ctx, net.JoinHostPort(vm.Runtime.GuestIP, "22"), d.config.SSHKeyPath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer client.Close()
|
|
path := session.StdoutLogPath
|
|
if stream == "stderr" {
|
|
path = session.StderrLogPath
|
|
}
|
|
var output bytes.Buffer
|
|
script := fmt.Sprintf("set -euo pipefail\nif [ -f %s ]; then tail -n %d %s; fi\n", sess.ShellQuote(path), tailLines, sess.ShellQuote(path))
|
|
if err := client.RunScript(ctx, script, &output); err != nil {
|
|
return "", sess.FormatStepError("read guest session log", err, output.String())
|
|
}
|
|
return output.String(), nil
|
|
}
|
|
runner := d.runner
|
|
if runner == nil {
|
|
runner = system.NewRunner()
|
|
}
|
|
workMount, cleanup, err := system.MountTempDir(ctx, runner, vm.Runtime.WorkDiskPath, false)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer cleanup()
|
|
logPath := filepath.Join(workMount, sess.RelativeStateDir(session.ID), stream+".log")
|
|
return sess.TailFileContent(logPath, tailLines)
|
|
}
|