Merge pull request #607 from samcharles93/fix/component-aware-updates
fix(update): install only approved components
This commit is contained in:
commit
d2e7b24cc3
15 files changed
+591
-117
No files matched your search
@@ -147,7 +147,7 @@ type Gateway struct {
|
||||
type UpdateService interface {
|
||||
Check(context.Context, int64) (releaseupdate.Snapshot, error)
|
||||
Defer(context.Context, int64, releaseupdate.Snapshot) error
|
||||
Install(context.Context, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
||||
Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
||||
CanInstall() bool
|
||||
}
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ func (g *Gateway) dispatchUpdateAction(ctx context.Context, b *bot.Bot, query *m
|
||||
// the install operation from that request lifetime. Progress and
|
||||
// final-message edits still use ctx and may harmlessly fail when the
|
||||
// callback request is gone.
|
||||
go g.installUpdate(ctx, b, query)
|
||||
go g.installUpdate(ctx, b, query, fresh)
|
||||
default:
|
||||
g.answerModelCallback(ctx, b, query.ID, "That update action is no longer valid.", true)
|
||||
}
|
||||
@@ -177,7 +177,7 @@ func (g *Gateway) beginUpdate() bool {
|
||||
// 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) {
|
||||
func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.CallbackQuery, snapshot releaseupdate.Snapshot) {
|
||||
defer func() {
|
||||
g.updateMu.Lock()
|
||||
g.updateInProgress = false
|
||||
@@ -203,7 +203,7 @@ func (g *Gateway) installUpdate(ctx context.Context, b *bot.Bot, query *models.C
|
||||
}
|
||||
|
||||
installCtx := context.WithoutCancel(ctx)
|
||||
result, err := g.Updates.Install(installCtx, meta, progress)
|
||||
result, err := g.Updates.Install(installCtx, snapshot, meta, progress)
|
||||
if err != nil {
|
||||
g.log.Error("approved update failed", "error", err)
|
||||
lines = append(lines, formatInstallFailure(err))
|
||||
|
||||
@@ -24,7 +24,7 @@ func (s *contextAwareUpdateStub) Defer(context.Context, int64, releaseupdate.Sna
|
||||
return nil
|
||||
}
|
||||
func (s *contextAwareUpdateStub) CanInstall() bool { return true }
|
||||
func (s *contextAwareUpdateStub) Install(ctx context.Context, _ releaseupdate.InstallMeta, _ func(string)) (releaseupdate.Result, error) {
|
||||
func (s *contextAwareUpdateStub) Install(ctx context.Context, _ releaseupdate.Snapshot, _ releaseupdate.InstallMeta, _ func(string)) (releaseupdate.Result, error) {
|
||||
s.seen = ctx
|
||||
close(s.started)
|
||||
return releaseupdate.Result{}, nil
|
||||
@@ -43,7 +43,7 @@ func TestInstallUpdateDetachesInstallerFromCallbackContext(t *testing.T) {
|
||||
g.installUpdate(callbackCtx, b, &models.CallbackQuery{
|
||||
From: models.User{ID: 42},
|
||||
Message: models.MaybeInaccessibleMessage{Message: message},
|
||||
})
|
||||
}, releaseupdate.Snapshot{})
|
||||
close(done)
|
||||
}()
|
||||
<-stub.started
|
||||
|
||||
@@ -63,7 +63,7 @@ func TestInstallUpdateStreamsProgressAndReportsSuccess(t *testing.T) {
|
||||
g.installUpdate(context.Background(), b, &models.CallbackQuery{
|
||||
From: models.User{ID: 42},
|
||||
Message: models.MaybeInaccessibleMessage{Message: message},
|
||||
})
|
||||
}, releaseupdate.Snapshot{})
|
||||
|
||||
if stub.gotMeta.Channel != "telegram" || stub.gotMeta.ChatID != 7 || stub.gotMeta.ThreadID != 3 {
|
||||
t.Errorf("gotMeta = %#v, want channel/chat/thread forwarded", stub.gotMeta)
|
||||
@@ -97,7 +97,7 @@ func TestInstallUpdateReportsBuildFailureWithoutClaimingRestart(t *testing.T) {
|
||||
g.installUpdate(context.Background(), b, &models.CallbackQuery{
|
||||
From: models.User{ID: 42},
|
||||
Message: models.MaybeInaccessibleMessage{Message: message},
|
||||
})
|
||||
}, releaseupdate.Snapshot{})
|
||||
|
||||
last := (*requests)[len(*requests)-1]
|
||||
text := strings.ToLower(last.form["text"])
|
||||
@@ -408,7 +408,7 @@ func (s *updateStub) Check(context.Context, int64) (releaseupdate.Snapshot, erro
|
||||
return s.snapshot, nil
|
||||
}
|
||||
func (s *updateStub) Defer(context.Context, int64, releaseupdate.Snapshot) error { return nil }
|
||||
func (s *updateStub) Install(_ context.Context, meta releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) {
|
||||
func (s *updateStub) Install(_ context.Context, _ releaseupdate.Snapshot, meta releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) {
|
||||
s.installCalls++
|
||||
s.gotMeta = meta
|
||||
for _, line := range s.progressText {
|
||||
|
||||
@@ -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, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
||||
Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
||||
CanInstall() bool
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ 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, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) {
|
||||
func (parityUpdateStub) Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error) {
|
||||
return releaseupdate.Result{}, nil
|
||||
}
|
||||
func (parityUpdateStub) CanInstall() bool { return true }
|
||||
|
||||
@@ -43,17 +43,22 @@ type CommandInstaller struct{ Command []string }
|
||||
// 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) {
|
||||
func (i CommandInstaller) Install(ctx context.Context, snapshot Snapshot, meta InstallMeta, progress func(string)) (Result, error) {
|
||||
if len(i.Command) == 0 {
|
||||
return Result{}, fmt.Errorf("update install command is empty")
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, i.Command[0], i.Command[1:]...)
|
||||
versions := componentVersions(snapshot)
|
||||
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,
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS="+versions[ComponentDaemon].Installed,
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION="+versions[ComponentDaemon].Available,
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS="+versions[ComponentAgent].Installed,
|
||||
"ARCHIE_UPDATE_AGENT_VERSION="+versions[ComponentAgent].Available,
|
||||
)
|
||||
|
||||
stdout, err := cmd.StdoutPipe()
|
||||
@@ -94,3 +99,24 @@ func (i CommandInstaller) Install(ctx context.Context, meta InstallMeta, progres
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// componentVersions reduces an approved snapshot to the two components the
|
||||
// reference binary installer owns. Available is intentionally blank for an
|
||||
// unchanged component: the install script treats these values as the complete
|
||||
// approved plan, not as hints to rediscover work after approval.
|
||||
func componentVersions(snapshot Snapshot) map[string]Component {
|
||||
versions := map[string]Component{
|
||||
ComponentDaemon: {},
|
||||
ComponentAgent: {},
|
||||
}
|
||||
for _, component := range snapshot.Components {
|
||||
if component.ID != ComponentDaemon && component.ID != ComponentAgent {
|
||||
continue
|
||||
}
|
||||
if component.Available == component.Installed {
|
||||
component.Available = ""
|
||||
}
|
||||
versions[component.ID] = component
|
||||
}
|
||||
return versions
|
||||
}
|
||||
@@ -32,7 +32,7 @@ echo 'ARCHIE_UPDATE_RESULT {"previous":{"daemon":"1.0.0"},"installed":{"daemon":
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
var progress []string
|
||||
result, err := installer.Install(context.Background(), InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
result, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
if err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
@@ -58,7 +58,7 @@ 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) })
|
||||
result, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
if err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func TestCommandInstallerMissingSentinelReturnsEmptyResult(t *testing.T) {
|
||||
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) {})
|
||||
_, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {})
|
||||
if err == nil {
|
||||
t.Fatal("Install() error = nil, want a decode error")
|
||||
}
|
||||
@@ -95,7 +95,7 @@ exit 1
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
var progress []string
|
||||
_, err := installer.Install(context.Background(), InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
_, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(line string) { progress = append(progress, line) })
|
||||
if err == nil {
|
||||
t.Fatal("Install() error = nil, want non-zero exit error")
|
||||
}
|
||||
@@ -117,7 +117,7 @@ echo "channel=$ARCHIE_UPDATE_CHANNEL chat=$ARCHIE_UPDATE_CHAT_ID thread=$ARCHIE_
|
||||
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 {
|
||||
if _, err := installer.Install(context.Background(), Snapshot{}, 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"
|
||||
@@ -126,9 +126,28 @@ echo "channel=$ARCHIE_UPDATE_CHANNEL chat=$ARCHIE_UPDATE_CHAT_ID thread=$ARCHIE_
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandInstallerForwardsApprovedComponentPlanAsEnv(t *testing.T) {
|
||||
script := writeFixtureScript(t, `
|
||||
echo "daemon=$ARCHIE_UPDATE_DAEMON_PREVIOUS->$ARCHIE_UPDATE_DAEMON_VERSION agent=$ARCHIE_UPDATE_AGENT_PREVIOUS->$ARCHIE_UPDATE_AGENT_VERSION"
|
||||
`)
|
||||
installer := CommandInstaller{Command: []string{script}}
|
||||
snapshot := Snapshot{Components: []Component{
|
||||
{ID: ComponentDaemon, Installed: "1.12.0", Available: "1.13.0"},
|
||||
{ID: ComponentAgent, Installed: "1.9.9", Available: "1.9.9"},
|
||||
}}
|
||||
var progress []string
|
||||
if _, err := installer.Install(context.Background(), snapshot, InstallMeta{}, func(line string) { progress = append(progress, line) }); err != nil {
|
||||
t.Fatalf("Install() error = %v", err)
|
||||
}
|
||||
want := "daemon=1.12.0->1.13.0 agent=1.9.9->"
|
||||
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 {
|
||||
if _, err := installer.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {}); err == nil {
|
||||
t.Fatal("Install() error = nil, want empty-command error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package releaseupdate
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpdateInstallGatewayOnlySkipsRuntimeWork(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "git pull --ff-only")
|
||||
assertCallContains(t, calls, "git -C", "rev-parse --verify refs/tags/archied/v1.13.0^{commit}")
|
||||
assertCallContains(t, calls, "git -C", "worktree add --detach")
|
||||
assertCallContains(t, calls, "go build", "main.runtimeVersion=1.9.9", "./cmd/archied")
|
||||
assertCallAbsent(t, calls, "./cmd/archie-agent")
|
||||
assertCallAbsent(t, calls, "docker compose build agent")
|
||||
if got := result.Installed[ComponentDaemon]; got != "1.13.0" {
|
||||
t.Fatalf("installed daemon = %q, want 1.13.0", got)
|
||||
}
|
||||
if _, found := result.Installed[ComponentAgent]; found {
|
||||
t.Fatalf("gateway-only result unexpectedly claims an agent install: %#v", result.Installed)
|
||||
}
|
||||
if !result.RestartRequested {
|
||||
t.Fatal("RestartRequested = false, want true for gateway update")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstallRuntimeOnlySkipsGatewayBuild(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "go build", "./cmd/archie-agent")
|
||||
assertCallAbsent(t, calls, "./cmd/archied")
|
||||
assertCallContains(t, calls, "docker compose build", "--build-arg RUNTIME_VERSION=1.10.0", "agent")
|
||||
if got := result.Installed[ComponentAgent]; got != "1.10.0" {
|
||||
t.Fatalf("installed agent = %q, want 1.10.0", got)
|
||||
}
|
||||
if _, found := result.Installed[ComponentDaemon]; found {
|
||||
t.Fatalf("runtime-only result unexpectedly claims a daemon install: %#v", result.Installed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstallBothComponentsBuildsAndInstallsBoth(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
|
||||
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
|
||||
})
|
||||
|
||||
assertCallContains(t, calls, "go build", "./cmd/archied")
|
||||
assertCallContains(t, calls, "go build", "./cmd/archie-agent")
|
||||
assertCallContains(t, calls, "docker compose build", "RUNTIME_VERSION=1.10.0")
|
||||
if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.10.0" {
|
||||
t.Fatalf("installed = %#v, want both release versions", result.Installed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInstallNoopDoesNotFetchBuildInstallOrRestart(t *testing.T) {
|
||||
result, calls := runUpdateInstallScript(t, map[string]string{
|
||||
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.13.0",
|
||||
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
|
||||
})
|
||||
|
||||
for _, forbidden := range []string{"git pull", "go build", "docker ", "systemd-run ", "install ", "cp "} {
|
||||
assertCallAbsent(t, calls, forbidden)
|
||||
}
|
||||
if len(result.Previous) != 0 || len(result.Installed) != 0 || len(result.Components) != 0 || result.RestartRequested {
|
||||
t.Fatalf("no-op result = %#v, want empty result without restart", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateWatchdogRollsBackAndReportsOnlyChangedComponents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
components string
|
||||
wantDaemon string
|
||||
wantAgent string
|
||||
}{
|
||||
{name: "gateway only", components: "daemon", wantDaemon: "old daemon", wantAgent: "new agent"},
|
||||
{name: "runtime only", components: "agent", wantDaemon: "new daemon", wantAgent: "old agent"},
|
||||
{name: "both", components: "daemon,agent", wantDaemon: "old daemon", wantAgent: "old agent"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
report, daemon, agent := runUpdateWatchdogFailure(t, tt.components)
|
||||
if daemon != tt.wantDaemon || agent != tt.wantAgent {
|
||||
t.Fatalf("binaries after rollback = daemon %q agent %q, want %q / %q", daemon, agent, tt.wantDaemon, tt.wantAgent)
|
||||
}
|
||||
if !report.RolledBack || report.HealthCheck != "failed" {
|
||||
t.Fatalf("report = %#v, want failed rollback", report)
|
||||
}
|
||||
if _, found := report.Installed[ComponentDaemon]; found != strings.Contains(tt.components, "daemon") {
|
||||
t.Fatalf("daemon report membership = %v for components %q", found, tt.components)
|
||||
}
|
||||
if _, found := report.Installed[ComponentAgent]; found != strings.Contains(tt.components, "agent") {
|
||||
t.Fatalf("agent report membership = %v for components %q", found, tt.components)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdateInstallScript(t *testing.T, environment map[string]string) (Result, []string) {
|
||||
t.Helper()
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir := filepath.Join(work, "bin")
|
||||
fakeDir := filepath.Join(work, "fake-bin")
|
||||
callsPath := filepath.Join(work, "calls")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"archied", "archie-agent"} {
|
||||
if err := os.WriteFile(filepath.Join(binDir, name), []byte("old "+name), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writeFakeCommand(t, fakeDir, "git", `
|
||||
printf '%s\n' "git $*" >> "$ARCHIE_TEST_CALLS"
|
||||
case "$*" in
|
||||
*"rev-parse --verify refs/tags/"*) echo approved-release-commit ;;
|
||||
*"worktree add --detach"*)
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = "--detach" ]; then
|
||||
source_dir="$2"
|
||||
mkdir -p "$source_dir"
|
||||
/usr/bin/cp -R "$ARCHIE_REPO_DIR/scripts" "$source_dir/scripts"
|
||||
: > "$source_dir/docker-compose.yml"
|
||||
break
|
||||
fi
|
||||
shift
|
||||
done
|
||||
;;
|
||||
*"worktree remove --force"*) ;;
|
||||
esac
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "go", `
|
||||
printf '%s\n' "go $*" >> "$ARCHIE_TEST_CALLS"
|
||||
out=""
|
||||
while [ "$#" -gt 0 ]; do
|
||||
if [ "$1" = "-o" ]; then out="$2"; break; fi
|
||||
shift
|
||||
done
|
||||
mkdir -p "$(dirname "$out")"
|
||||
printf 'built\n' > "$out"
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "docker", `printf '%s\n' "docker $*" >> "$ARCHIE_TEST_CALLS"`)
|
||||
writeFakeCommand(t, fakeDir, "systemd-run", `printf '%s\n' "systemd-run $*" >> "$ARCHIE_TEST_CALLS"`)
|
||||
writeFakeCommand(t, fakeDir, "install", `
|
||||
printf '%s\n' "install $*" >> "$ARCHIE_TEST_CALLS"
|
||||
/usr/bin/install "$@"
|
||||
`)
|
||||
writeFakeCommand(t, fakeDir, "cp", `
|
||||
printf '%s\n' "cp $*" >> "$ARCHIE_TEST_CALLS"
|
||||
/usr/bin/cp "$@"
|
||||
`)
|
||||
|
||||
// The production adapter prepends /usr/local/go/bin. Run an otherwise
|
||||
// byte-for-byte copy with the harness PATH left first so fake go records
|
||||
// build intent without compiling or touching Docker/systemd.
|
||||
scriptData, err := os.ReadFile(filepath.Join(root, "scripts", "archie-update-install"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scriptPath := filepath.Join(work, "archie-update-install")
|
||||
scriptData = []byte(strings.Replace(string(scriptData), `export PATH="/usr/local/go/bin:$PATH"`, `export PATH="$PATH"`, 1))
|
||||
if err := os.WriteFile(scriptPath, scriptData, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command(scriptPath)
|
||||
cmd.Env = append(
|
||||
os.Environ(),
|
||||
"PATH="+fakeDir+":"+os.Getenv("PATH"),
|
||||
"ARCHIE_REPO_DIR="+root,
|
||||
"ARCHIE_BIN_DIR="+binDir,
|
||||
"ARCHIE_TEST_CALLS="+callsPath,
|
||||
)
|
||||
for key, value := range environment {
|
||||
cmd.Env = append(cmd.Env, key+"="+value)
|
||||
}
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("archie-update-install failed: %v\n%s", err, output)
|
||||
}
|
||||
var result Result
|
||||
scanner := bufio.NewScanner(strings.NewReader(string(output)))
|
||||
found := false
|
||||
for scanner.Scan() {
|
||||
if payload, ok := strings.CutPrefix(scanner.Text(), updateResultSentinel); ok {
|
||||
found = true
|
||||
if err := json.Unmarshal([]byte(payload), &result); err != nil {
|
||||
t.Fatalf("decode result %q: %v", payload, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("installer output has no result sentinel:\n%s", output)
|
||||
}
|
||||
callsData, err := os.ReadFile(callsPath)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var calls []string
|
||||
if len(callsData) > 0 {
|
||||
calls = strings.Split(strings.TrimSpace(string(callsData)), "\n")
|
||||
}
|
||||
return result, calls
|
||||
}
|
||||
|
||||
func writeFakeCommand(t *testing.T, dir, name, body string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(path, []byte("#!/usr/bin/env bash\nset -euo pipefail\n"+body), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, string) {
|
||||
t.Helper()
|
||||
root, err := filepath.Abs(filepath.Join("..", ".."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
work := t.TempDir()
|
||||
binDir := filepath.Join(work, "bin")
|
||||
fakeDir := filepath.Join(work, "fake-bin")
|
||||
reportPath := filepath.Join(work, "report.json")
|
||||
if err := os.MkdirAll(binDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files := map[string]string{
|
||||
"archied": "new daemon", "archied.prev": "old daemon",
|
||||
"archie-agent": "new agent", "archie-agent.prev": "old agent",
|
||||
}
|
||||
for name, content := range files {
|
||||
if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
writeFakeCommand(t, fakeDir, "systemctl", `exit 0`)
|
||||
writeFakeCommand(t, fakeDir, "curl", `exit 1`)
|
||||
|
||||
cmd := exec.Command(filepath.Join(root, "scripts", "archie-update-watchdog"))
|
||||
cmd.Env = append(
|
||||
os.Environ(),
|
||||
"PATH="+fakeDir+":"+os.Getenv("PATH"),
|
||||
"ARCHIE_BIN_DIR="+binDir,
|
||||
"ARCHIE_UPDATE_REPORT_PATH="+reportPath,
|
||||
"ARCHIE_UPDATE_HEALTH_TIMEOUT=0",
|
||||
"ARCHIE_UPDATE_COMPONENTS="+components,
|
||||
"ARCHIE_UPDATE_PREVIOUS_GATEWAY=1.12.0",
|
||||
"ARCHIE_UPDATE_INSTALLED_GATEWAY=1.13.0",
|
||||
"ARCHIE_UPDATE_PREVIOUS_RUNTIME=1.9.9",
|
||||
"ARCHIE_UPDATE_INSTALLED_RUNTIME=1.10.0",
|
||||
)
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("watchdog failed: %v\n%s", err, output)
|
||||
}
|
||||
reportData, err := os.ReadFile(reportPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var report Report
|
||||
if err := json.Unmarshal(reportData, &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
daemon, err := os.ReadFile(filepath.Join(binDir, "archied"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
agent, err := os.ReadFile(filepath.Join(binDir, "archie-agent"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return report, string(daemon), string(agent)
|
||||
}
|
||||
|
||||
func assertCallContains(t *testing.T, calls []string, fragments ...string) {
|
||||
t.Helper()
|
||||
for _, call := range calls {
|
||||
matched := true
|
||||
for _, fragment := range fragments {
|
||||
matched = matched && strings.Contains(call, fragment)
|
||||
}
|
||||
if matched {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("calls %#v contain no call with fragments %#v", calls, fragments)
|
||||
}
|
||||
|
||||
func assertCallAbsent(t *testing.T, calls []string, fragment string) {
|
||||
t.Helper()
|
||||
for _, call := range calls {
|
||||
if strings.Contains(call, fragment) {
|
||||
t.Fatalf("calls unexpectedly contain %q: %#v", fragment, calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ type Catalog interface {
|
||||
// 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, InstallMeta, func(string)) (Result, error)
|
||||
Install(context.Context, Snapshot, InstallMeta, func(string)) (Result, error)
|
||||
}
|
||||
|
||||
type Component struct {
|
||||
@@ -217,7 +217,7 @@ const installTimeout = 30 * time.Minute
|
||||
// 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) {
|
||||
func (s *Service) Install(ctx context.Context, snapshot Snapshot, meta InstallMeta, progress func(string)) (Result, error) {
|
||||
if s == nil || s.Installer == nil {
|
||||
return Result{}, errors.New("update installation is not configured")
|
||||
}
|
||||
@@ -239,7 +239,7 @@ func (s *Service) Install(ctx context.Context, meta InstallMeta, progress func(s
|
||||
|
||||
installCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), installTimeout)
|
||||
defer cancel()
|
||||
return s.Installer.Install(installCtx, meta, progress)
|
||||
return s.Installer.Install(installCtx, snapshot, meta, progress)
|
||||
}
|
||||
|
||||
func (s *Service) CanInstall() bool { return s != nil && s.Installer != nil }
|
||||
|
||||
@@ -123,7 +123,8 @@ func TestServiceInstallForwardsProgressAndFailure(t *testing.T) {
|
||||
service := Service{Installer: installer, InstallType: "binary"}
|
||||
var progress []string
|
||||
meta := InstallMeta{Channel: "telegram", ChatID: 42}
|
||||
result, err := service.Install(context.Background(), meta, func(message string) { progress = append(progress, message) })
|
||||
snapshot := Snapshot{Components: []Component{{ID: ComponentDaemon, Installed: "1.0.0", Available: "1.1.0"}}}
|
||||
result, err := service.Install(context.Background(), snapshot, meta, func(message string) { progress = append(progress, message) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -133,6 +134,9 @@ func TestServiceInstallForwardsProgressAndFailure(t *testing.T) {
|
||||
if installer.gotMeta != meta {
|
||||
t.Errorf("installer received meta = %#v, want %#v", installer.gotMeta, meta)
|
||||
}
|
||||
if !SameAvailable(installer.gotSnapshot, snapshot) {
|
||||
t.Errorf("installer received snapshot = %#v, want %#v", installer.gotSnapshot, snapshot)
|
||||
}
|
||||
if len(progress) != 1 || progress[0] != "Pulling release..." {
|
||||
t.Errorf("progress = %#v", progress)
|
||||
}
|
||||
@@ -160,7 +164,7 @@ func TestServiceInstallRefusesAnUnknownInstallType(t *testing.T) {
|
||||
installer := &installerStub{}
|
||||
service := Service{Installer: installer, InstallType: tt.installType}
|
||||
|
||||
_, err := service.Install(context.Background(), InstallMeta{}, func(string) {})
|
||||
_, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {})
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("Install() returned nil error, want a refusal")
|
||||
@@ -186,7 +190,7 @@ func TestServiceInstallSurvivesCallerContextCancellation(t *testing.T) {
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := service.Install(ctx, InstallMeta{}, func(string) {})
|
||||
_, err := service.Install(ctx, Snapshot{}, InstallMeta{}, func(string) {})
|
||||
done <- err
|
||||
}()
|
||||
|
||||
@@ -216,12 +220,12 @@ func TestServiceInstallRefusesConcurrentInstalls(t *testing.T) {
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := service.Install(context.Background(), InstallMeta{}, func(string) {})
|
||||
_, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {})
|
||||
done <- err
|
||||
}()
|
||||
<-installer.started
|
||||
|
||||
if _, err := service.Install(context.Background(), InstallMeta{}, func(string) {}); !errors.Is(err, ErrInstallInProgress) {
|
||||
if _, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, func(string) {}); !errors.Is(err, ErrInstallInProgress) {
|
||||
t.Fatalf("second Install() error = %v, want ErrInstallInProgress", err)
|
||||
}
|
||||
|
||||
@@ -243,7 +247,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(), InstallMeta{}, nil); err == nil {
|
||||
if _, err := service.Install(context.Background(), Snapshot{}, InstallMeta{}, nil); err == nil {
|
||||
t.Fatal("nil service install returned nil error")
|
||||
}
|
||||
if service.CanInstall() {
|
||||
@@ -289,7 +293,7 @@ type blockingInstallerStub struct {
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *blockingInstallerStub) Install(ctx context.Context, _ InstallMeta, _ func(string)) (Result, error) {
|
||||
func (s *blockingInstallerStub) Install(ctx context.Context, _ Snapshot, _ InstallMeta, _ func(string)) (Result, error) {
|
||||
s.calls++
|
||||
close(s.started)
|
||||
if s.gotCancelled == nil {
|
||||
@@ -304,13 +308,15 @@ func (s *blockingInstallerStub) Install(ctx context.Context, _ InstallMeta, _ fu
|
||||
}
|
||||
|
||||
type installerStub struct {
|
||||
called bool
|
||||
gotMeta InstallMeta
|
||||
called bool
|
||||
gotMeta InstallMeta
|
||||
gotSnapshot Snapshot
|
||||
}
|
||||
|
||||
func (s *installerStub) Install(_ context.Context, meta InstallMeta, progress func(string)) (Result, error) {
|
||||
func (s *installerStub) Install(_ context.Context, snapshot Snapshot, meta InstallMeta, progress func(string)) (Result, error) {
|
||||
s.called = true
|
||||
s.gotMeta = meta
|
||||
s.gotSnapshot = snapshot
|
||||
progress("Pulling release...")
|
||||
return Result{Installed: map[string]string{"daemon": "1.1.0"}}, nil
|
||||
}
|
||||
@@ -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, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
||||
Install(context.Context, releaseupdate.Snapshot, releaseupdate.InstallMeta, func(string)) (releaseupdate.Result, error)
|
||||
CanInstall() bool
|
||||
}
|
||||
|
||||
@@ -510,7 +510,7 @@ func (s *Server) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
progress := make([]string, 0, 4)
|
||||
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: s.UpdateReportPath}
|
||||
result, err := chat.Updates.Install(r.Context(), meta, func(message string) { progress = append(progress, message) })
|
||||
result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) })
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadGateway)
|
||||
return
|
||||
|
||||
@@ -91,7 +91,7 @@ func (s *chatUpdateStub) Defer(_ context.Context, _ int64, snapshot releaseupdat
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *chatUpdateStub) Install(_ context.Context, meta releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) {
|
||||
func (s *chatUpdateStub) Install(_ context.Context, _ releaseupdate.Snapshot, meta releaseupdate.InstallMeta, progress func(string)) (releaseupdate.Result, error) {
|
||||
s.installed = true
|
||||
s.installedMeta = meta
|
||||
progress("install started")
|
||||
|
||||
+119
-57
@@ -1,24 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# archie-update-install -- update installation adapter for archied's /update.
|
||||
# archie-update-install -- component-aware update installation adapter.
|
||||
#
|
||||
# archied runs this via CommandInstaller after the operator approves, and
|
||||
# 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.
|
||||
#
|
||||
# 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.
|
||||
# CommandInstaller passes the freshly revalidated, approved snapshot through
|
||||
# ARCHIE_UPDATE_{DAEMON,AGENT}_{PREVIOUS,VERSION}. A VERSION is non-empty only
|
||||
# when that component changed in the approved snapshot. This script must never
|
||||
# rediscover a broader plan after approval.
|
||||
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'
|
||||
}
|
||||
@@ -27,43 +15,108 @@ REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}"
|
||||
BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}"
|
||||
export PATH="/usr/local/go/bin:$PATH"
|
||||
|
||||
PREV_GW="${ARCHIE_UPDATE_DAEMON_PREVIOUS:-}"
|
||||
PREV_RT="${ARCHIE_UPDATE_AGENT_PREVIOUS:-}"
|
||||
GW_TARGET="${ARCHIE_UPDATE_DAEMON_VERSION:-}"
|
||||
RT_TARGET="${ARCHIE_UPDATE_AGENT_VERSION:-}"
|
||||
GW="$PREV_GW"
|
||||
RT="$PREV_RT"
|
||||
components=""
|
||||
|
||||
if [ -n "$GW_TARGET" ] && [ "$GW_TARGET" != "$PREV_GW" ]; then
|
||||
GW="$GW_TARGET"
|
||||
components="daemon"
|
||||
fi
|
||||
if [ -n "$RT_TARGET" ] && [ "$RT_TARGET" != "$PREV_RT" ]; then
|
||||
case "$RT_TARGET" in
|
||||
dev|unknown) echo "refusing to build a released runtime image with version '$RT_TARGET'" >&2; exit 1 ;;
|
||||
esac
|
||||
RT="$RT_TARGET"
|
||||
components="${components:+$components,}agent"
|
||||
fi
|
||||
|
||||
if [ -z "$components" ]; then
|
||||
echo '==> no approved component changes; nothing to install'
|
||||
echo 'ARCHIE_UPDATE_RESULT {"previous":{},"installed":{},"components":[],"restart_requested":false}'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
valid_release_version() {
|
||||
[[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+([+-][0-9A-Za-z.-]+)?$ ]]
|
||||
}
|
||||
|
||||
for target in "$GW_TARGET" "$RT_TARGET"; do
|
||||
if [ -n "$target" ] && ! valid_release_version "$target"; then
|
||||
echo "refusing non-release component version '$target'" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
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"
|
||||
echo "==> fetching approved component releases"
|
||||
git pull --ff-only
|
||||
|
||||
# Refresh the installed adapters from the checkout just fetched. The running
|
||||
# shell continues with the old script, but the next /update uses the current
|
||||
# implementation even when this invocation was started by an older install.
|
||||
install -m755 "$REPO/scripts/archie-update-install" "$BIN_DIR/archie-update-install"
|
||||
install -m755 "$REPO/scripts/archie-update-watchdog" "$BIN_DIR/archie-update-watchdog"
|
||||
install -m755 "$REPO/scripts/archie-update-check" "$BIN_DIR/archie-update-check"
|
||||
|
||||
GW="$(git describe --tags --match 'archied/v*' | sed 's|^archied/v||')"
|
||||
RT="$(git describe --tags --match 'archie/v*' | sed 's|^archie/v||')"
|
||||
echo "==> building archied $GW / archie-agent $RT"
|
||||
# Build from the exact approved release commit, not the moving branch tip. A
|
||||
# temporary worktree keeps the operator's main checkout on its branch.
|
||||
if [[ ",$components," == *,daemon,* ]]; then
|
||||
gw_commit="$(git -C "$REPO" rev-parse --verify "refs/tags/archied/v$GW^{commit}")"
|
||||
fi
|
||||
if [[ ",$components," == *,agent,* ]]; then
|
||||
rt_commit="$(git -C "$REPO" rev-parse --verify "refs/tags/archie/v$RT^{commit}")"
|
||||
fi
|
||||
case "$components" in
|
||||
daemon) build_commit="$gw_commit" ;;
|
||||
agent) build_commit="$rt_commit" ;;
|
||||
daemon,agent)
|
||||
if [ "$gw_commit" != "$rt_commit" ]; then
|
||||
echo "approved component tags do not identify the same source commit" >&2
|
||||
exit 1
|
||||
fi
|
||||
build_commit="$gw_commit"
|
||||
;;
|
||||
esac
|
||||
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
source_dir="$tmp/source"
|
||||
cleanup() {
|
||||
git -C "$REPO" worktree remove --force "$source_dir" >/dev/null 2>&1 || true
|
||||
rm -rf "$tmp"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
git -C "$REPO" worktree add --detach "$source_dir" "$build_commit"
|
||||
cd "$source_dir"
|
||||
|
||||
go build -ldflags "-X main.gatewayVersion=$GW -X main.runtimeVersion=$RT -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" \
|
||||
-o "$tmp/archied" ./cmd/archied
|
||||
go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version=$RT -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" \
|
||||
-o "$tmp/archie-agent" ./cmd/archie-agent
|
||||
# Refresh adapters from the approved release source. The running shell
|
||||
# continues with this copy; subsequent updates use the current contract.
|
||||
install -m755 "$source_dir/scripts/archie-update-install" "$BIN_DIR/archie-update-install"
|
||||
install -m755 "$source_dir/scripts/archie-update-watchdog" "$BIN_DIR/archie-update-watchdog"
|
||||
install -m755 "$source_dir/scripts/archie-update-check" "$BIN_DIR/archie-update-check"
|
||||
|
||||
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"
|
||||
if [[ ",$components," == *,daemon,* ]]; then
|
||||
echo "==> building archied $GW"
|
||||
go build -ldflags "-X main.gatewayVersion=$GW -X main.runtimeVersion=$RT -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" \
|
||||
-o "$tmp/archied" ./cmd/archied
|
||||
fi
|
||||
if [[ ",$components," == *,agent,* ]]; then
|
||||
echo "==> building archie-agent $RT"
|
||||
go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version=$RT -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" \
|
||||
-o "$tmp/archie-agent" ./cmd/archie-agent
|
||||
fi
|
||||
|
||||
echo "==> installing"
|
||||
install -m755 "$tmp/archied" "$BIN_DIR/archied"
|
||||
install -m755 "$tmp/archie-agent" "$BIN_DIR/archie-agent"
|
||||
|
||||
echo "==> rebuilding agent image"
|
||||
docker compose build agent
|
||||
if [[ ",$components," == *,daemon,* ]]; then
|
||||
echo "==> backing up current archied binary"
|
||||
[ -f "$BIN_DIR/archied" ] && cp -f "$BIN_DIR/archied" "$BIN_DIR/archied.prev"
|
||||
echo "==> installing archied"
|
||||
install -m755 "$tmp/archied" "$BIN_DIR/archied"
|
||||
fi
|
||||
if [[ ",$components," == *,agent,* ]]; then
|
||||
echo "==> backing up current archie-agent binary"
|
||||
[ -f "$BIN_DIR/archie-agent" ] && cp -f "$BIN_DIR/archie-agent" "$BIN_DIR/archie-agent.prev"
|
||||
echo "==> installing archie-agent"
|
||||
install -m755 "$tmp/archie-agent" "$BIN_DIR/archie-agent"
|
||||
echo "==> rebuilding agent image for runtime $RT"
|
||||
docker compose build --build-arg "RUNTIME_VERSION=$RT" agent
|
||||
fi
|
||||
|
||||
echo "==> handing off to the update watchdog for restart and health verification"
|
||||
systemd-run --user --unit=archied-update-restart --collect --quiet \
|
||||
@@ -73,19 +126,28 @@ systemd-run --user --unit=archied-update-restart --collect --quiet \
|
||||
--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_COMPONENTS="$components" \
|
||||
--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"
|
||||
"$BIN_DIR/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}"
|
||||
case "$components" in
|
||||
daemon)
|
||||
previous="{\"daemon\":\"$(json_escape "$PREV_GW")\"}"
|
||||
installed="{\"daemon\":\"$(json_escape "$GW")\"}"
|
||||
results='[{"id":"daemon","label":"daemon","status":"updated"}]'
|
||||
;;
|
||||
agent)
|
||||
previous="{\"agent\":\"$(json_escape "$PREV_RT")\"}"
|
||||
installed="{\"agent\":\"$(json_escape "$RT")\"}"
|
||||
results='[{"id":"agent","label":"agent","status":"updated"}]'
|
||||
;;
|
||||
daemon,agent)
|
||||
previous="{\"daemon\":\"$(json_escape "$PREV_GW")\",\"agent\":\"$(json_escape "$PREV_RT")\"}"
|
||||
installed="{\"daemon\":\"$(json_escape "$GW")\",\"agent\":\"$(json_escape "$RT")\"}"
|
||||
results='[{"id":"daemon","label":"daemon","status":"updated"},{"id":"agent","label":"agent","status":"updated"}]'
|
||||
;;
|
||||
esac
|
||||
echo "ARCHIE_UPDATE_RESULT {\"previous\":$previous,\"installed\":$installed,\"components\":$results,\"restart_requested\":true}"
|
||||
@@ -1,16 +1,10 @@
|
||||
#!/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.
|
||||
# archie-update-watchdog -- restarts archied after an update, verifies health,
|
||||
# and rolls back only the components named by ARCHIE_UPDATE_COMPONENTS.
|
||||
#
|
||||
# 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.
|
||||
# Runtime-only updates still restart archied: the restart is the existing
|
||||
# phase-2 handoff that makes the daemon consume and deliver the health report.
|
||||
# It does not rebuild or reinstall the gateway binary.
|
||||
set -uo pipefail
|
||||
|
||||
BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}"
|
||||
@@ -18,21 +12,41 @@ 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
|
||||
COMPONENTS="${ARCHIE_UPDATE_COMPONENTS:-daemon,agent}"
|
||||
|
||||
# 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'
|
||||
}
|
||||
|
||||
report_versions() {
|
||||
case "$COMPONENTS" in
|
||||
daemon)
|
||||
previous_json="{\"daemon\":\"$(json_escape "${ARCHIE_UPDATE_PREVIOUS_GATEWAY:-unknown}")\"}"
|
||||
installed_json="{\"daemon\":\"$(json_escape "${ARCHIE_UPDATE_INSTALLED_GATEWAY:-unknown}")\"}"
|
||||
;;
|
||||
agent)
|
||||
previous_json="{\"agent\":\"$(json_escape "${ARCHIE_UPDATE_PREVIOUS_RUNTIME:-unknown}")\"}"
|
||||
installed_json="{\"agent\":\"$(json_escape "${ARCHIE_UPDATE_INSTALLED_RUNTIME:-unknown}")\"}"
|
||||
;;
|
||||
daemon,agent)
|
||||
previous_json="{\"daemon\":\"$(json_escape "${ARCHIE_UPDATE_PREVIOUS_GATEWAY:-unknown}")\",\"agent\":\"$(json_escape "${ARCHIE_UPDATE_PREVIOUS_RUNTIME:-unknown}")\"}"
|
||||
installed_json="{\"daemon\":\"$(json_escape "${ARCHIE_UPDATE_INSTALLED_GATEWAY:-unknown}")\",\"agent\":\"$(json_escape "${ARCHIE_UPDATE_INSTALLED_RUNTIME:-unknown}")\"}"
|
||||
;;
|
||||
*)
|
||||
echo "invalid ARCHIE_UPDATE_COMPONENTS: $COMPONENTS" >&2
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
write_report() {
|
||||
local health_check="$1" rolled_back="$2"
|
||||
[ -z "$REPORT_PATH" ] && return 0
|
||||
report_versions || return 1
|
||||
mkdir -p "$(dirname "$REPORT_PATH")"
|
||||
tmp="$(mktemp "$(dirname "$REPORT_PATH")/.update-report-XXXXXX")"
|
||||
cat >"$tmp" <<EOF
|
||||
{"channel":"$(json_escape "${ARCHIE_UPDATE_CHANNEL:-}")","chat_id":${ARCHIE_UPDATE_CHAT_ID:-0},"thread_id":${ARCHIE_UPDATE_THREAD_ID:-0},"previous":{"daemon":"$(json_escape "${ARCHIE_UPDATE_PREVIOUS_GATEWAY:-unknown}")","agent":"$(json_escape "${ARCHIE_UPDATE_PREVIOUS_RUNTIME:-unknown}")"},"installed":{"daemon":"$(json_escape "${ARCHIE_UPDATE_INSTALLED_GATEWAY:-unknown}")","agent":"$(json_escape "${ARCHIE_UPDATE_INSTALLED_RUNTIME:-unknown}")"},"health_check":"$health_check","rolled_back":$rolled_back}
|
||||
{"channel":"$(json_escape "${ARCHIE_UPDATE_CHANNEL:-}")","chat_id":${ARCHIE_UPDATE_CHAT_ID:-0},"thread_id":${ARCHIE_UPDATE_THREAD_ID:-0},"previous":$previous_json,"installed":$installed_json,"health_check":"$health_check","rolled_back":$rolled_back}
|
||||
EOF
|
||||
chmod 600 "$tmp"
|
||||
mv -f "$tmp" "$REPORT_PATH"
|
||||
@@ -49,6 +63,15 @@ wait_healthy() {
|
||||
return 1
|
||||
}
|
||||
|
||||
rollback_component() {
|
||||
local name="$1"
|
||||
if [ ! -f "$BIN_DIR/$name.prev" ]; then
|
||||
echo "==> no backup for $name; cannot roll it back automatically" >&2
|
||||
return 1
|
||||
fi
|
||||
cp -f "$BIN_DIR/$name.prev" "$BIN_DIR/$name"
|
||||
}
|
||||
|
||||
echo "==> restarting archied.service"
|
||||
systemctl --user restart archied.service
|
||||
|
||||
@@ -58,19 +81,40 @@ if wait_healthy; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "==> health check failed after ${HEALTH_TIMEOUT_SECONDS}s; rolling back"
|
||||
echo "==> health check failed after ${HEALTH_TIMEOUT_SECONDS}s; rolling back changed components"
|
||||
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
|
||||
case "$COMPONENTS" in
|
||||
daemon)
|
||||
if [ -f "$BIN_DIR/archied.prev" ]; then
|
||||
rollback_component archied && rolled_back=true
|
||||
else
|
||||
echo "==> no backup for archied; cannot roll it back automatically" >&2
|
||||
fi
|
||||
;;
|
||||
agent)
|
||||
if [ -f "$BIN_DIR/archie-agent.prev" ]; then
|
||||
rollback_component archie-agent && rolled_back=true
|
||||
else
|
||||
echo "==> no backup for archie-agent; cannot roll it back automatically" >&2
|
||||
fi
|
||||
;;
|
||||
daemon,agent)
|
||||
# Preserve the old all-or-nothing rollback guarantee: never restore one
|
||||
# component and leave the other on the failed release.
|
||||
if [ -f "$BIN_DIR/archied.prev" ] && [ -f "$BIN_DIR/archie-agent.prev" ]; then
|
||||
if rollback_component archied && rollback_component archie-agent; then
|
||||
rolled_back=true
|
||||
fi
|
||||
else
|
||||
echo "==> not all changed-component backups exist; cannot roll back automatically" >&2
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
echo "invalid ARCHIE_UPDATE_COMPONENTS: $COMPONENTS" >&2
|
||||
;;
|
||||
esac
|
||||
if [ "$rolled_back" = true ]; then
|
||||
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"
|
||||
Reference in new issue
Block a user