feat(agents): self-updating agent image variant
ci / test (pull_request) Successful in 9m12s
ci / lint (pull_request) Successful in 12m17s
ci / build (pull_request) Successful in 16m25s
ci / image (pull_request) Successful in 4m40s

The -autoupdate variant of the checker and status page images adds a
launcher layer. The launcher runs the agent as a child process and keeps
it on the platform's release: GET /agent/v1/update names the API's own
release and the agent image for it, the launcher downloads the binary
for its platform from the registry, accepts it only when the index is
signed with a release key for exactly that version, swaps the agent
gracefully and rolls back when the new release does not become ready or
crashes right after starting. Agents never get ahead of the API, and
installations on unreleased builds are not followed.

CI pushes both variants and signs each index with RELEASE_SIGNING_KEY
(minisign signature in a sha256-<digest>.minisig image next to it). The
image builder moves to internal/agentimage; the API image job takes the
build job's version so the API reports the release its agents are tagged
with. Agents gain a version command.

Closes #129
Closes #128

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-23 18:57:48 +01:00
1 parent 431048e244
commit a35dadd8f6
20 files changed
+1577 -443

No files matched your search

+291
View File
@@ -0,0 +1,291 @@
// Package launcher keeps a self-updating agent on the platform's release.
// It runs the agent as a child process, asks the API which release to run,
// downloads and verifies it, swaps the running agent gracefully and falls
// back to the previous release when the new one does not become ready.
package launcher
import (
"context"
"errors"
"fmt"
"log/slog"
"math/rand/v2"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
// Process is a running agent.
type Process interface {
// Stop asks the agent to shut down and kills it after timeout.
Stop(timeout time.Duration)
// Done is closed when the agent has exited.
Done() <-chan struct{}
// Err is the agent's exit error, once Done is closed.
Err() error
}
// Config wires the launcher to its surroundings.
type Config struct {
// Agent is the binary name: checker or statuspage.
Agent string
// Bundled is the binary shipped in the image.
Bundled string
// Dir keeps downloaded releases and the current choice.
Dir string
// Interval is the time between update checks, ±10%.
Interval time.Duration
// ReadyWait is how long a release has to become ready.
ReadyWait time.Duration
// StopTimeout is how long an agent may take to shut down.
StopTimeout time.Duration
// RetryAfter is how long a release that failed is not tried again.
RetryAfter time.Duration
Log *slog.Logger
// Updates asks the API which release to run.
Updates func(context.Context) (agentapi.Update, error)
// Fetch downloads and verifies the agent binary of a release.
Fetch func(context.Context, agentapi.Update) ([]byte, error)
// Start runs an agent binary.
Start func(path string) (Process, error)
// Ready reports whether the running agent is ready.
Ready func(context.Context) error
// Version reads the release a binary was built as.
Version func(path string) (string, error)
}
// release is an agent binary and its version.
type release struct {
version, path string
}
// Launcher runs one agent.
type Launcher struct {
cfg Config
bundled release
failed map[string]time.Time
}
// New returns a launcher for cfg.
func New(cfg Config) *Launcher {
return &Launcher{cfg: cfg, failed: map[string]time.Time{}}
}
var safeVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
func (l *Launcher) releasePath(version string) string {
return filepath.Join(l.cfg.Dir, "releases", version, l.cfg.Agent)
}
func (l *Launcher) currentFile() string { return filepath.Join(l.cfg.Dir, "current") }
// initial picks the release to start with: the one chosen last time if it
// is still there, otherwise the bundled one.
func (l *Launcher) initial() release {
raw, err := os.ReadFile(l.currentFile())
v := strings.TrimSpace(string(raw))
if err != nil || !safeVersion.MatchString(v) || v == l.bundled.version {
return l.bundled
}
p := l.releasePath(v)
if got, err := l.cfg.Version(p); err != nil || got != v {
return l.bundled
}
return release{v, p}
}
// Run starts the agent and keeps it updated until ctx ends, then stops it.
// It returns when the agent exits on its own.
func (l *Launcher) Run(ctx context.Context) error {
v, err := l.cfg.Version(l.cfg.Bundled)
if err != nil {
return fmt.Errorf("launcher: bundled %s: %w", l.cfg.Agent, err)
}
l.bundled = release{v, l.cfg.Bundled}
cur := l.initial()
proc, err := l.cfg.Start(cur.path)
if err != nil {
return err
}
started := time.Now()
l.cfg.Log.Info("agent started", "release", cur.version, "bundled", cur == l.bundled)
// The first check comes soon, so new installations catch up quickly.
timer := time.NewTimer(min(l.cfg.Interval, 30*time.Second))
defer timer.Stop()
for {
select {
case <-ctx.Done():
proc.Stop(l.cfg.StopTimeout)
return nil
case <-proc.Done():
if cur == l.bundled || time.Since(started) > l.cfg.ReadyWait {
return fmt.Errorf("launcher: %s %s exited: %w", l.cfg.Agent, cur.version, proc.Err())
}
// A downloaded release that crashes right after starting is
// not run again for a while.
l.cfg.Log.Error("agent crashed right after starting; falling back to the bundled release",
"release", cur.version, "error", proc.Err())
l.failed[cur.version] = time.Now()
_ = os.Remove(l.currentFile())
cur = l.bundled
if proc, err = l.cfg.Start(cur.path); err != nil {
return err
}
started = time.Now()
case <-timer.C:
next, np := l.check(ctx, cur, proc)
if np != proc {
started = time.Now()
}
cur, proc = next, np
if proc == nil {
return errors.New("launcher: no agent could be started")
}
timer.Reset(time.Duration(float64(l.cfg.Interval) * (0.9 + 0.2*rand.Float64())))
}
}
}
// check updates the agent if the platform names another release. It
// returns the release and process running afterwards.
func (l *Launcher) check(ctx context.Context, cur release, proc Process) (release, Process) {
u, err := l.cfg.Updates(ctx)
switch {
case err != nil:
l.cfg.Log.Warn("asking for updates failed", "error", err)
return cur, proc
case u.Image == "" || u.Version == cur.version:
return cur, proc
case !safeVersion.MatchString(u.Version):
l.cfg.Log.Warn("ignoring an invalid release name", "release", u.Version)
return cur, proc
case time.Since(l.failed[u.Version]) < l.cfg.RetryAfter:
return cur, proc
}
log := l.cfg.Log.With("from", cur.version, "to", u.Version)
next, err := l.obtain(ctx, u)
if err != nil {
log.Error("downloading the release failed", "image", u.Image, "error", err)
return cur, proc
}
log.Info("switching release")
proc.Stop(l.cfg.StopTimeout)
np, err := l.cfg.Start(next.path)
if err == nil && l.ready(ctx, np) {
if err := l.remember(next, cur); err != nil {
log.Warn("saving the release choice failed", "error", err)
}
log.Info("release switched")
return next, np
}
if np != nil {
np.Stop(l.cfg.StopTimeout)
}
log.Error("the release did not become ready; rolling back", "error", err, "retry_in", l.cfg.RetryAfter)
l.failed[u.Version] = time.Now()
back, err := l.cfg.Start(cur.path)
if err != nil {
log.Error("restarting the previous release failed", "error", err)
return cur, nil
}
return cur, back
}
// obtain returns the binary of u's release: the bundled one, one
// downloaded before, or a fresh download.
func (l *Launcher) obtain(ctx context.Context, u agentapi.Update) (release, error) {
if u.Version == l.bundled.version {
return l.bundled, nil
}
path := l.releasePath(u.Version)
if v, err := l.cfg.Version(path); err == nil && v == u.Version {
return release{u.Version, path}, nil
}
bin, err := l.cfg.Fetch(ctx, u)
if err != nil {
return release{}, err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return release{}, err
}
tmp := path + ".tmp"
if err := writeFileSync(tmp, bin, 0o700); err != nil {
return release{}, err
}
if v, err := l.cfg.Version(tmp); err != nil || v != u.Version {
_ = os.Remove(tmp)
if err != nil {
return release{}, fmt.Errorf("launcher: the downloaded binary does not run: %w", err)
}
return release{}, fmt.Errorf("launcher: the downloaded binary is %q, not %s", v, u.Version)
}
if err := os.Rename(tmp, path); err != nil {
return release{}, err
}
return release{u.Version, path}, nil
}
func writeFileSync(path string, data []byte, mode os.FileMode) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
if _, err := f.Write(data); err != nil {
_ = f.Close()
return err
}
if err := f.Sync(); err != nil {
_ = f.Close()
return err
}
return f.Close()
}
// ready waits until the agent is ready, it exits or ReadyWait passes.
func (l *Launcher) ready(ctx context.Context, p Process) bool {
deadline := time.Now().Add(l.cfg.ReadyWait)
tick := time.NewTicker(min(time.Second, l.cfg.ReadyWait/10))
defer tick.Stop()
for time.Now().Before(deadline) {
select {
case <-ctx.Done():
return false
case <-p.Done():
return false
case <-tick.C:
if l.cfg.Ready(ctx) == nil {
return true
}
}
}
return false
}
// remember records next as the release to start with and deletes all other
// downloads except prev, the fallback.
func (l *Launcher) remember(next, prev release) error {
if next == l.bundled {
if err := os.Remove(l.currentFile()); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
} else if err := writeFileSync(l.currentFile(), []byte(next.version+"\n"), 0o600); err != nil {
return err
}
entries, err := os.ReadDir(filepath.Join(l.cfg.Dir, "releases"))
if err != nil {
return nil
}
for _, e := range entries {
if e.Name() != next.version && e.Name() != prev.version {
_ = os.RemoveAll(filepath.Join(l.cfg.Dir, "releases", e.Name()))
}
}
return nil
}
+307
View File
@@ -0,0 +1,307 @@
package launcher
import (
"context"
"errors"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
// The fake world: a binary is a file holding "version <v>"; a started
// release is ready unless listed in broken and exits at once if listed in
// crashing.
type fakeProc struct {
version string
done chan struct{}
once sync.Once
}
func (p *fakeProc) Stop(time.Duration) { p.once.Do(func() { close(p.done) }) }
func (p *fakeProc) Done() <-chan struct{} { return p.done }
func (p *fakeProc) Err() error { return errors.New("exit status 1") }
type world struct {
t *testing.T
dir string
mu sync.Mutex
// target is what the API names; fetchErr fails downloads.
target agentapi.Update
fetchErr error
fetched int
wrongBin bool
broken map[string]bool
crashing map[string]bool
running *fakeProc
started []string
}
func newWorld(t *testing.T) *world {
w := &world{t: t, dir: t.TempDir(), broken: map[string]bool{}, crashing: map[string]bool{}}
if err := os.WriteFile(filepath.Join(w.dir, "bundled"), []byte("version v1.0.0"), 0o755); err != nil {
t.Fatal(err)
}
return w
}
func (w *world) config() Config {
return Config{
Agent: "checker", Bundled: filepath.Join(w.dir, "bundled"), Dir: filepath.Join(w.dir, "state"),
Interval: 20 * time.Millisecond, ReadyWait: 100 * time.Millisecond, StopTimeout: time.Second, RetryAfter: time.Hour,
Log: slog.New(slog.DiscardHandler),
Updates: func(context.Context) (agentapi.Update, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.target.Version == "" {
return agentapi.Update{}, errors.New("api down")
}
return w.target, nil
},
Fetch: func(_ context.Context, u agentapi.Update) ([]byte, error) {
w.mu.Lock()
defer w.mu.Unlock()
w.fetched++
if w.fetchErr != nil {
return nil, w.fetchErr
}
if w.wrongBin {
return []byte("version v6.6.6"), nil
}
return []byte("version " + u.Version), nil
},
Start: func(path string) (Process, error) {
v, err := fakeVersion(path)
if err != nil {
return nil, err
}
w.mu.Lock()
defer w.mu.Unlock()
p := &fakeProc{version: v, done: make(chan struct{})}
if w.crashing[v] {
close(p.done)
}
w.running = p
w.started = append(w.started, v)
return p, nil
},
Ready: func(context.Context) error {
w.mu.Lock()
defer w.mu.Unlock()
if w.running == nil || w.broken[w.running.version] {
return errors.New("not ready")
}
return nil
},
Version: fakeVersion,
}
}
func fakeVersion(path string) (string, error) {
raw, err := os.ReadFile(path)
if err != nil {
return "", err
}
v, ok := strings.CutPrefix(string(raw), "version ")
if !ok {
return "", errors.New("not a binary")
}
return v, nil
}
func (w *world) set(fn func(w *world)) {
w.mu.Lock()
defer w.mu.Unlock()
fn(w)
}
func (w *world) runningVersion() string {
w.mu.Lock()
defer w.mu.Unlock()
if w.running == nil {
return ""
}
return w.running.version
}
// current is the release the launcher starts with next time.
func (w *world) current() string {
raw, _ := os.ReadFile(filepath.Join(w.dir, "state", "current"))
return strings.TrimSpace(string(raw))
}
// eventually waits for cond.
func eventually(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(5 * time.Millisecond)
}
}
func run(t *testing.T, w *world) (cancel func() error) {
t.Helper()
ctx, stop := context.WithCancel(context.Background())
errc := make(chan error, 1)
go func() { errc <- New(w.config()).Run(ctx) }()
return func() error {
stop()
return <-errc
}
}
func TestUpdateAndRestart(t *testing.T) {
w := newWorld(t)
stop := run(t, w)
eventually(t, "bundled start", func() bool { return w.runningVersion() == "v1.0.0" })
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "reg/uptimesebi-checker:1.1.0"} })
eventually(t, "update to v1.1.0", func() bool { return w.runningVersion() == "v1.1.0" && w.current() == "v1.1.0" })
if err := stop(); err != nil {
t.Fatal(err)
}
// A restart starts the release chosen last time, without downloading.
before := w.fetched
stop = run(t, w)
eventually(t, "restart with v1.1.0", func() bool { return w.runningVersion() == "v1.1.0" })
time.Sleep(60 * time.Millisecond)
if w.fetched != before {
t.Error("the release was downloaded again")
}
// Another update keeps the previous release as fallback and deletes
// older ones; going back to the bundled release needs no download.
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.2.0", Image: "x"} })
eventually(t, "update to v1.2.0", func() bool { return w.runningVersion() == "v1.2.0" })
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.0.0", Image: "x"} })
gone := func(p ...string) bool {
_, err := os.Stat(filepath.Join(append([]string{w.dir, "state"}, p...)...))
return os.IsNotExist(err)
}
eventually(t, "back to bundled, old releases deleted", func() bool {
return w.runningVersion() == "v1.0.0" && gone("current") && gone("releases", "v1.1.0")
})
if gone("releases", "v1.2.0") {
t.Error("the fallback release was deleted")
}
if err := stop(); err != nil {
t.Fatal(err)
}
}
func TestRollback(t *testing.T) {
w := newWorld(t)
w.broken["v2.0.0"] = true
stop := run(t, w)
eventually(t, "bundled start", func() bool { return w.runningVersion() == "v1.0.0" })
w.set(func(w *world) { w.target = agentapi.Update{Version: "v2.0.0", Image: "x"} })
eventually(t, "rollback", func() bool {
w.mu.Lock()
defer w.mu.Unlock()
n := len(w.started)
return n >= 3 && w.started[n-2] == "v2.0.0" && w.started[n-1] == "v1.0.0"
})
// The failed release is not tried again right away.
time.Sleep(100 * time.Millisecond)
w.mu.Lock()
tries := strings.Count(strings.Join(w.started, " "), "v2.0.0")
w.mu.Unlock()
if tries != 1 || w.runningVersion() != "v1.0.0" {
t.Errorf("started %v", w.started)
}
if err := stop(); err != nil {
t.Fatal(err)
}
}
func TestCrashAfterRestart(t *testing.T) {
w := newWorld(t)
stop := run(t, w)
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "x"} })
eventually(t, "update", func() bool { return w.runningVersion() == "v1.1.0" && w.current() == "v1.1.0" })
if err := stop(); err != nil {
t.Fatal(err)
}
// After a restart the remembered release crashes at once: the bundled
// release takes over.
w.set(func(w *world) { w.crashing["v1.1.0"] = true; w.target = agentapi.Update{} })
stop = run(t, w)
eventually(t, "fallback", func() bool { return w.runningVersion() == "v1.0.0" })
if err := stop(); err != nil {
t.Fatal(err)
}
// The bundled release crashing ends the launcher, so the container
// restarts.
w.set(func(w *world) { w.crashing["v1.0.0"] = true })
if err := New(w.config()).Run(context.Background()); err == nil {
t.Error("a crashing bundled agent did not end the launcher")
}
}
func TestBadDownloads(t *testing.T) {
w := newWorld(t)
w.fetchErr = errors.New("signature does not match")
stop := run(t, w)
w.set(func(w *world) { w.target = agentapi.Update{Version: "v1.1.0", Image: "x"} })
eventually(t, "retries", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return w.fetched >= 2 })
if w.runningVersion() != "v1.0.0" {
t.Error("switched without a verified download")
}
// A binary that is not the release asked for is never run.
w.set(func(w *world) { w.fetchErr = nil; w.wrongBin = true })
eventually(t, "more retries", func() bool { w.mu.Lock(); defer w.mu.Unlock(); return w.fetched >= 4 })
w.mu.Lock()
for _, v := range w.started {
if v != "v1.0.0" {
t.Errorf("started %s", v)
}
}
w.mu.Unlock()
// Unreleased platforms and nonsense release names are ignored.
w.set(func(w *world) { w.wrongBin = false; w.target = agentapi.Update{Version: "dev"} })
time.Sleep(60 * time.Millisecond)
w.set(func(w *world) { w.target = agentapi.Update{Version: "../../etc", Image: "x"} })
time.Sleep(60 * time.Millisecond)
if w.runningVersion() != "v1.0.0" {
t.Error("followed an unreleased or invalid release")
}
if err := stop(); err != nil {
t.Fatal(err)
}
}
func TestBinaryVersion(t *testing.T) {
dir := t.TempDir()
script := func(name, body string) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil {
t.Fatal(err)
}
return p
}
if v, err := BinaryVersion(script("good", `[ "$1" = version ] && echo v1.2.3`)); err != nil || v != "v1.2.3" {
t.Errorf("BinaryVersion = %q, %v", v, err)
}
for name, body := range map[string]string{"silent": "true", "failing": "exit 3", "chatty": "echo hello world"} {
if v, err := BinaryVersion(script(name, body)); err == nil {
t.Errorf("%s: BinaryVersion = %q", name, v)
}
}
if _, err := BinaryVersion(filepath.Join(dir, "missing")); err == nil {
t.Error("read a missing file")
}
if p := Platform(); p.OS == "" || p.Architecture == "" {
t.Errorf("Platform = %v", p)
}
}
+86
View File
@@ -0,0 +1,86 @@
package launcher
import (
"context"
"fmt"
"os"
"os/exec"
"runtime"
"runtime/debug"
"strings"
"syscall"
"time"
v1 "github.com/google/go-containerregistry/pkg/v1"
)
type process struct {
cmd *exec.Cmd
done chan struct{}
err error
}
// StartProcess runs path with the launcher's environment and output.
func StartProcess(path string) (Process, error) {
cmd := exec.Command(path)
cmd.Stdout, cmd.Stderr, cmd.Env = os.Stdout, os.Stderr, os.Environ()
if err := cmd.Start(); err != nil {
return nil, err
}
p := &process{cmd: cmd, done: make(chan struct{})}
go func() {
p.err = cmd.Wait()
close(p.done)
}()
return p, nil
}
// Done is closed when the agent has exited.
func (p *process) Done() <-chan struct{} { return p.done }
// Err is the agent's exit error.
func (p *process) Err() error { return p.err }
// Stop sends SIGTERM and kills the agent after timeout.
func (p *process) Stop(timeout time.Duration) {
_ = p.cmd.Process.Signal(syscall.SIGTERM)
select {
case <-p.done:
case <-time.After(timeout):
_ = p.cmd.Process.Kill()
<-p.done
}
}
// BinaryVersion asks an agent binary which release it is.
func BinaryVersion(path string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, path, "version").Output()
if err != nil {
return "", err
}
v := strings.TrimSpace(string(out))
if v == "" || strings.ContainsAny(v, " \n") {
return "", fmt.Errorf("launcher: %s reports no release", path)
}
return v, nil
}
// Platform is the platform this launcher was built for, and so the agent
// binaries it runs.
func Platform() v1.Platform {
p := v1.Platform{OS: runtime.GOOS, Architecture: runtime.GOARCH}
if runtime.GOARCH != "arm" {
return p
}
p.Variant = "v7" // Go's default for linux/arm
if info, ok := debug.ReadBuildInfo(); ok {
for _, s := range info.Settings {
if s.Key == "GOARM" && s.Value != "" {
p.Variant = "v" + s.Value[:1]
}
}
}
return p
}