From ddd532b8248c3a36da21067d99766c26d8295bb4 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 19 Aug 2026 01:11:46 +1000 Subject: [PATCH] feat(update): stream live progress and roll back failed updates automatically The /update command went silent between "starting" and one final message, gave no version summary, and required manual intervention on failure. CommandInstaller now streams the installer script's stdout live instead of buffering it, and parses a structured result (previous/installed versions, per-component status) from a sentinel line. Because the reference install script hands the daemon restart off to a detached systemd unit specifically so restarting archied.service doesn't kill the process that requested the update, the outcome is reported in two phases: the synchronous build/install result comes back through Install() itself, and the post-restart health check/rollback outcome is written by a new watchdog script and relayed by whichever archied process boots next, via a small JSON handoff file cleared once relayed. Also fixes three defects an adversarial review pass found in the first draft: the caller's request/handler context was passed straight into the install child process, so a concurrent /restart or a browser disconnect could SIGKILL it mid binary-copy; Telegram and the web dashboard each tracked "install in progress" with their own private flag despite sharing one Service, allowing two installs to race the same .prev backups; and the watchdog reported rolled_back:true even when no backup existed to restore, which would have told an operator to stand down while the daemon was still broken. internal/webui gains an unauthenticated /healthz the watchdog polls after restarting archied. --- cmd/archied/main.go | 12 + cmd/archied/telegram_setup.go | 1 + internal/channels/telegram/telegram.go | 20 +- internal/channels/telegram/update.go | 158 ++++++++++++- internal/channels/telegram/update_test.go | 218 +++++++++++++++++- internal/gateway/gateway.go | 2 +- internal/gateway/web_parity_test.go | 6 +- internal/releaseupdate/command.go | 66 +++++- internal/releaseupdate/command_test.go | 134 +++++++++++ internal/releaseupdate/pending_report.go | 76 ++++++ internal/releaseupdate/pending_report_test.go | 80 +++++++ internal/releaseupdate/result.go | 37 +++ internal/releaseupdate/service.go | 92 ++++++-- internal/releaseupdate/service_test.go | 112 ++++++++- internal/webui/api_chat.go | 6 +- internal/webui/api_chat_test.go | 4 +- internal/webui/server.go | 17 +- internal/webui/webui_test.go | 15 ++ scripts/archie-update-install | 58 ++++- scripts/archie-update-watchdog | 76 ++++++ 20 files changed, 1133 insertions(+), 57 deletions(-) create mode 100644 internal/releaseupdate/command_test.go create mode 100644 internal/releaseupdate/pending_report.go create mode 100644 internal/releaseupdate/pending_report_test.go create mode 100644 internal/releaseupdate/result.go mode change 100644 => 100755 scripts/archie-update-install create mode 100755 scripts/archie-update-watchdog diff --git a/cmd/archied/main.go b/cmd/archied/main.go index ec07ee42a..27bbc78fe 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -815,6 +815,18 @@ func releaseAnnouncementStatePath(workDir, identity string) string { ) } +// updateReportPath is where the update watchdog leaves the phase-2 outcome +// of an update for this identity to relay on its next launch. Hashed the +// same way as releaseAnnouncementStatePath so multiple identities sharing +// one daemon (see docs/architecture/identity.md) never collide. +func updateReportPath(workDir, identity string) string { + identityHash := sha256.Sum256([]byte(identity)) + return filepath.Join( + workDir, + fmt.Sprintf("update-report-%x.json", identityHash[:8]), + ) +} + // safePluginInfo calls Name() and Version() on a plugin, recovering from // panics. A panicking plugin must not crash the daemon at startup. func safePluginInfo(p plugin.Plugin) (name, version string) { diff --git a/cmd/archied/telegram_setup.go b/cmd/archied/telegram_setup.go index 11aa9b547..e69cf0696 100644 --- a/cmd/archied/telegram_setup.go +++ b/cmd/archied/telegram_setup.go @@ -95,6 +95,7 @@ func setupTelegramGateway(ctx context.Context, s telegramSetup) (start func(), o {ID: "runtime", Label: "THE RUNTIME", Version: runtimeVersion, ChangelogPath: packagedRuntimeChangelogPath}, }, } + tg.UpdateReportPath = updateReportPath(cfg.WorkDir, cfg.BotUser) tg.Reload = makeTelegramReload(s) sessionStore := s.SessionStore diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 1c8d17721..bbe1dcc53 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -54,6 +54,13 @@ type Gateway struct { // deferral persistence, and installation; Telegram only presents it. Updates UpdateService + // UpdateReportPath is where the update watchdog (see + // scripts/archie-update-watchdog) leaves the phase-2 outcome of an + // update -- whether the restarted daemon came up healthy or was rolled + // back. Checked and relayed on every gateway launch (process boot and + // /restart alike), same as ReleaseAnnouncements. Empty disables it. + UpdateReportPath string + // Dangerous is the sandbox/process authority for /rollback and /stop. // When nil, those commands return "not configured". The composition // root supplies this; Telegram only renders approval UX. @@ -129,7 +136,7 @@ type Gateway struct { type UpdateService interface { Check(context.Context, int64) (releaseupdate.Snapshot, error) Defer(context.Context, int64, releaseupdate.Snapshot) error - Install(context.Context, func(string)) error + Install(context.Context, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) CanInstall() bool } @@ -285,7 +292,7 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, // the commands are undiscoverable and the LLM, having no idea they // exist, tells users there are none. g.registerCommands(ctx, b) - g.announceRelease(ctx, b) + g.notifyLaunch(ctx, b) // Set up webhook or fall back to long polling. if g.WebhookURL != "" { @@ -327,6 +334,15 @@ func (g *Gateway) launch(ctx context.Context, router *gateway.Router) (*bot.Bot, return b, nil } +// notifyLaunch sends the one-time notifications that belong to every +// gateway launch, not just a process boot: a newly installed release's +// changelog, and the phase-2 outcome of an update the watchdog finished +// while this gateway was down. +func (g *Gateway) notifyLaunch(ctx context.Context, b *bot.Bot) { + g.announceRelease(ctx, b) + g.reportPendingUpdate(ctx, b) +} + func (g *Gateway) announceRelease(ctx context.Context, b *bot.Bot) { if g.ReleaseAnnouncements == nil { return diff --git a/internal/channels/telegram/update.go b/internal/channels/telegram/update.go index 87c0b0765..59bb35b33 100644 --- a/internal/channels/telegram/update.go +++ b/internal/channels/telegram/update.go @@ -4,6 +4,8 @@ import ( "context" "crypto/rand" "encoding/hex" + "fmt" + "sort" "strings" "time" @@ -161,6 +163,14 @@ func (g *Gateway) beginUpdate() bool { return true } +// installUpdate runs the synchronous phase of an update (build/install) and +// reports it live. It deliberately never claims the update itself +// succeeded: the reference installer queues the daemon restart through a +// detached unit precisely so restarting archied.service doesn't kill this +// call before it can report a clean exit, which means the restart -- and +// whether the new version actually comes up healthy -- happens after this +// function returns. That outcome is reported separately, by whichever +// archied process boots next, via SendPendingReport. func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.CallbackQuery) { defer func() { g.updateMu.Lock() @@ -171,15 +181,153 @@ func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.C if message == nil { return } - progress := func(text string) { - g.sendMessage(ctx, b, message.Chat.ID, message.MessageThreadID, text) + meta := releaseupdate.InstallMeta{ + Channel: "telegram", ChatID: message.Chat.ID, ThreadID: message.MessageThreadID, + ReportPath: g.UpdateReportPath, } - if err := g.Updates.Install(ctx, progress); err != nil { + + var lines []string + progress := func(text string) { + lines = append(lines, text) + if _, err := b.EditMessageText(ctx, &bot.EditMessageTextParams{ + ChatID: message.Chat.ID, MessageID: message.ID, Text: progressText(lines), + }); err != nil { + g.log.Warn("update progress message failed", "error", err) + } + } + + result, err := g.Updates.Install(ctx, meta, progress) + if err != nil { g.log.Error("approved update failed", "error", err) - progress("Update failed. Archie is still running; check the installation logs and try again.") + lines = append(lines, formatInstallFailure(err)) + g.editUpdateMessage(ctx, b, query, progressText(lines)) return } - progress("Update completed. Archie will use the new version after it restarts.") + lines = append(lines, formatInstallSuccess(result)) + g.editUpdateMessage(ctx, b, query, progressText(lines)) +} + +// progressText joins accumulated status lines into one message, keeping the +// most recent lines when the total would exceed Telegram's message length +// limit -- the newest status matters most once history has to be dropped. +func progressText(lines []string) string { + text := strings.Join(lines, "\n") + runes := []rune(text) + if len(runes) <= messageMaxLen { + return text + } + return "…\n" + string(runes[len(runes)-messageMaxLen:]) +} + +// formatInstallSuccess reports the synchronous phase-1 outcome only: build +// and install succeeded, and a restart has been queued. It must not claim +// the update finished -- see installUpdate's doc comment. +func formatInstallSuccess(result releaseupdate.Result) string { + var text strings.Builder + text.WriteString("Build and install succeeded") + if changes := formatVersionChanges(result); changes != "" { + fmt.Fprintf(&text, ": %s", changes) + } + text.WriteString(".") + if result.RestartRequested { + text.WriteString(" Restart queued — I'll confirm once the new version is up and healthy.") + } + return text.String() +} + +func formatInstallFailure(err error) string { + return fmt.Sprintf("Update failed during build/install: %s. Nothing was restarted; archie-core is still running the previous version.", err) +} + +func formatVersionChanges(result releaseupdate.Result) string { + ids := make([]string, 0, len(result.Installed)) + for id := range result.Installed { + ids = append(ids, id) + } + sort.Strings(ids) + parts := make([]string, 0, len(ids)) + for _, id := range ids { + installed := result.Installed[id] + previous := result.Previous[id] + if previous == "" || previous == installed { + continue + } + parts = append(parts, fmt.Sprintf("%s %s → %s", id, previous, installed)) + } + return strings.Join(parts, ", ") +} + +// formatPendingReport describes the phase-2 outcome. There are three +// distinct cases, not two: the daemon came back up healthy; it didn't, and +// was rolled back to its previous version; or it didn't, and there was no +// backup to roll back to. That third case must never be worded like the +// second -- claiming a rollback that didn't happen tells the operator to +// stand down while the daemon may still be running the broken version, or +// not running at all. +func formatPendingReport(report releaseupdate.Report) string { + changes := formatVersionChanges(releaseupdate.Result{Previous: report.Previous, Installed: report.Installed}) + if !report.RolledBack && report.HealthCheck == "passed" { + text := "Update complete" + if changes != "" { + text += ": " + changes + } + return text + ". Health check passed — archie-core is healthy on the new version." + } + + ids := make([]string, 0, len(report.Previous)) + for id := range report.Previous { + ids = append(ids, id) + } + sort.Strings(ids) + versions := make([]string, 0, len(ids)) + for _, id := range ids { + versions = append(versions, fmt.Sprintf("%s %s", id, report.Previous[id])) + } + previousVersions := strings.Join(versions, ", ") + + if report.RolledBack { + return fmt.Sprintf("Update failed health check after restarting and was automatically rolled back to the previous version (%s). archie-core is running normally on the previous release.", previousVersions) + } + return fmt.Sprintf("Update failed health check after restarting and could NOT be rolled back automatically (no backup was found). archie-core may still be running the broken version, or may not be running at all — manual intervention is required. Previous version was %s.", previousVersions) +} + +// reportPendingUpdate checks for a phase-2 outcome left by the update +// watchdog and relays it, exactly like announceRelease -- called on every +// gateway launch so it fires whether this is a fresh process boot (the +// common case after an update restart) or a later /restart. A report is +// cleared as soon as it's handled -- relayed, or found unreadable -- so a +// later launch never retries it. An unreadable report is discarded rather +// than left in place: without clearing it, every future launch would fail +// the same decode and the chat that approved the update would never learn +// any outcome at all. +func (g *Gateway) reportPendingUpdate(ctx context.Context, b *bot.Bot) { + if g.UpdateReportPath == "" { + return + } + report, found, err := releaseupdate.ReadPendingReport(g.UpdateReportPath) + if err != nil { + g.log.Warn("read pending update report failed; discarding it", "error", err) + if clearErr := releaseupdate.ClearPendingReport(g.UpdateReportPath); clearErr != nil { + g.log.Warn("clear unreadable update report failed", "error", clearErr) + } + return + } + if !found { + return + } + g.SendPendingReport(ctx, b, report) + if err := releaseupdate.ClearPendingReport(g.UpdateReportPath); err != nil { + g.log.Warn("clear pending update report failed", "error", err) + } +} + +// SendPendingReport relays the phase-2 outcome of an update -- whether the +// restarted daemon came up healthy, or was rolled back -- to the chat that +// originally approved it. Called once, on startup, by whichever archied +// process finds a pending report left by the previous boot's install; see +// releaseupdate.ReadPendingReport. +func (g *Gateway) SendPendingReport(ctx context.Context, b *bot.Bot, report releaseupdate.Report) { + g.sendMessage(ctx, b, report.ChatID, report.ThreadID, formatPendingReport(report)) } func sameUpdateSnapshot(left, right releaseupdate.Snapshot) bool { diff --git a/internal/channels/telegram/update_test.go b/internal/channels/telegram/update_test.go index 154742490..8ed4f1694 100644 --- a/internal/channels/telegram/update_test.go +++ b/internal/channels/telegram/update_test.go @@ -2,7 +2,10 @@ package telegram import ( "context" + "errors" "log/slog" + "os" + "path/filepath" "strings" "testing" @@ -11,6 +14,8 @@ import ( "github.com/samcharles93/archie-core/internal/releaseupdate" ) +var errFixtureInstall = errors.New("build failed: exit status 1") + func TestUpdateShowsComponentSectionsAndActions(t *testing.T) { g := New("1:test", "", "", []int64{42}, slog.Default()) g.Updates = &updateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{ @@ -37,6 +42,203 @@ func TestUpdateShowsComponentSectionsAndActions(t *testing.T) { } } +// TestInstallUpdateStreamsProgressAndReportsSuccess: the phase-1 summary +// must be distinct from a final "it worked" claim -- the daemon has not +// restarted yet when this message is sent, so it can only promise that the +// build/install step succeeded and a restart is queued. +func TestInstallUpdateStreamsProgressAndReportsSuccess(t *testing.T) { + g := New("1:test", "", "", []int64{42}, slog.Default()) + stub := &updateStub{ + progressText: []string{"==> fetching", "==> building"}, + result: releaseupdate.Result{ + Previous: map[string]string{"daemon": "1.0.0", "agent": "1.0.0"}, + Installed: map[string]string{"daemon": "1.1.0", "agent": "1.0.0"}, + RestartRequested: true, + }, + } + g.Updates = stub + b, requests := newTelegramTestBot(t) + + message := &models.Message{Chat: models.Chat{ID: 7}, ID: 100, MessageThreadID: 3} + g.installUpdate(context.Background(), b, &models.CallbackQuery{ + From: models.User{ID: 42}, + Message: models.MaybeInaccessibleMessage{Message: message}, + }) + + if stub.gotMeta.Channel != "telegram" || stub.gotMeta.ChatID != 7 || stub.gotMeta.ThreadID != 3 { + t.Errorf("gotMeta = %#v, want channel/chat/thread forwarded", stub.gotMeta) + } + if len(*requests) == 0 { + t.Fatal("no requests sent") + } + last := (*requests)[len(*requests)-1] + if last.method != "editMessageText" { + t.Fatalf("last request method = %q, want editMessageText", last.method) + } + text := last.form["text"] + for _, want := range []string{"1.0.0 → 1.1.0", "restart queued", "healthy"} { + if !strings.Contains(strings.ToLower(text), strings.ToLower(want)) { + t.Errorf("summary missing %q: %q", want, text) + } + } +} + +// TestInstallUpdateReportsBuildFailureWithoutClaimingRestart: a failure +// during build/install must say nothing was restarted -- that's true only +// because the reference script never reaches the restart step on a +// non-zero exit. +func TestInstallUpdateReportsBuildFailureWithoutClaimingRestart(t *testing.T) { + g := New("1:test", "", "", []int64{42}, slog.Default()) + stub := &updateStub{installErr: errFixtureInstall} + g.Updates = stub + b, requests := newTelegramTestBot(t) + + message := &models.Message{Chat: models.Chat{ID: 7}, ID: 100} + g.installUpdate(context.Background(), b, &models.CallbackQuery{ + From: models.User{ID: 42}, + Message: models.MaybeInaccessibleMessage{Message: message}, + }) + + last := (*requests)[len(*requests)-1] + text := strings.ToLower(last.form["text"]) + if !strings.Contains(text, "failed") { + t.Errorf("summary missing failure notice: %q", text) + } + if strings.Contains(text, "restart queued") { + t.Errorf("summary falsely claims a restart was queued: %q", text) + } +} + +// TestReportPendingUpdateSendsAndClearsReport: this is the phase-2 side of +// the two-phase update report -- called on every gateway launch (process +// boot and /restart alike), it must relay whatever the update watchdog +// decided and never report the same outcome twice. +func TestReportPendingUpdateSendsAndClearsReport(t *testing.T) { + path := filepath.Join(t.TempDir(), "update-report.json") + report := releaseupdate.Report{ + Channel: "telegram", ChatID: 7, ThreadID: 3, + Previous: map[string]string{"daemon": "1.0.0"}, Installed: map[string]string{"daemon": "1.1.0"}, + HealthCheck: "passed", + } + if err := releaseupdate.WritePendingReport(path, report); err != nil { + t.Fatal(err) + } + g := New("1:test", "", "", []int64{42}, slog.Default()) + g.UpdateReportPath = path + b, requests := newTelegramTestBot(t) + + g.reportPendingUpdate(context.Background(), b) + + if len(*requests) != 1 { + t.Fatalf("requests = %#v, want exactly one", *requests) + } + if got := (*requests)[0].form["chat_id"]; got != "7" { + t.Errorf("chat_id = %q, want 7", got) + } + if _, found, err := releaseupdate.ReadPendingReport(path); err != nil || found { + t.Errorf("report still present after reportPendingUpdate: found=%v err=%v", found, err) + } +} + +// TestReportPendingUpdateClearsUnreadableReport: a corrupt report file +// (partial write, disk issue, a future format the running binary doesn't +// understand) must not jam forever -- without clearing it, every future +// launch would retry, fail identically, and the chat that approved the +// update would never learn any outcome at all. +func TestReportPendingUpdateClearsUnreadableReport(t *testing.T) { + path := filepath.Join(t.TempDir(), "update-report.json") + if err := os.WriteFile(path, []byte("{not valid json"), 0o600); err != nil { + t.Fatal(err) + } + g := New("1:test", "", "", []int64{42}, slog.Default()) + g.UpdateReportPath = path + b, _ := newTelegramTestBot(t) + + g.reportPendingUpdate(context.Background(), b) + + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("corrupt report file still exists after reportPendingUpdate: err = %v", err) + } +} + +func TestReportPendingUpdateNoFileIsNoop(t *testing.T) { + g := New("1:test", "", "", []int64{42}, slog.Default()) + g.UpdateReportPath = filepath.Join(t.TempDir(), "does-not-exist.json") + b, requests := newTelegramTestBot(t) + + g.reportPendingUpdate(context.Background(), b) + + if len(*requests) != 0 { + t.Fatalf("requests = %#v, want none", *requests) + } +} + +func TestReportPendingUpdateDisabledWhenPathEmpty(t *testing.T) { + g := New("1:test", "", "", []int64{42}, slog.Default()) + b, requests := newTelegramTestBot(t) + + g.reportPendingUpdate(context.Background(), b) + + if len(*requests) != 0 { + t.Fatalf("requests = %#v, want none", *requests) + } +} + +func TestFormatPendingReportDescribesSuccessAndRollback(t *testing.T) { + success := releaseupdate.Report{ + Previous: map[string]string{"daemon": "1.0.0"}, + Installed: map[string]string{"daemon": "1.1.0"}, + HealthCheck: "passed", + RolledBack: false, + } + text := formatPendingReport(success) + for _, want := range []string{"1.0.0 → 1.1.0", "healthy"} { + if !strings.Contains(strings.ToLower(text), strings.ToLower(want)) { + t.Errorf("success report missing %q: %q", want, text) + } + } + + failure := releaseupdate.Report{ + Previous: map[string]string{"daemon": "1.0.0"}, + Installed: map[string]string{"daemon": "1.1.0"}, + HealthCheck: "failed", + RolledBack: true, + } + text = formatPendingReport(failure) + for _, want := range []string{"rolled back", "1.0.0"} { + if !strings.Contains(strings.ToLower(text), strings.ToLower(want)) { + t.Errorf("rollback report missing %q: %q", want, text) + } + } +} + +// TestFormatPendingReportDistinguishesUnrolledBackFailure: a failed health +// check with no backup to restore from must never read like the success or +// rolled-back cases -- the daemon may still be running the broken version, +// or may not be running at all, and nothing further will fix that +// automatically. Reporting this the same as a successful rollback is worse +// than reporting nothing, because it tells the operator to stand down. +func TestFormatPendingReportDistinguishesUnrolledBackFailure(t *testing.T) { + notRolledBack := releaseupdate.Report{ + Previous: map[string]string{"daemon": "1.0.0"}, + Installed: map[string]string{"daemon": "1.1.0"}, + HealthCheck: "failed", + RolledBack: false, + } + text := strings.ToLower(formatPendingReport(notRolledBack)) + if strings.Contains(text, "was automatically rolled back") { + t.Errorf("report falsely claims a rollback happened: %q", text) + } + if strings.Contains(text, "running normally") { + t.Errorf("report falsely claims the system is healthy: %q", text) + } + for _, want := range []string{"could not", "manual"} { + if !strings.Contains(text, want) { + t.Errorf("report missing %q (must call out that manual intervention is needed): %q", want, text) + } + } +} + func TestUpdateCallbackRejectsUnauthorizedSender(t *testing.T) { g := New("1:test", "", "", []int64{42}, slog.Default()) g.Updates = &updateStub{} @@ -61,15 +263,25 @@ func TestUpdateCallbackRejectsUnauthorizedSender(t *testing.T) { type updateStub struct { snapshot releaseupdate.Snapshot installCalls int + gotMeta releaseupdate.InstallMeta + result releaseupdate.Result + installErr error + progressText []string } func (s *updateStub) Check(context.Context, int64) (releaseupdate.Snapshot, error) { return s.snapshot, nil } func (s *updateStub) Defer(context.Context, int64, releaseupdate.Snapshot) error { return nil } -func (s *updateStub) Install(_ context.Context, progress func(string)) error { +func (s *updateStub) Install(_ context.Context, meta releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) { s.installCalls++ - progress("Update started.") - return nil + s.gotMeta = meta + for _, line := range s.progressText { + progress(line) + } + if s.installErr != nil { + return releaseupdate.Result{}, s.installErr + } + return s.result, nil } func (*updateStub) CanInstall() bool { return true } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index d2d0ccf63..68683f4b8 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -152,7 +152,7 @@ type ProviderDisplayNamer interface { type UpdateService interface { Check(context.Context, int64) (releaseupdate.Snapshot, error) Defer(context.Context, int64, releaseupdate.Snapshot) error - Install(context.Context, func(string)) error + Install(context.Context, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) CanInstall() bool } diff --git a/internal/gateway/web_parity_test.go b/internal/gateway/web_parity_test.go index 9e73c1003..390a46ce2 100644 --- a/internal/gateway/web_parity_test.go +++ b/internal/gateway/web_parity_test.go @@ -14,8 +14,10 @@ func (parityUpdateStub) Check(context.Context, int64) (releaseupdate.Snapshot, e return releaseupdate.Snapshot{Components: []releaseupdate.Component{{ID: "gateway", Label: "THE GATEWAY", Installed: "v1", Available: "v2"}}}, nil } func (parityUpdateStub) Defer(context.Context, int64, releaseupdate.Snapshot) error { return nil } -func (parityUpdateStub) Install(context.Context, func(string)) error { return nil } -func (parityUpdateStub) CanInstall() bool { return true } +func (parityUpdateStub) Install(context.Context, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) { + return releaseupdate.Result{}, nil +} +func (parityUpdateStub) CanInstall() bool { return true } type parityDangerousStub struct{ decisions []string } diff --git a/internal/releaseupdate/command.go b/internal/releaseupdate/command.go index 49dcfb5f3..11ac56634 100644 --- a/internal/releaseupdate/command.go +++ b/internal/releaseupdate/command.go @@ -1,12 +1,21 @@ package releaseupdate import ( + "bufio" + "bytes" "context" "encoding/json" "fmt" "os/exec" + "strconv" + "strings" ) +// updateResultSentinel prefixes the one line an install command may print to +// report its structured Result. Every other line is forwarded to progress +// as-is. +const updateResultSentinel = "ARCHIE_UPDATE_RESULT " + // CommandCatalog reads a Snapshot JSON document from an explicitly configured // argv command. It never invokes a shell; deployment tooling remains an // administrator-owned adapter. @@ -29,13 +38,58 @@ func (c CommandCatalog) Check(ctx context.Context) (Snapshot, error) { type CommandInstaller struct{ Command []string } -func (i CommandInstaller) Install(ctx context.Context, progress func(string)) error { +// Install runs the configured command and streams its stdout to progress +// line by line as the command emits it -- the earlier CombinedOutput-based +// version buffered everything until exit, so callers saw nothing until the +// whole update either finished or failed. One stdout line may be a +// structured Result instead of prose; see updateResultSentinel. +func (i CommandInstaller) Install(ctx context.Context, meta InstallMeta, progress func(string)) (Result, error) { if len(i.Command) == 0 { - return fmt.Errorf("update install command is empty") + return Result{}, fmt.Errorf("update install command is empty") } - progress("Installing approved update…") - if output, err := exec.CommandContext(ctx, i.Command[0], i.Command[1:]...).CombinedOutput(); err != nil { - return fmt.Errorf("run update installer: %w: %s", err, string(output)) + cmd := exec.CommandContext(ctx, i.Command[0], i.Command[1:]...) + cmd.Env = append(cmd.Environ(), + "ARCHIE_UPDATE_CHANNEL="+meta.Channel, + "ARCHIE_UPDATE_CHAT_ID="+strconv.FormatInt(meta.ChatID, 10), + "ARCHIE_UPDATE_THREAD_ID="+strconv.Itoa(meta.ThreadID), + "ARCHIE_UPDATE_REPORT_PATH="+meta.ReportPath, + ) + + stdout, err := cmd.StdoutPipe() + if err != nil { + return Result{}, fmt.Errorf("open update installer stdout: %w", err) } - return nil + var stderr bytes.Buffer + cmd.Stderr = &stderr + + if err := cmd.Start(); err != nil { + return Result{}, fmt.Errorf("start update installer: %w", err) + } + + var result Result + var resultErr error + scanner := bufio.NewScanner(stdout) + scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024) + for scanner.Scan() { + line := scanner.Text() + if rest, ok := strings.CutPrefix(line, updateResultSentinel); ok { + if err := json.Unmarshal([]byte(rest), &result); err != nil { + resultErr = fmt.Errorf("decode update installer result: %w", err) + } + continue + } + progress(line) + } + if err := scanner.Err(); err != nil { + resultErr = fmt.Errorf("read update installer output: %w", err) + } + + waitErr := cmd.Wait() + if waitErr != nil { + return result, fmt.Errorf("run update installer: %w: %s", waitErr, stderr.String()) + } + if resultErr != nil { + return result, resultErr + } + return result, nil } diff --git a/internal/releaseupdate/command_test.go b/internal/releaseupdate/command_test.go new file mode 100644 index 000000000..303c17936 --- /dev/null +++ b/internal/releaseupdate/command_test.go @@ -0,0 +1,134 @@ +package releaseupdate + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +// writeFixtureScript creates an executable shell script and returns its path. +func writeFixtureScript(t *testing.T, body string) string { + t.Helper() + dir := t.TempDir() + path := filepath.Join(dir, "fixture.sh") + script := "#!/usr/bin/env bash\nset -euo pipefail\n" + body + if err := os.WriteFile(path, []byte(script), 0o755); err != nil { + t.Fatalf("write fixture script: %v", err) + } + return path +} + +// TestCommandInstallerStreamsProgressLive confirms every stdout line the +// script prints reaches progress() as it is emitted, not buffered until the +// process exits -- this is the difference between silent-until-done and +// live status. +func TestCommandInstallerStreamsProgressLive(t *testing.T) { + script := writeFixtureScript(t, ` +echo "==> fetching" +echo "==> building" +echo 'ARCHIE_UPDATE_RESULT {"previous":{"daemon":"1.0.0"},"installed":{"daemon":"1.1.0"},"components":[{"id":"daemon","label":"daemon","status":"updated"}],"restart_requested":true}' +`) + installer := CommandInstaller{Command: []string{script}} + var progress []string + result, err := installer.Install(context.Background(), InstallMeta{}, func(line string) { progress = append(progress, line) }) + if err != nil { + t.Fatalf("Install() error = %v", err) + } + if len(progress) != 2 || progress[0] != "==> fetching" || progress[1] != "==> building" { + t.Fatalf("progress = %#v, want the two stage lines (sentinel excluded)", progress) + } + if result.Previous["daemon"] != "1.0.0" || result.Installed["daemon"] != "1.1.0" { + t.Fatalf("result versions = %#v", result) + } + if len(result.Components) != 1 || result.Components[0].Status != "updated" { + t.Fatalf("result components = %#v", result.Components) + } + if !result.RestartRequested { + t.Error("RestartRequested = false, want true") + } +} + +// TestCommandInstallerMissingSentinelReturnsEmptyResult: a script that never +// prints the sentinel line (e.g. an operator's older custom script) must not +// crash the parse -- it just reports nothing structured, and progress lines +// are still delivered. +func TestCommandInstallerMissingSentinelReturnsEmptyResult(t *testing.T) { + script := writeFixtureScript(t, `echo "==> done, no sentinel"`) + installer := CommandInstaller{Command: []string{script}} + var progress []string + result, err := installer.Install(context.Background(), InstallMeta{}, func(line string) { progress = append(progress, line) }) + if err != nil { + t.Fatalf("Install() error = %v", err) + } + if len(progress) != 1 || progress[0] != "==> done, no sentinel" { + t.Fatalf("progress = %#v", progress) + } + if result.Previous != nil || result.Installed != nil || result.Components != nil { + t.Fatalf("result = %#v, want zero value", result) + } +} + +// TestCommandInstallerMalformedSentinelReturnsError: a sentinel line present +// but with invalid JSON is a script bug -- it must surface as an error +// rather than silently reporting an empty (and therefore misleadingly +// "nothing changed") result. +func TestCommandInstallerMalformedSentinelReturnsError(t *testing.T) { + script := writeFixtureScript(t, `echo 'ARCHIE_UPDATE_RESULT {not valid json}'`) + installer := CommandInstaller{Command: []string{script}} + _, err := installer.Install(context.Background(), InstallMeta{}, func(string) {}) + if err == nil { + t.Fatal("Install() error = nil, want a decode error") + } +} + +// TestCommandInstallerNonZeroExitReturnsPartialResultAndError: a script that +// fails partway through should still surface whatever progress and result it +// managed to emit before failing, alongside the error -- callers need to +// know how far the update got. +func TestCommandInstallerNonZeroExitReturnsPartialResultAndError(t *testing.T) { + script := writeFixtureScript(t, ` +echo "==> fetching" +echo "build failed" >&2 +exit 1 +`) + installer := CommandInstaller{Command: []string{script}} + var progress []string + _, err := installer.Install(context.Background(), InstallMeta{}, func(line string) { progress = append(progress, line) }) + if err == nil { + t.Fatal("Install() error = nil, want non-zero exit error") + } + if !strings.Contains(err.Error(), "build failed") { + t.Errorf("error = %v, want it to include stderr", err) + } + if len(progress) != 1 || progress[0] != "==> fetching" { + t.Fatalf("progress = %#v, want the line emitted before failure", progress) + } +} + +// TestCommandInstallerForwardsMetaAsEnv: the script needs to know who to +// report back to once the daemon restarts, since the process that requested +// the update is not the process that observes the restart succeeding. +func TestCommandInstallerForwardsMetaAsEnv(t *testing.T) { + script := writeFixtureScript(t, ` +echo "channel=$ARCHIE_UPDATE_CHANNEL chat=$ARCHIE_UPDATE_CHAT_ID thread=$ARCHIE_UPDATE_THREAD_ID report=$ARCHIE_UPDATE_REPORT_PATH" +`) + installer := CommandInstaller{Command: []string{script}} + meta := InstallMeta{Channel: "telegram", ChatID: 123, ThreadID: 7, ReportPath: "/var/lib/archie/update-report.json"} + var progress []string + if _, err := installer.Install(context.Background(), meta, func(line string) { progress = append(progress, line) }); err != nil { + t.Fatalf("Install() error = %v", err) + } + want := "channel=telegram chat=123 thread=7 report=/var/lib/archie/update-report.json" + if len(progress) != 1 || progress[0] != want { + t.Fatalf("progress = %#v, want [%q]", progress, want) + } +} + +func TestCommandInstallerEmptyCommandReturnsError(t *testing.T) { + installer := CommandInstaller{} + if _, err := installer.Install(context.Background(), InstallMeta{}, func(string) {}); err == nil { + t.Fatal("Install() error = nil, want empty-command error") + } +} diff --git a/internal/releaseupdate/pending_report.go b/internal/releaseupdate/pending_report.go new file mode 100644 index 000000000..0bbabe2fe --- /dev/null +++ b/internal/releaseupdate/pending_report.go @@ -0,0 +1,76 @@ +package releaseupdate + +import ( + "encoding/json" + "errors" + "fmt" + "os" +) + +// Report is the phase-2 outcome of an update: whether the daemon came back +// up healthy after restarting, written by whichever process determined that +// (the deployment's restart/health-check tooling) and read, relayed to +// Channel/ChatID/ThreadID, and cleared by whichever archied process boots +// next -- which may be the newly installed version (success) or the +// previous one, if a crash-loop forced a rollback before this code could +// ever run on the new version. +type Report struct { + Channel string `json:"channel"` + ChatID int64 `json:"chat_id"` + ThreadID int `json:"thread_id"` + Previous map[string]string `json:"previous"` + Installed map[string]string `json:"installed"` + HealthCheck string `json:"health_check"` // "passed" or "failed" + RolledBack bool `json:"rolled_back"` +} + +func (r Report) validate() error { + if r.RolledBack && r.HealthCheck != "failed" { + return errors.New("update report: rolled_back requires health_check to be \"failed\"") + } + return nil +} + +// WritePendingReport persists r to path atomically, the same way +// saveDeferrals does. +func WritePendingReport(path string, r Report) error { + if err := r.validate(); err != nil { + return err + } + data, err := json.Marshal(r) + if err != nil { + return fmt.Errorf("encode update report: %w", err) + } + if err := writeFileAtomic(path, data); err != nil { + return fmt.Errorf("write update report: %w", err) + } + return nil +} + +// ReadPendingReport reads a Report previously written by WritePendingReport. +// found is false, with a nil error, when no update is in flight -- the +// common case on every normal startup. +func ReadPendingReport(path string) (Report, bool, error) { + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return Report{}, false, nil + } + if err != nil { + return Report{}, false, fmt.Errorf("read update report: %w", err) + } + var report Report + if err := json.Unmarshal(data, &report); err != nil { + return Report{}, false, fmt.Errorf("decode update report: %w", err) + } + return report, true, nil +} + +// ClearPendingReport removes a report once it has been relayed. A report +// that is already gone (cleared by a previous boot attempt) is not an +// error. +func ClearPendingReport(path string) error { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("clear update report: %w", err) + } + return nil +} diff --git a/internal/releaseupdate/pending_report_test.go b/internal/releaseupdate/pending_report_test.go new file mode 100644 index 000000000..90d007949 --- /dev/null +++ b/internal/releaseupdate/pending_report_test.go @@ -0,0 +1,80 @@ +package releaseupdate + +import ( + "os" + "path/filepath" + "testing" +) + +// TestPendingReportRoundTrip covers the cross-restart handoff: the watchdog +// script decides the phase-2 outcome and writes it; whichever archied +// process boots next reads it, relays it, and clears it so it is never +// reported twice. +func TestPendingReportRoundTrip(t *testing.T) { + path := filepath.Join(t.TempDir(), "update-report.json") + want := Report{ + Channel: "telegram", + ChatID: 42, + ThreadID: 7, + Previous: map[string]string{"daemon": "1.0.0", "agent": "1.0.0"}, + Installed: map[string]string{"daemon": "1.1.0", "agent": "1.0.0"}, + HealthCheck: "passed", + RolledBack: false, + } + + if err := WritePendingReport(path, want); err != nil { + t.Fatalf("WritePendingReport() error = %v", err) + } + + got, found, err := ReadPendingReport(path) + if err != nil { + t.Fatalf("ReadPendingReport() error = %v", err) + } + if !found { + t.Fatal("ReadPendingReport() found = false, want true") + } + if got.Channel != want.Channel || got.ChatID != want.ChatID || got.ThreadID != want.ThreadID || + got.HealthCheck != want.HealthCheck || got.RolledBack != want.RolledBack || + got.Installed["daemon"] != want.Installed["daemon"] || got.Previous["daemon"] != want.Previous["daemon"] { + t.Fatalf("ReadPendingReport() = %#v, want %#v", got, want) + } + + if err := ClearPendingReport(path); err != nil { + t.Fatalf("ClearPendingReport() error = %v", err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("report file still exists after ClearPendingReport(): err = %v", err) + } +} + +// TestReadPendingReportMissingFileReturnsNotFound: no update in flight is +// the overwhelmingly common case (every normal startup), so it must be a +// plain "not found", never an error a caller has to specially ignore. +func TestReadPendingReportMissingFileReturnsNotFound(t *testing.T) { + path := filepath.Join(t.TempDir(), "does-not-exist.json") + _, found, err := ReadPendingReport(path) + if err != nil { + t.Fatalf("ReadPendingReport() error = %v, want nil", err) + } + if found { + t.Fatal("ReadPendingReport() found = true, want false") + } +} + +// TestClearPendingReportMissingFileIsNotAnError: startup may race a report +// that was already cleared by a previous boot attempt; clearing twice must +// be harmless. +func TestClearPendingReportMissingFileIsNotAnError(t *testing.T) { + path := filepath.Join(t.TempDir(), "does-not-exist.json") + if err := ClearPendingReport(path); err != nil { + t.Fatalf("ClearPendingReport() error = %v, want nil for a missing file", err) + } +} + +func TestWritePendingReportRejectsRolledBackWithoutHealthCheckFailure(t *testing.T) { + path := filepath.Join(t.TempDir(), "update-report.json") + bad := Report{Channel: "telegram", ChatID: 1, RolledBack: true, HealthCheck: "passed"} + if err := WritePendingReport(path, bad); err == nil { + t.Fatal("WritePendingReport() error = nil, want a validation error for rolled_back+passed") + } +} diff --git a/internal/releaseupdate/result.go b/internal/releaseupdate/result.go new file mode 100644 index 000000000..e70307269 --- /dev/null +++ b/internal/releaseupdate/result.go @@ -0,0 +1,37 @@ +package releaseupdate + +// InstallMeta identifies who to notify once an installed update finishes +// restarting. The process that calls Install returns before the daemon +// actually restarts (the reference installer queues the restart through a +// detached unit so restarting archied.service doesn't kill the installer +// mid-run), so this identity has to survive the restart on disk -- see +// Report and WritePendingReport. +type InstallMeta struct { + Channel string + ChatID int64 + ThreadID int + // ReportPath is where the installer's restart/health-check tooling + // should write the phase-2 Report once it knows the outcome -- see + // WritePendingReport. Empty means the deployment has no phase-2 + // reporting configured (the caller only gets the synchronous Result). + ReportPath string +} + +// ComponentResult reports what an installer actually did to one component. +type ComponentResult struct { + ID string `json:"id"` + Label string `json:"label"` + Status string `json:"status"` // "updated", "unchanged", or "failed" +} + +// Result is the structured outcome of the synchronous phase of an install: +// fetch/build/install, before any restart happens. Previous and Installed +// map a component ID to its version. Field names are snake_case in JSON to +// match the install script's ARCHIE_UPDATE_RESULT sentinel line -- see +// command.go and scripts/archie-update-install. +type Result struct { + Previous map[string]string `json:"previous"` + Installed map[string]string `json:"installed"` + Components []ComponentResult `json:"components"` + RestartRequested bool `json:"restart_requested"` +} diff --git a/internal/releaseupdate/service.go b/internal/releaseupdate/service.go index 31919e068..3162cd14f 100644 --- a/internal/releaseupdate/service.go +++ b/internal/releaseupdate/service.go @@ -11,6 +11,7 @@ import ( "path/filepath" "strconv" "sync" + "time" "github.com/samcharles93/archie-core/internal/installtype" ) @@ -24,8 +25,11 @@ type Catalog interface { // Installer applies an approved update. It reports only work it has actually // started; callers remain responsible for telling users the final result. +// The returned Result covers only the synchronous phase (fetch/build/ +// install) -- whether a subsequent restart actually came up healthy is +// reported later, out of band, via a Report (see pending_report.go). type Installer interface { - Install(context.Context, func(string)) error + Install(context.Context, InstallMeta, func(string)) (Result, error) } type Component struct { @@ -87,7 +91,8 @@ type Service struct { // process-wide state. InstallType string - mu sync.Mutex + mu sync.Mutex + installing bool } func (s *Service) Check(ctx context.Context, recipient int64) (Snapshot, error) { @@ -156,14 +161,53 @@ func (s *Service) Defer(ctx context.Context, recipient int64, expected Snapshot) // instance was actually deployed. var ErrUnknownInstallType = errors.New("refusing to install: install type is unknown") -func (s *Service) Install(ctx context.Context, progress func(string)) error { +// ErrInstallInProgress is returned by Install when another install is +// already running. Telegram and the web dashboard each keep their own +// local "already in progress" flag for a quick UI response, but both are +// wired to the same Service in production -- this is the one guard that +// actually sees both, since a caller-local bool would let one adapter start +// a second install while the other's is still copying binaries. +var ErrInstallInProgress = errors.New("an update is already in progress") + +// installTimeout bounds an install after it has been deliberately detached +// from the caller's context (see below) -- otherwise a hung installer +// script would hold the in-progress lock forever. +const installTimeout = 30 * time.Minute + +// Install runs the configured Installer. The context it hands the +// Installer is intentionally NOT ctx: ctx belongs to whatever triggered the +// update (a chat message handler cancelled by /restart, an HTTP request +// cancelled by a client disconnect), and exec.CommandContext SIGKILLs its +// child the instant that context is cancelled. The install script backs up +// and overwrites the live binaries with plain, non-atomic copies -- a kill +// mid-copy can leave the daemon unable to start, with the one thing that +// could roll that back (the watchdog) never launched because the script +// never reached that line. Detaching the install from ctx, bounded by +// installTimeout instead, is what actually makes the caller's own +// lifecycle safe to interrupt without corrupting an in-flight update. +func (s *Service) Install(ctx context.Context, meta InstallMeta, progress func(string)) (Result, error) { if s == nil || s.Installer == nil { - return errors.New("update installation is not configured") + return Result{}, errors.New("update installation is not configured") } if s.InstallType == "" || s.InstallType == installtype.Unknown { - return ErrUnknownInstallType + return Result{}, ErrUnknownInstallType } - return s.Installer.Install(ctx, progress) + s.mu.Lock() + if s.installing { + s.mu.Unlock() + return Result{}, ErrInstallInProgress + } + s.installing = true + s.mu.Unlock() + defer func() { + s.mu.Lock() + s.installing = false + s.mu.Unlock() + }() + + installCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), installTimeout) + defer cancel() + return s.Installer.Install(installCtx, meta, progress) } func (s *Service) CanInstall() bool { return s != nil && s.Installer != nil } @@ -186,32 +230,46 @@ func loadDeferrals(path string) (deferrals, error) { } func saveDeferrals(path string, state deferrals) error { - if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { - return fmt.Errorf("create update state directory: %w", err) - } - file, err := os.CreateTemp(filepath.Dir(path), ".update-deferrals-*") + data, err := json.Marshal(state) if err != nil { - return fmt.Errorf("create update state: %w", err) + return fmt.Errorf("encode update deferrals: %w", err) + } + return writeFileAtomic(path, data) +} + +// writeFileAtomic writes data to path via a temp file in the same +// directory, synced and renamed into place, so a reader never observes a +// partially written file. Shared by saveDeferrals and WritePendingReport -- +// both are small JSON state files under the same operational directory +// (cfg.WorkDir) with the same durability requirement. +func writeFileAtomic(path string, data []byte) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create state directory: %w", err) + } + file, err := os.CreateTemp(dir, ".update-state-*") + if err != nil { + return fmt.Errorf("create temp state file: %w", err) } tempPath := file.Name() defer func() { _ = os.Remove(tempPath) }() if err := file.Chmod(0o600); err != nil { _ = file.Close() - return fmt.Errorf("protect update state: %w", err) + return fmt.Errorf("protect state file: %w", err) } - if err := json.NewEncoder(file).Encode(state); err != nil { + if _, err := file.Write(data); err != nil { _ = file.Close() - return fmt.Errorf("encode update deferrals: %w", err) + return fmt.Errorf("write state file: %w", err) } if err := file.Sync(); err != nil { _ = file.Close() - return fmt.Errorf("sync update deferrals: %w", err) + return fmt.Errorf("sync state file: %w", err) } if err := file.Close(); err != nil { - return fmt.Errorf("close update state: %w", err) + return fmt.Errorf("close state file: %w", err) } if err := os.Rename(tempPath, path); err != nil { - return fmt.Errorf("replace update state: %w", err) + return fmt.Errorf("replace state file: %w", err) } return nil } diff --git a/internal/releaseupdate/service_test.go b/internal/releaseupdate/service_test.go index 629bbb862..cb6097758 100644 --- a/internal/releaseupdate/service_test.go +++ b/internal/releaseupdate/service_test.go @@ -2,9 +2,11 @@ package releaseupdate import ( "context" + "errors" "path/filepath" "strings" "testing" + "time" "github.com/samcharles93/archie-core/internal/installtype" ) @@ -52,15 +54,23 @@ func TestServiceInstallForwardsProgressAndFailure(t *testing.T) { installer := &installerStub{} service := Service{Installer: installer, InstallType: "binary"} var progress []string - if err := service.Install(context.Background(), func(message string) { progress = append(progress, message) }); err != nil { + meta := InstallMeta{Channel: "telegram", ChatID: 42} + result, err := service.Install(context.Background(), meta, func(message string) { progress = append(progress, message) }) + if err != nil { t.Fatal(err) } if !installer.called { t.Error("installer was not called") } + if installer.gotMeta != meta { + t.Errorf("installer received meta = %#v, want %#v", installer.gotMeta, meta) + } if len(progress) != 1 || progress[0] != "Pulling release..." { t.Errorf("progress = %#v", progress) } + if result.Installed["daemon"] != "1.1.0" { + t.Errorf("result = %#v", result) + } } // TestServiceInstallRefusesAnUnknownInstallType is the fail-closed guarantee @@ -82,7 +92,7 @@ func TestServiceInstallRefusesAnUnknownInstallType(t *testing.T) { installer := &installerStub{} service := Service{Installer: installer, InstallType: tt.installType} - err := service.Install(context.Background(), func(string) {}) + _, err := service.Install(context.Background(), InstallMeta{}, func(string) {}) if err == nil { t.Fatal("Install() returned nil error, want a refusal") @@ -94,6 +104,68 @@ func TestServiceInstallRefusesAnUnknownInstallType(t *testing.T) { } } +// TestServiceInstallSurvivesCallerContextCancellation: the caller's context +// belongs to the request/handler that triggered the update (a Telegram +// message handler cancelled by /restart, or an HTTP request cancelled by a +// client disconnect) -- it must not reach into the install child process. +// Killing that process mid-run can leave binaries half-overwritten with no +// rollback ever attempted, which is exactly the failure mode this feature +// exists to prevent. +func TestServiceInstallSurvivesCallerContextCancellation(t *testing.T) { + installer := &blockingInstallerStub{unblock: make(chan struct{}), started: make(chan struct{})} + service := Service{Installer: installer, InstallType: "binary"} + ctx, cancel := context.WithCancel(context.Background()) + + done := make(chan error, 1) + go func() { + _, err := service.Install(ctx, InstallMeta{}, func(string) {}) + done <- err + }() + + <-installer.started + cancel() // simulate the triggering request/handler being torn down mid-install + + select { + case <-installer.gotCancelled: + t.Fatal("installer observed its context as cancelled after only the caller's context was cancelled") + case <-time.After(50 * time.Millisecond): + } + close(installer.unblock) + + if err := <-done; err != nil { + t.Fatalf("Install() error = %v, want nil", err) + } +} + +// TestServiceInstallRefusesConcurrentInstalls: Telegram and the web +// dashboard are two different callers of the same Service, each with its +// own local "already in progress" flag -- neither knows about the other. +// The authoritative guard against two installs racing the same binaries +// and .prev backups has to live here, not duplicated per caller. +func TestServiceInstallRefusesConcurrentInstalls(t *testing.T) { + installer := &blockingInstallerStub{unblock: make(chan struct{}), started: make(chan struct{})} + service := Service{Installer: installer, InstallType: "binary"} + + done := make(chan error, 1) + go func() { + _, err := service.Install(context.Background(), InstallMeta{}, func(string) {}) + done <- err + }() + <-installer.started + + if _, err := service.Install(context.Background(), InstallMeta{}, func(string) {}); !errors.Is(err, ErrInstallInProgress) { + t.Fatalf("second Install() error = %v, want ErrInstallInProgress", err) + } + + close(installer.unblock) + if err := <-done; err != nil { + t.Fatalf("first Install() error = %v, want nil", err) + } + if installer.calls != 1 { + t.Fatalf("installer.calls = %d, want exactly 1", installer.calls) + } +} + func TestNilServiceReturnsConfigurationErrors(t *testing.T) { var service *Service @@ -103,7 +175,7 @@ func TestNilServiceReturnsConfigurationErrors(t *testing.T) { if err := service.Defer(context.Background(), 0, Snapshot{}); err == nil { t.Fatal("nil service defer returned nil error") } - if err := service.Install(context.Background(), nil); err == nil { + if _, err := service.Install(context.Background(), InstallMeta{}, nil); err == nil { t.Fatal("nil service install returned nil error") } if service.CanInstall() { @@ -139,10 +211,38 @@ type catalogStub struct{ snapshot Snapshot } func (s *catalogStub) Check(context.Context) (Snapshot, error) { return s.snapshot, nil } -type installerStub struct{ called bool } +// blockingInstallerStub lets a test hold Install() open until it chooses to +// release it, and records whether the context it was given ever reported +// cancellation. +type blockingInstallerStub struct { + unblock chan struct{} + started chan struct{} + gotCancelled chan struct{} + calls int +} -func (s *installerStub) Install(_ context.Context, progress func(string)) error { +func (s *blockingInstallerStub) Install(ctx context.Context, _ InstallMeta, _ func(string)) (Result, error) { + s.calls++ + close(s.started) + if s.gotCancelled == nil { + s.gotCancelled = make(chan struct{}) + } + go func() { + <-ctx.Done() + close(s.gotCancelled) + }() + <-s.unblock + return Result{}, nil +} + +type installerStub struct { + called bool + gotMeta InstallMeta +} + +func (s *installerStub) Install(_ context.Context, meta InstallMeta, progress func(string)) (Result, error) { s.called = true + s.gotMeta = meta progress("Pulling release...") - return nil + return Result{Installed: map[string]string{"daemon": "1.1.0"}}, nil } diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index cb493ba7f..187a2b48f 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -35,7 +35,7 @@ type ChatService struct { type ChatUpdateService interface { Check(context.Context, int64) (releaseupdate.Snapshot, error) Defer(context.Context, int64, releaseupdate.Snapshot) error - Install(context.Context, func(string)) error + Install(context.Context, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) CanInstall() bool } @@ -494,12 +494,12 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request) }() progress := make([]string, 0, 4) - err = chat.Updates.Install(r.Context(), func(message string) { progress = append(progress, message) }) + result, err := chat.Updates.Install(r.Context(), releaseupdate.InstallMeta{Channel: "webui"}, func(message string) { progress = append(progress, message) }) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } - writeJSON(w, map[string]any{"ok": true, "progress": progress}) + writeJSON(w, map[string]any{"ok": true, "progress": progress, "result": result}) } func (s *Server) handleChatDangerousState(w http.ResponseWriter, r *http.Request) { diff --git a/internal/webui/api_chat_test.go b/internal/webui/api_chat_test.go index e812df51b..c0d19ed3f 100644 --- a/internal/webui/api_chat_test.go +++ b/internal/webui/api_chat_test.go @@ -90,10 +90,10 @@ func (s *chatUpdateStub) Defer(_ context.Context, _ int64, snapshot releaseupdat return nil } -func (s *chatUpdateStub) Install(_ context.Context, progress func(string)) error { +func (s *chatUpdateStub) Install(_ context.Context, _ releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) { s.installed = true progress("install started") - return nil + return releaseupdate.Result{}, nil } func (*chatUpdateStub) CanInstall() bool { return true } diff --git a/internal/webui/server.go b/internal/webui/server.go index 2eeff0a68..f3fae9bb5 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -208,7 +208,22 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("POST /api/chat/dangerous/{id}/decision", s.handleChatDangerousDecision) mux.HandleFunc("GET /events", s.handleSSE) mux.Handle("GET /", s.assets()) - return s.requireToken(mux) + + top := http.NewServeMux() + top.HandleFunc("GET /healthz", s.handleHealthz) + top.Handle("/", s.requireToken(mux)) + return top +} + +// handleHealthz is a liveness probe for local, unauthenticated callers -- +// most notably the update watchdog script, which polls it after restarting +// archied to decide whether the new version came up or the update needs to +// be rolled back (see scripts/archie-update-watchdog). It deliberately +// bypasses requireToken: the token protects the dashboard from remote +// access, not this process's own local restart tooling. +func (s *Server) handleHealthz(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok")) } // assets serves the embedded dashboard, falling back to index.html so client diff --git a/internal/webui/webui_test.go b/internal/webui/webui_test.go index c38a05e5e..e4468e606 100644 --- a/internal/webui/webui_test.go +++ b/internal/webui/webui_test.go @@ -274,6 +274,21 @@ func TestHandleIndex(t *testing.T) { } } +// TestHealthzIsReachableWithoutAToken: the update watchdog script polls +// this endpoint from the local host after restarting archied, with no +// dashboard session -- it must never require the dashboard token, unlike +// every other route. +func TestHealthzIsReachableWithoutAToken(t *testing.T) { + srv := newTestServer(t) + srv.Token = "dashboard-secret" + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/healthz", nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %q", w.Code, w.Body.String()) + } +} + // TestHandleSSEEventsSinceError proves that handleSSE does not silently // discard an error from EventsSince. Today the handler has no else // branch for err != nil, so the error is swallowed and the client diff --git a/scripts/archie-update-install b/scripts/archie-update-install old mode 100644 new mode 100755 index 2aa44f03a..f6fa868cf --- a/scripts/archie-update-install +++ b/scripts/archie-update-install @@ -2,20 +2,36 @@ # archie-update-install -- update installation adapter for archied's /update. # # archied runs this via CommandInstaller after the operator approves, and -# captures CombinedOutput, so everything printed here reaches the chat on -# failure. It is exec'd directly, without a shell. +# streams stdout to the chat live as each line is printed. The final line is +# a single "ARCHIE_UPDATE_RESULT {json}" the Go side parses to report which +# components changed; every other line is shown as plain progress text. It +# is exec'd directly, without a shell. # -# The restart is queued through a separate transient systemd unit. The -# installer is a child of archied.service; restarting that unit directly -# would make systemd kill this process before CommandInstaller can observe a -# successful exit. +# This script only covers the synchronous phase: fetch, build, install, +# rebuild the agent image. Nothing here restarts archied directly -- that is +# handed off to archie-update-watchdog, launched detached via systemd-run so +# restarting archied.service doesn't kill this process before it can report +# a clean exit. The watchdog is also the only place a crash-loop on the new +# binary gets detected and rolled back, since by definition no Go code can +# be running to do that itself. set -euo pipefail +# json_escape minimally escapes a string for embedding in a JSON document +# built by shell interpolation: backslashes first (so the quote-escaping +# backslash it inserts next isn't itself re-escaped), then double quotes. +json_escape() { + printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' +} + REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}" BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}" export PATH="/usr/local/go/bin:$PATH" cd "$REPO" + +PREV_GW="$(git describe --tags --match 'archied/v*' 2>/dev/null | sed 's|^archied/v||' || echo unknown)" +PREV_RT="$(git describe --tags --match 'archie/v*' 2>/dev/null | sed 's|^archie/v||' || echo unknown)" + echo "==> fetching" git pull --ff-only @@ -30,6 +46,10 @@ go build -ldflags "-X main.gatewayVersion=$GW -X main.runtimeVersion=$RT -X gith -o "$tmp/archied" ./cmd/archied go build -o "$tmp/archie-agent" ./cmd/archie-agent +echo "==> backing up current binaries" +[ -f "$BIN_DIR/archied" ] && cp -f "$BIN_DIR/archied" "$BIN_DIR/archied.prev" +[ -f "$BIN_DIR/archie-agent" ] && cp -f "$BIN_DIR/archie-agent" "$BIN_DIR/archie-agent.prev" + echo "==> installing" install -m755 "$tmp/archied" "$BIN_DIR/archied" install -m755 "$tmp/archie-agent" "$BIN_DIR/archie-agent" @@ -37,7 +57,27 @@ install -m755 "$tmp/archie-agent" "$BIN_DIR/archie-agent" echo "==> rebuilding agent image" docker compose build agent -echo "==> restarting (queued in a separate transient unit)" +echo "==> handing off to the update watchdog for restart and health verification" systemd-run --user --unit=archied-update-restart --collect --quiet \ - /usr/bin/systemctl --user restart --no-block archied.service -echo "update applied: archied $GW, archie-agent $RT" + --setenv=ARCHIE_BIN_DIR="$BIN_DIR" \ + --setenv=ARCHIE_HEALTH_URL="${ARCHIE_HEALTH_URL:-http://127.0.0.1:8420}" \ + --setenv=ARCHIE_UPDATE_REPORT_PATH="${ARCHIE_UPDATE_REPORT_PATH:-}" \ + --setenv=ARCHIE_UPDATE_CHANNEL="${ARCHIE_UPDATE_CHANNEL:-}" \ + --setenv=ARCHIE_UPDATE_CHAT_ID="${ARCHIE_UPDATE_CHAT_ID:-0}" \ + --setenv=ARCHIE_UPDATE_THREAD_ID="${ARCHIE_UPDATE_THREAD_ID:-0}" \ + --setenv=ARCHIE_UPDATE_PREVIOUS_GATEWAY="$PREV_GW" \ + --setenv=ARCHIE_UPDATE_PREVIOUS_RUNTIME="$PREV_RT" \ + --setenv=ARCHIE_UPDATE_INSTALLED_GATEWAY="$GW" \ + --setenv=ARCHIE_UPDATE_INSTALLED_RUNTIME="$RT" \ + "$REPO/scripts/archie-update-watchdog" + +daemon_status="updated" +[ "$PREV_GW" = "$GW" ] && daemon_status="unchanged" +agent_status="updated" +[ "$PREV_RT" = "$RT" ] && agent_status="unchanged" + +esc_prev_gw="$(json_escape "$PREV_GW")" +esc_prev_rt="$(json_escape "$PREV_RT")" +esc_gw="$(json_escape "$GW")" +esc_rt="$(json_escape "$RT")" +echo "ARCHIE_UPDATE_RESULT {\"previous\":{\"daemon\":\"$esc_prev_gw\",\"agent\":\"$esc_prev_rt\"},\"installed\":{\"daemon\":\"$esc_gw\",\"agent\":\"$esc_rt\"},\"components\":[{\"id\":\"daemon\",\"label\":\"daemon\",\"status\":\"$daemon_status\"},{\"id\":\"agent\",\"label\":\"agent\",\"status\":\"$agent_status\"}],\"restart_requested\":true}" diff --git a/scripts/archie-update-watchdog b/scripts/archie-update-watchdog new file mode 100755 index 000000000..cbba53f4d --- /dev/null +++ b/scripts/archie-update-watchdog @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# archie-update-watchdog -- restarts archied after an update, verifies the +# new version comes up healthy, and rolls back automatically if it doesn't. +# +# Launched detached (via systemd-run) by archie-update-install, after that +# script's own synchronous build/install work already completed and +# reported success back to chat. This script owns everything that happens +# after that point: nothing here can be observed by the Go process that +# requested the update, because restarting archied.service kills it. +# +# This is deliberately the ONLY place a crash-loop on the newly installed +# binary gets detected and rolled back -- by definition, no archied Go code +# can be running to do that itself if the new binary never gets that far. +set -uo pipefail + +BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}" +HEALTH_URL="${ARCHIE_HEALTH_URL:-http://127.0.0.1:8420}" +REPORT_PATH="${ARCHIE_UPDATE_REPORT_PATH:-}" +HEALTH_TIMEOUT_SECONDS="${ARCHIE_UPDATE_HEALTH_TIMEOUT:-60}" +POLL_INTERVAL_SECONDS=3 + +# json_escape minimally escapes a string for embedding in a JSON document +# built by shell interpolation: backslashes first (so the quote-escaping +# backslash it inserts next isn't itself re-escaped), then double quotes. +json_escape() { + printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' +} + +write_report() { + local health_check="$1" rolled_back="$2" + [ -z "$REPORT_PATH" ] && return 0 + mkdir -p "$(dirname "$REPORT_PATH")" + tmp="$(mktemp "$(dirname "$REPORT_PATH")/.update-report-XXXXXX")" + cat >"$tmp" < restarting archied.service" +systemctl --user restart archied.service + +if wait_healthy; then + echo "==> new version is healthy" + write_report "passed" false + exit 0 +fi + +echo "==> health check failed after ${HEALTH_TIMEOUT_SECONDS}s; rolling back" +rolled_back=false +if [ -f "$BIN_DIR/archied.prev" ] && [ -f "$BIN_DIR/archie-agent.prev" ]; then + cp -f "$BIN_DIR/archied.prev" "$BIN_DIR/archied" + cp -f "$BIN_DIR/archie-agent.prev" "$BIN_DIR/archie-agent" + rolled_back=true + systemctl --user restart archied.service +else + echo "==> no backup binaries found; cannot roll back automatically" >&2 +fi + +# rolled_back reflects what actually happened, not what was attempted: a +# report claiming a healed system when no backup existed to restore from +# would tell an operator to stand down while the broken version is still +# what's running (or still failing to start at all). +write_report "failed" "$rolled_back"