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 "; 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) } }