diff --git a/config.example.toml b/config.example.toml index 7436cccfc..7aefe69a9 100644 --- a/config.example.toml +++ b/config.example.toml @@ -185,6 +185,16 @@ class = "ollama" # Per-index lifecycle metadata DB (default: /workspace-indexes.db). # db_path = "/var/lib/archie/workspace-indexes.db" +# archied's own liveness surface, always on. GET /healthz and /health answer +# 200 once the daemon is serving (503 while it is still booting), and +# /health/detailed reports the readiness probes. This is what the update +# watchdog polls after restarting archied to decide whether the release came +# up or has to be rolled back, so it stays separate from the dashboard's +# /healthz: the dashboard can be switched off, and it runs as its own process +# in the extracted UI topology. +[health] +listen = "127.0.0.1:8485" + # Web dashboard and API: task board, activity stream, chat, config, # logs, memory, SSE events. Served as an embedded SPA with a full REST # and streaming API. Auth is token-based for non-loopback addresses; diff --git a/deployments/README.md b/deployments/README.md index 351f0ec4b..821b6f8a8 100644 --- a/deployments/README.md +++ b/deployments/README.md @@ -62,6 +62,23 @@ archie-state-store -config ~/.config/archie/config.toml -listen 127.0.0.1:9090 archie-state-store -config ~/.config/archie/config.toml -listen 172.17.0.1:9090 -token ``` +## Verifying the daemon + +`archied` always serves its own liveness surface on `[health].listen` +(`127.0.0.1:8485` by default). It answers 503 for the whole of boot and 200 +once the daemon is running, which is what makes it a usable restart check: + +```bash +curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8485/healthz # 200 = daemon running, 503 = still booting +curl -s http://127.0.0.1:8485/health/detailed # readiness probes, 503 when degraded +``` + +The update watchdog polls this address after restarting the daemon and rolls +the release back when it never answers, so a deployment that moves it must +change `[health].listen` rather than relying on the script's fallback. The +dashboard's `/healthz` is a separate surface on `[web].listen` and reports the +dashboard's process, not the daemon's. + ## Verifying the State Store `archie-state-store` exposes an optional HTTP readiness surface when launched diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 108021ba1..549d5447c 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -88,6 +88,7 @@ type boot struct { bootOverlayErr atomic.Pointer[string] currentProvenance atomic.Pointer[configuration.Provenance] + health *healthSurface logFeed *logging.Feed taskLogs *logging.TaskRegistry @@ -1670,6 +1671,9 @@ func exitCode(err error) int { } func (b *boot) runLoop(ctx context.Context, once bool) error { + // Boot is done: the liveness surface stops answering 503, which is what + // the update watchdog is waiting to see after a restart. + b.health.markServing() if once { b.d.Cycle(ctx) return nil diff --git a/internal/app/archied/health.go b/internal/app/archied/health.go new file mode 100644 index 000000000..ece5aab69 --- /dev/null +++ b/internal/app/archied/health.go @@ -0,0 +1,122 @@ +package archied + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "sync/atomic" + "time" + + "github.com/samcharles93/archie-core/internal/domain/health" +) + +// healthSurface is archied's own liveness endpoint, served on +// [health].listen for the lifetime of the process. +// +// The dashboard also answers /healthz, but on the dashboard's listener: that +// can be switched off, and in Phase 3 it belongs to a separate process +// entirely. Either way it is the wrong thing to ask "did archied come back +// up?" -- which is exactly what the update watchdog asks after restarting +// the daemon, and answers with a rollback when nothing replies +// (archie-core-1r4g, archie-core-exbz). +// +// serving gates the liveness answer: the listener binds early in boot, so +// the port is answering before the daemon is, and a 200 before the daemon +// reached its run loop would tell the watchdog a half-started release came +// up fine. +type healthSurface struct { + serving atomic.Bool + registry func() *health.Registry +} + +// markServing tolerates a nil surface so a boot path that serves no health +// endpoint (the Gateway and State Store entry points) cannot panic here. +func (h *healthSurface) markServing() { + if h == nil { + return + } + h.serving.Store(true) +} + +func (h *healthSurface) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", h.handleLiveness) + mux.HandleFunc("GET /health", h.handleLiveness) + mux.HandleFunc("GET /health/detailed", h.handleDetailed) + return mux +} + +func (h *healthSurface) handleLiveness(w http.ResponseWriter, _ *http.Request) { + if !h.serving.Load() { + http.Error(w, "starting", http.StatusServiceUnavailable) + return + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok")) +} + +// handleDetailed reports the daemon's readiness probes, the same registry +// the dashboard serves. A nil registry (probes not wired yet, or at all) +// answers 503 rather than fabricating a report, so a deployment never looks +// healthy by accident. +func (h *healthSurface) handleDetailed(w http.ResponseWriter, r *http.Request) { + var registry *health.Registry + if h.registry != nil { + registry = h.registry() + } + if registry == nil { + http.Error(w, "readiness probes are unavailable", http.StatusServiceUnavailable) + return + } + report := registry.Run(r.Context()) + w.Header().Set("Content-Type", "application/json") + if report.Status != health.StatusOK { + w.WriteHeader(http.StatusServiceUnavailable) + } + _ = json.NewEncoder(w).Encode(report) +} + +// startHealth binds the daemon's liveness surface on [health].listen. A +// failure to bind is fatal: a daemon nothing can probe cannot have its own +// updates verified, and the watchdog would roll back every release it +// installs. +func (b *boot) startHealth(ctx context.Context) error { + b.health = &healthSurface{registry: func() *health.Registry { + if b.web == nil { + return nil + } + return b.web.Health + }} + addr := b.cfg.Health.Listen + if err := b.serveHealth(ctx, addr, b.health.handler(), "daemon health"); err != nil { + b.log.Error("health listener failed", "addr", addr, "err", err) + return err + } + return nil +} + +// serveHealth runs mux on addr until shutdown, registering its own cleanup. +// Shared by the daemon and the standalone State Store, which serve the same +// three routes over different probes. label names the surface in the log and +// error text, which operators and the State Store's own process test read. +func (b *boot) serveHealth(ctx context.Context, addr string, mux http.Handler, label string) error { + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", addr) + if err != nil { + return fmt.Errorf("listen for %s: %w", label, err) + } + srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second} + go func() { + if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed { + b.log.Error(label+" server stopped", "err", err) + } + }() + b.addCleanup(func() { + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second) + defer cancel() + _ = srv.Shutdown(shutdownCtx) + }) + b.log.Info(label+" listening", "addr", "http://"+listener.Addr().String()) + return nil +} diff --git a/internal/app/archied/health_test.go b/internal/app/archied/health_test.go new file mode 100644 index 000000000..36aa5f588 --- /dev/null +++ b/internal/app/archied/health_test.go @@ -0,0 +1,82 @@ +package archied + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/health" +) + +// TestHealthSurfaceLivenessWaitsForBoot: the update watchdog restarts archied +// and takes the first 200 as proof the new release came up. The listener +// binds early so the port is not simply refused during boot, which means an +// unconditional 200 would confirm a release that had not started yet. +func TestHealthSurfaceLivenessWaitsForBoot(t *testing.T) { + surface := &healthSurface{} + handler := surface.handler() + + for _, path := range []string{"/healthz", "/health"} { + res := httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) + if res.Code != http.StatusServiceUnavailable { + t.Errorf("GET %s while booting = %d, want 503", path, res.Code) + } + } + + surface.markServing() + + for _, path := range []string{"/healthz", "/health"} { + res := httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil)) + if res.Code != http.StatusOK { + t.Errorf("GET %s once serving = %d, want 200", path, res.Code) + } + } +} + +// TestHealthSurfaceDetailedReportsProbes: /health/detailed is the readiness +// answer, and an unwired or degraded registry must never read as ready. +func TestHealthSurfaceDetailedReportsProbes(t *testing.T) { + var registry *health.Registry + surface := &healthSurface{registry: func() *health.Registry { return registry }} + surface.markServing() + handler := surface.handler() + + res := httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)) + if res.Code != http.StatusServiceUnavailable { + t.Fatalf("detailed with no probes = %d, want 503", res.Code) + } + + registry = health.NewRegistry(failingProbe{}) + res = httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)) + if res.Code != http.StatusServiceUnavailable { + t.Fatalf("detailed with a failing probe = %d, want 503", res.Code) + } + + registry = health.NewRegistry(passingProbe{}) + res = httptest.NewRecorder() + handler.ServeHTTP(res, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/health/detailed", nil)) + if res.Code != http.StatusOK { + t.Fatalf("detailed with a passing probe = %d, want 200", res.Code) + } +} + +type failingProbe struct{} + +func (failingProbe) Name() string { return "test" } + +func (failingProbe) Check(context.Context) health.Result { + return health.Result{Status: health.StatusDegraded, Detail: "down"} +} + +type passingProbe struct{} + +func (passingProbe) Name() string { return "test" } + +func (passingProbe) Check(context.Context) health.Result { + return health.Result{Status: health.StatusOK} +} diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index f3151a6d5..b5ef64c2d 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -374,6 +374,13 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del } defer b.cleanup() + // Before any subsystem: the port answers 503 for the whole of boot, so a + // watchdog polling a restarted daemon sees "not yet" rather than a + // refused connection it cannot tell from a crash. + if err := b.startHealth(ctx); err != nil { + return 1 + } + if err := b.openStores(ctx); err != nil { return 1 } @@ -429,10 +436,7 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del } b.registerStandaloneTools() b.buildDaemon() - b.wireConfigPublishing(ctx, args.cfgPath, args.overlayPath) - b.installUpdateConfigHandler() - b.installUpdateRepoFieldHandler() - b.installConfigHandlers(args.cfgPath, args.overlayPath) + b.wireConfigSurfaces(ctx, args.cfgPath, args.overlayPath) if err := b.startServices(ctx); err != nil { return 1 @@ -440,6 +444,19 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del return exitCode(b.runLoop(ctx, args.once)) } +// wireConfigSurfaces attaches the dashboard's configuration read and write +// paths: the published snapshot plus the three validate-persist-publish +// handlers behind PATCH /api/config, POST /api/config/reset and the +// per-repository field update. They are wired together because they are one +// capability -- the daemon owning configuration on the dashboard's behalf -- +// and archie-core-8cda.5.4 replaces the set of them at once. +func (b *boot) wireConfigSurfaces(ctx context.Context, cfgPath, overlayPath string) { + b.wireConfigPublishing(ctx, cfgPath, overlayPath) + b.installUpdateConfigHandler() + b.installUpdateRepoFieldHandler() + b.installConfigHandlers(cfgPath, overlayPath) +} + // bootConfigOverlay layers the runtime config overlay over the resolved // file config. Every failure degrades rather than aborts -- the daemon // boots on file config alone and the reason is recorded in bootOverlayErr, diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index ac3a62957..4e4147a70 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -186,23 +186,7 @@ func (b *boot) startStateStoreReadiness(ctx context.Context, readyAddr string) e } _ = json.NewEncoder(w).Encode(report) }) - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", readyAddr) - if err != nil { - return fmt.Errorf("listen for state store readiness: %w", err) - } - srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second} - go func() { - if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed { - b.log.Error("state store readiness server stopped", "err", err) - } - }() - b.addCleanup(func() { - shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second) - defer cancel() - _ = srv.Shutdown(shutdownCtx) - }) - b.log.Info("state store readiness listening", "addr", "http://"+listener.Addr().String()) - return nil + return b.serveHealth(ctx, readyAddr, mux, "state store readiness") } // stateStoreServerOpts applies the transport security boundary (ยง9): a diff --git a/internal/app/archied/telegram_setup.go b/internal/app/archied/telegram_setup.go index d0508987d..cea9e1d01 100644 --- a/internal/app/archied/telegram_setup.go +++ b/internal/app/archied/telegram_setup.go @@ -26,7 +26,6 @@ import ( "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/tools" - "github.com/samcharles93/archie-core/internal/webui" ) // telegramSetup contains the inputs needed to initialise the Telegram @@ -238,7 +237,7 @@ func makeUpdateService(s telegramSetup) *releaseupdate.Service { if len(cfg.Chat.Telegram.UpdateInstallCommand) != 0 { updates.Installer = releaseupdate.CommandInstaller{ Command: cfg.Chat.Telegram.UpdateInstallCommand, - HealthURL: webui.HealthURL(cfg.Web.Listen), + HealthURL: cfg.Health.URL(), } } return updates diff --git a/internal/app/archied/telegram_setup_test.go b/internal/app/archied/telegram_setup_test.go index 3d7493914..b8bb86884 100644 --- a/internal/app/archied/telegram_setup_test.go +++ b/internal/app/archied/telegram_setup_test.go @@ -201,20 +201,22 @@ func TestDaemonRunningVersionsIncludesObservedAgent(t *testing.T) { } } -// TestMakeUpdateServiceDerivesHealthURLFromWebListen: the watchdog's health -// probe has to reach the dashboard listener this instance actually binds. -// Left to the script's own default it polls a port nothing serves, waits out -// the timeout and rolls back a release that came up fine (archie-core-1r4g). -func TestMakeUpdateServiceDerivesHealthURLFromWebListen(t *testing.T) { +// TestMakeUpdateServiceProbesTheDaemonsOwnHealthAddress: the watchdog is +// verifying archied's restart, so it has to probe archied. The dashboard's +// listener is the wrong answer twice over -- it can be switched off, and in +// Phase 3 it belongs to another process, which would report health for +// something the watchdog never restarted (archie-core-1r4g). +func TestMakeUpdateServiceProbesTheDaemonsOwnHealthAddress(t *testing.T) { for _, tc := range []struct{ name, listen, want string }{ - {name: "loopback dashboard", listen: "127.0.0.1:9000", want: "http://127.0.0.1:9000"}, - {name: "wildcard bind", listen: "0.0.0.0:8484", want: "http://localhost:8484"}, - {name: "dashboard off", listen: "off", want: ""}, - {name: "dashboard unset", listen: "", want: ""}, + {name: "default loopback", listen: "127.0.0.1:8485", want: "http://127.0.0.1:8485"}, + {name: "wildcard bind", listen: "0.0.0.0:8485", want: "http://localhost:8485"}, + {name: "operator-chosen port", listen: "127.0.0.1:9500", want: "http://127.0.0.1:9500"}, } { t.Run(tc.name, func(t *testing.T) { cfg := config.Config{} - cfg.Web.Listen = tc.listen + cfg.Health.Listen = tc.listen + // The dashboard's own address must not leak into the probe. + cfg.Web.Listen = "127.0.0.1:8484" cfg.Chat.Telegram.UpdateCheckCommand = []string{"archie-update-check"} cfg.Chat.Telegram.UpdateInstallCommand = []string{"archie-update-install"} diff --git a/internal/channels/telegram/update_regression_test.go b/internal/channels/telegram/update_regression_test.go deleted file mode 100644 index a90719897..000000000 --- a/internal/channels/telegram/update_regression_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package telegram - -import ( - "context" - "log/slog" - "testing" - "time" - - "github.com/go-telegram/bot/models" - - "github.com/samcharles93/archie-core/internal/releaseupdate" -) - -// contextAwareUpdateStub embeds the shared updateStub so the interface's -// Check/Defer/CanInstall come for free, and overrides only Install to -// capture the context the gateway hands to the installer. Capturing a -// context in a test double is the accepted exception to "don't store -// contexts": the regression test needs to observe which context reached -// Install. -type contextAwareUpdateStub struct { - updateStub - started chan struct{} - installCtx context.Context //nolint:containedctx // test double must observe which context reached Install -} - -func (s *contextAwareUpdateStub) Install(ctx context.Context, _ releaseupdate.Snapshot, _ releaseupdate.InstallMeta, _ func(string)) (releaseupdate.Result, error) { - s.installCtx = ctx - close(s.started) - return releaseupdate.Result{}, nil -} - -func TestInstallUpdateDetachesInstallerFromCallbackContext(t *testing.T) { - g := New("1:test", "", "", []int64{42}, slog.Default()) - stub := &contextAwareUpdateStub{started: make(chan struct{})} - g.Updates = stub - b, _ := newTelegramTestBot(t) - // t.Context() is the framework-owned parent: it auto-cancels at test - // teardown, so a failure before cancel() can't orphan the goroutine's - // context. We still derive a cancellable child because the test must - // cancel the callback context itself -- mirroring Telegram's handler - // lifetime ending -- while the installer is mid-flight. - callbackCtx, cancel := context.WithCancel(t.Context()) - message := &models.Message{Chat: models.Chat{ID: 7}, ID: 100} - - done := make(chan struct{}) - go func() { - g.installUpdate(callbackCtx, b, &models.CallbackQuery{ - From: models.User{ID: 42}, - Message: models.MaybeInaccessibleMessage{Message: message}, - }, releaseupdate.Snapshot{}) - close(done) - }() - <-stub.started - cancel() - - select { - case <-stub.installCtx.Done(): - t.Fatal("installer context was cancelled with the callback context") - case <-time.After(20 * time.Millisecond): - } - select { - case <-done: - case <-time.After(time.Second): - t.Fatal("installUpdate did not finish") - } -} diff --git a/internal/config/config.go b/internal/config/config.go index 12287d019..1ed54ede5 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -18,6 +18,7 @@ import ( "encoding/json" "fmt" "maps" + "net" "strings" "time" @@ -508,6 +509,7 @@ type Config struct { Budgets Budgets `toml:"budgets" yaml:"budgets"` Web Web `toml:"web" yaml:"web"` + Health Health `toml:"health" yaml:"health"` Log Log `toml:"log" yaml:"log"` Notify Notify `toml:"notify" yaml:"notify"` NATS NATSConfig `toml:"nats" yaml:"nats"` @@ -954,6 +956,37 @@ type Notify struct { } // Web configures the observability dashboard. +// Health is archied's own liveness surface, always on. It is separate from +// the dashboard's /healthz because the process whose restart is being +// verified has to be the one answering: the dashboard can be switched off, +// and it becomes its own process in Phase 3, at which point probing it would +// report health for something the update watchdog never restarted. +type Health struct { + // Listen is the address the daemon serves /healthz, /health and + // /health/detailed on. Defaulted, never empty in a loaded config. + Listen string `toml:"listen" yaml:"listen"` +} + +// URL renders Listen as an address a local caller can dial, which is what +// the daemon hands its update tooling (see releaseupdate.CommandInstaller). +// A wildcard bind is a valid thing to listen on but not to dial, so it +// resolves to localhost, the same substitution the dashboard link makes. +func (h Health) URL() string { + listen := strings.TrimSpace(h.Listen) + if listen == "" { + return "" + } + host, port, err := net.SplitHostPort(listen) + if err != nil { + host, port = "", strings.TrimPrefix(listen, ":") + } + switch host { + case "", "0.0.0.0", "::", "[::]": + host = "localhost" + } + return "http://" + net.JoinHostPort(host, port) +} + type Web struct { // Listen is the dashboard address; "off" disables the web UI. // Bind localhost (or a LAN/tailnet address) -- there is no auth. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 6b7fd5ca2..7c4fc43b8 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -467,3 +467,23 @@ func TestWebConfigTOML(t *testing.T) { }) } } + +// TestHealthURL renders the address out-of-process tooling probes. A wrong +// address here reads as an unhealthy release and rolls back one that came up +// fine (archie-core-1r4g). +func TestHealthURL(t *testing.T) { + for _, tc := range []struct{ listen, want string }{ + {"127.0.0.1:8485", "http://127.0.0.1:8485"}, + {"localhost:8485", "http://localhost:8485"}, + {"0.0.0.0:8485", "http://localhost:8485"}, + {":8485", "http://localhost:8485"}, + {"[::]:8485", "http://localhost:8485"}, + {"100.64.1.2:9000", "http://100.64.1.2:9000"}, + {" 127.0.0.1:8485 ", "http://127.0.0.1:8485"}, + {"", ""}, + } { + if got := (Health{Listen: tc.listen}).URL(); got != tc.want { + t.Errorf("Health{Listen: %q}.URL() = %q, want %q", tc.listen, got, tc.want) + } + } +} diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index a9eb507a5..1fef7ea47 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -47,6 +47,10 @@ const ( defaultCaptureMaxBodyBytes = 256 * 1024 defaultCaptureRatePerSecond = 1.0 defaultCaptureRateBurst = 5 + + // defaultHealthListen is the daemon's own liveness address. The update + // watchdog's fallback in scripts/archie-update-watchdog must match it. + defaultHealthListen = "127.0.0.1:8485" ) // applyDefaults fills in every absent value. It never reports an error and @@ -62,6 +66,9 @@ func (l *Loader) applyDefaults(cfg *config.Config) { if cfg.Services.Gateway.Target == "" { cfg.Services.Gateway.Target = "127.0.0.1:8585" } + if cfg.Health.Listen == "" { + cfg.Health.Listen = defaultHealthListen + } l.applyGeneralDefaults(cfg) applyForgeDefaults(cfg) applyDispatchDefaults(cfg) diff --git a/internal/infrastructure/configuration/services_test.go b/internal/infrastructure/configuration/services_test.go index faa2c161b..b5e1efd7c 100644 --- a/internal/infrastructure/configuration/services_test.go +++ b/internal/infrastructure/configuration/services_test.go @@ -28,3 +28,31 @@ func TestLoadGatewayServiceTarget(t *testing.T) { }) } } + +// TestLoadHealthListen: the daemon's liveness surface is not optional. The +// update watchdog restarts archied and asks whether it came back, and only +// archied can answer that -- the dashboard's /healthz belongs to the +// dashboard, which can be switched off and moves to its own process +// (archie-core-1r4g, archie-core-exbz). +func TestLoadHealthListen(t *testing.T) { + for _, tt := range []struct { + name, section, wantListen string + }{ + {name: "default", wantListen: "127.0.0.1:8485"}, + {name: "explicit listen", section: "[health]\nlisten = '127.0.0.1:9500'", wantListen: "127.0.0.1:9500"}, + } { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"+tt.section), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := loadFile(path) + if err != nil { + t.Fatal(err) + } + if cfg.Health.Listen != tt.wantListen { + t.Fatalf("health listen = %q, want %q", cfg.Health.Listen, tt.wantListen) + } + }) + } +} diff --git a/internal/releaseupdate/install_script_test.go b/internal/releaseupdate/install_script_test.go index cb42fabf5..e20f58ea3 100644 --- a/internal/releaseupdate/install_script_test.go +++ b/internal/releaseupdate/install_script_test.go @@ -170,18 +170,18 @@ func TestUpdateWatchdogPassesHealthCheckAgainstRealListener(t *testing.T) { assertCallAbsent(t, calls, "docker image load") } -// TestUpdateWatchdogDefaultHealthURLTargetsTheDashboardListener pins the -// fallback the script uses when nothing exports one. It has to be the -// address archied serves /healthz on (config.example.toml's [web] listen); -// anything else times out and rolls back a healthy release. -func TestUpdateWatchdogDefaultHealthURLTargetsTheDashboardListener(t *testing.T) { +// TestUpdateWatchdogDefaultHealthURLTargetsTheDaemon pins the fallback the +// script uses when nothing exports one. It has to be the address archied +// itself serves /healthz on ([health] listen); anything else times out and +// rolls back a healthy release. +func TestUpdateWatchdogDefaultHealthURLTargetsTheDaemon(t *testing.T) { report, _, calls := runUpdateWatchdog(t, watchdogRun{ components: "daemon", curl: `printf '%s\n' "curl $*" >> "$ARCHIE_TEST_CALLS"; exit 0`, env: map[string]string{"ARCHIE_UPDATE_HEALTH_TIMEOUT": "10"}, }) - assertCallContains(t, calls, "curl ", "http://127.0.0.1:8484/healthz") + assertCallContains(t, calls, "curl ", "http://127.0.0.1:8485/healthz") if report.HealthCheck != "passed" || report.RolledBack { t.Fatalf("report = %#v, want a passed health check with no rollback", report) } diff --git a/internal/webui/auth.go b/internal/webui/auth.go index 739392976..ab738a29a 100644 --- a/internal/webui/auth.go +++ b/internal/webui/auth.go @@ -60,24 +60,6 @@ func DashboardURL(listen, token string) string { return url } -// HealthURL renders the base URL of this process's /healthz endpoint for -// out-of-process tooling: the update watchdog polls it after restarting -// archied to decide whether the release it just installed came up. -// -// It is empty when the dashboard is disabled, because /healthz is served by -// the dashboard listener and there is no other surface to probe. -// -// The address must remain the one archied itself binds. The watchdog is -// verifying archied's own restart, so probing an address served by a -// different process would report health for something it never restarted. -func HealthURL(listen string) string { - listen = strings.TrimSpace(listen) - if listen == "" || listen == "off" { - return "" - } - return strings.TrimSuffix(DashboardURL(listen, ""), "/") -} - // LoadOrCreateToken returns the dashboard token, generating and persisting one // on first use. The token is created rather than configured so a non-loopback // bind cannot be brought up unprotected by omission: there is no setup step to diff --git a/internal/webui/dashboard_url_test.go b/internal/webui/dashboard_url_test.go index ff251bdfe..71d9bfbde 100644 --- a/internal/webui/dashboard_url_test.go +++ b/internal/webui/dashboard_url_test.go @@ -15,24 +15,3 @@ func TestDashboardURL(t *testing.T) { } } } - -// TestHealthURL pins what out-of-process tooling probes after restarting -// archied. A wrong address here reads as an unhealthy release and triggers a -// rollback of one that came up fine (archie-core-1r4g). -func TestHealthURL(t *testing.T) { - for _, tc := range []struct{ listen, want string }{ - {"127.0.0.1:8484", "http://127.0.0.1:8484"}, - {"localhost:8484", "http://localhost:8484"}, - {"0.0.0.0:8484", "http://localhost:8484"}, - {":8484", "http://localhost:8484"}, - {"[::]:8484", "http://localhost:8484"}, - {"100.64.1.2:9000", "http://100.64.1.2:9000"}, - {" 127.0.0.1:8484 ", "http://127.0.0.1:8484"}, - {"off", ""}, - {"", ""}, - } { - if got := HealthURL(tc.listen); got != tc.want { - t.Errorf("HealthURL(%q) = %q, want %q", tc.listen, got, tc.want) - } - } -} diff --git a/scripts/archie-update-watchdog b/scripts/archie-update-watchdog index 4ef9d4824..07ebd886a 100755 --- a/scripts/archie-update-watchdog +++ b/scripts/archie-update-watchdog @@ -12,10 +12,11 @@ AGENT_IMAGE="${ARCHIE_AGENT_IMAGE:-ghcr.io/samcharles93/archie-agent:latest}" AGENT_IMAGE_BACKUP="${ARCHIE_AGENT_IMAGE_BACKUP:-$BIN_DIR/archie-agent-image.prev.tar}" TASK_DB_PATH="${ARCHIE_TASK_DB_PATH:-}" TASK_DB_BACKUP="${ARCHIE_TASK_DB_BACKUP:-$BIN_DIR/archie-task-db.prev.sqlite}" -# The daemon exports its own dashboard address (releaseupdate.CommandInstaller); +# The daemon exports its own health address (releaseupdate.CommandInstaller); # this default only covers a hand-driven run, and must stay the address archied -# serves /healthz on -- config.example.toml's [web] listen. -HEALTH_URL="${ARCHIE_HEALTH_URL:-http://127.0.0.1:8484}" +# itself serves /healthz on -- [health] listen, defaulted in +# internal/infrastructure/configuration/defaults.go. +HEALTH_URL="${ARCHIE_HEALTH_URL:-http://127.0.0.1:8485}" HEALTH_URL="${HEALTH_URL%/}" REPORT_PATH="${ARCHIE_UPDATE_REPORT_PATH:-}" HEALTH_TIMEOUT_SECONDS="${ARCHIE_UPDATE_HEALTH_TIMEOUT:-60}"