// 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 }