feat(releaseupdate): install from release artifacts with journaled rollback, topology check and channels

This commit is contained in:
sam committed 2026-10-05 17:02:29 +11:00
1 parent 9bb20830f3
commit ee2c9cda97
24 files changed
+1186 -333

No files matched your search

+20 -2
View File
@@ -7,6 +7,7 @@ import (
"sync/atomic"
"github.com/samcharles93/archie-core/internal/app/servicekit"
"github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/domain/health"
)
@@ -24,6 +25,7 @@ import (
type healthSurface struct {
serving atomic.Bool
registry func() *health.Registry
inFlight func() int
}
// markServing tolerates a nil surface so a boot path that serves no health
@@ -70,7 +72,15 @@ func (h *healthSurface) handleDetailed(w http.ResponseWriter, r *http.Request) {
if report.Status != health.StatusOK {
w.WriteHeader(http.StatusServiceUnavailable)
}
_ = json.NewEncoder(w).Encode(report)
inFlight := -1
if h.serving.Load() && h.inFlight != nil {
inFlight = h.inFlight()
}
_ = json.NewEncoder(w).Encode(struct {
health.Report
Version string `json:"version"`
InFlight int `json:"in_flight"`
}{Report: report, Version: buildinfo.Version, InFlight: inFlight})
}
// startHealth binds the daemon's liveness surface on [health].listen. A
@@ -78,7 +88,15 @@ func (h *healthSurface) handleDetailed(w http.ResponseWriter, r *http.Request) {
// updates verified, and the watchdog would roll back every release it
// installs.
func (b *boot) startHealth(ctx context.Context) error {
b.health = &healthSurface{registry: func() *health.Registry { return b.healthRegistry }}
b.health = &healthSurface{
registry: func() *health.Registry { return b.healthRegistry },
inFlight: func() int {
if b.d == nil {
return -1
}
return b.d.InFlight()
},
}
addr := b.cfg.Health.Listen
if err := b.serveHealth(ctx, addr, b.health.handler(), "daemon health"); err != nil {
b.log.Error("health listener failed", "addr", addr, "err", err)
+7
View File
@@ -123,6 +123,13 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
return 0
}
if recovering, err := resumeUpdate(context.Background()); err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
} else if recovering {
return 0
}
root, cancelRoot := context.WithCancel(context.Background())
ctx, stop := signal.NotifyContext(root, os.Interrupt, syscall.SIGTERM)
defer stop()
+32
View File
@@ -0,0 +1,32 @@
package archied
import (
"flag"
"fmt"
"io"
"strings"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
func RunReleaseChannel(args []string, in io.Reader, out, stderr io.Writer) int {
flags := flag.NewFlagSet("select-release", flag.ContinueOnError)
flags.SetOutput(stderr)
channel := flags.String("channel", "stable", "stable, next, or exact-pin")
pin := flags.String("pin", "", "exact release version")
if err := flags.Parse(args); err != nil {
return 1
}
data, err := io.ReadAll(in)
if err != nil {
fmt.Fprintln(stderr, err)
return 1
}
version, err := releaseupdate.SelectRelease(strings.Fields(string(data)), *channel, *pin)
if err != nil {
fmt.Fprintln(stderr, err)
return 1
}
fmt.Fprintln(out, version)
return 0
}
+150
View File
@@ -0,0 +1,150 @@
package archied
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/BurntSushi/toml"
"golang.org/x/sys/unix"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// RunUpdateTopology observes the host using the candidate's topology contract.
func RunUpdateTopology(args []string, out, stderr io.Writer) int {
flags := flag.NewFlagSet("update-topology", flag.ContinueOnError)
flags.SetOutput(stderr)
configPath := flags.String("config", "", "bootstrap config file")
releasePath := flags.String("release", "", "release manifest")
if err := flags.Parse(args); err != nil {
return 1
}
if err := checkUpdateTopology(*configPath, *releasePath, out); err != nil {
fmt.Fprintln(stderr, err)
return 1
}
return 0
}
func checkUpdateTopology(configPath, releasePath string, out io.Writer) error {
data, err := os.ReadFile(releasePath)
if err != nil {
return err
}
var manifest struct {
Required releaseupdate.Topology `json:"required_topology"`
}
if err := json.Unmarshal(data, &manifest); err != nil {
return err
}
if len(manifest.Required.Units) == 0 {
return errors.New("release has no required_topology")
}
for _, unit := range manifest.Required.Units {
if !regexp.MustCompile(`^archie[a-z0-9-]*$`).MatchString(unit) {
return fmt.Errorf("invalid release unit %q", unit)
}
}
data, err = os.ReadFile(configPath)
if err != nil {
return err
}
var document map[string]any
if err := toml.Unmarshal(data, &document); err != nil {
return fmt.Errorf("observe topology: %w", err)
}
sections := make(map[string]bool)
for _, section := range manifest.Required.ConfigSections {
sections[section] = hasConfigSection(document, section)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
output, observeErr := exec.CommandContext(ctx, "systemctl", "--user", "list-unit-files", "archie*.service", "--no-legend", "--no-pager").Output()
units := observedUnits(output, observeErr)
plan := manifest.Required.MigrationPlan(units, sections)
if len(plan) != 0 {
fmt.Fprintln(out, "Required migration, in order:")
for _, step := range plan {
fmt.Fprintln(out, " -", step)
}
if observeErr != nil {
return fmt.Errorf("topology unknown; apply the printed migration before retrying: %w", observeErr)
}
return errors.New("refusing partial installation; apply the printed migration before retrying")
}
return nil
}
func hasConfigSection(document map[string]any, section string) bool {
for part := range strings.SplitSeq(section, ".") {
next, ok := document[part].(map[string]any)
if !ok {
return false
}
document = next
}
return true
}
func updateStateDir() string {
if dir := os.Getenv("ARCHIE_UPDATE_STATE_DIR"); dir != "" {
return dir
}
dir := os.Getenv("XDG_STATE_HOME")
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".local", "state")
}
return filepath.Join(dir, "archie", "update")
}
// Recovery runs independently of the daemon unit: it must be able to stop that
// unit and replace its executable without systemd killing the recovery process.
func resumeUpdate(ctx context.Context) (bool, error) {
journal := filepath.Join(updateStateDir(), "transaction")
if _, err := os.Stat(journal); errors.Is(err, os.ErrNotExist) {
return false, nil
} else if err != nil {
return false, err
}
lock, err := os.OpenFile(filepath.Join(updateStateDir(), "lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return false, err
}
defer lock.Close()
if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB); errors.Is(err, unix.EWOULDBLOCK) {
return false, nil
} else if err != nil {
return false, err
}
defer func() { _ = unix.Flock(int(lock.Fd()), unix.LOCK_UN) }()
cmd := exec.CommandContext(ctx, "systemd-run", "--user", "--collect", "--quiet", "--unit=archied-update-recovery", "--setenv=ARCHIE_UPDATE_STATE_DIR="+updateStateDir(), filepath.Join(journal, "watchdog"), "--boot-recover")
if output, err := cmd.CombinedOutput(); err != nil {
return false, fmt.Errorf("schedule update recovery: %w: %s", err, output)
}
return true, nil
}
func observedUnits(output []byte, err error) map[string]bool {
units := make(map[string]bool)
if err != nil {
return units
}
for line := range strings.SplitSeq(string(output), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 && fields[1] != "masked" {
units[strings.TrimSuffix(fields[0], ".service")] = true
}
}
return units
}
+117
View File
@@ -0,0 +1,117 @@
package archied
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"regexp"
"time"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/app/servicekit"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/secret"
)
type imageChange struct {
Previous string `json:"previous"`
Candidate string `json:"candidate"`
}
// RunUpdateImage journals and switches the control-plane image policy. It only
// changes the image field, preserving concurrent edits to unrelated settings.
func RunUpdateImage(args []string, stderr io.Writer) int {
flags := flag.NewFlagSet("update-image", flag.ContinueOnError)
flags.SetOutput(stderr)
configPath := flags.String("config", "", "bootstrap config")
journal := flags.String("journal", "", "transaction directory")
candidate := flags.String("prepare", "", "candidate image digest")
rollback := flags.Bool("rollback", false, "restore the prior image")
if err := flags.Parse(args); err != nil {
return 1
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := updateImage(ctx, *configPath, *journal, *candidate, *rollback); err != nil {
fmt.Fprintln(stderr, err)
return 1
}
return 0
}
func updateImage(ctx context.Context, configPath, journal, candidate string, rollback bool) error {
_, doc, err := servicekit.Resolve(slog.New(slog.DiscardHandler), configPath, "")
if err != nil {
return err
}
client, cleanup, err := servicekit.StateStoreClient(presence.Daemon, doc.Config.Services, secret.NewRegistry())
if err != nil {
return err
}
defer cleanup()
rpc := client.ControlPlane()
response, err := rpc.Query(ctx, &pb.QueryRequest{Kind: controlplane.ContainerRuntimePoliciesKind})
if err != nil {
return err
}
var policy map[string]json.RawMessage
if err := json.Unmarshal(response.Resource.ValueJson, &policy); err != nil {
return err
}
var current string
if err := json.Unmarshal(policy["image"], &current); err != nil {
return err
}
path := filepath.Join(journal, "image.json")
if candidate != "" {
return prepareImageChange(path, current, candidate)
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
var change imageChange
if err := json.Unmarshal(data, &change); err != nil {
return err
}
expected, desired := change.Previous, change.Candidate
if rollback {
expected, desired = desired, expected
}
if current == desired {
return nil
}
if current != expected {
return errors.New("image policy changed during update; refusing to overwrite it")
}
policy["image"], err = json.Marshal(desired)
if err != nil {
return err
}
data, err = json.Marshal(policy)
if err != nil {
return err
}
_, err = rpc.Command(ctx, &pb.CommandRequest{Kind: controlplane.ContainerRuntimePoliciesKind, Command: "replace", ValueJson: data, ExpectedVersion: response.Resource.Version, Actor: "self-update", Source: "installer", RequestId: fmt.Sprintf("self-update-%x-%d", sha256.Sum256(data), response.Resource.Version)})
return err
}
func prepareImageChange(path, current, candidate string) error {
if !regexp.MustCompile(`^([a-zA-Z0-9./:_-]+@)?sha256:[a-f0-9]{64}$`).MatchString(candidate) {
return errors.New("candidate image must be pinned by digest")
}
data, err := json.Marshal(imageChange{Previous: current, Candidate: candidate})
if err != nil {
return err
}
return os.WriteFile(path, data, 0o600)
}
+75
View File
@@ -0,0 +1,75 @@
package archied
import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"golang.org/x/sys/unix"
)
func TestUpdateTopologyRefusal(t *testing.T) {
root := t.TempDir()
manifest := filepath.Join(root, "release.json")
config := filepath.Join(root, "config.toml")
writeUpdateFixture(t, manifest, `{"required_topology":{"units":["archie-state-store","archie-gateway","archied"],"config_sections":["services.state","services.gateway"]}}`)
writeUpdateFixture(t, config, "[services.state]\ntarget='localhost:9090'\n")
writeUpdateFixture(t, filepath.Join(root, "systemctl"), "#!/bin/sh\nprintf 'archied.service enabled enabled\\n'\n")
t.Setenv("PATH", root+":"+os.Getenv("PATH"))
var output bytes.Buffer
if err := checkUpdateTopology(config, manifest, &output); err == nil {
t.Fatal("partial topology accepted")
}
for _, missing := range []string{"configure [services.gateway]", "install and enable archie-state-store.service", "install and enable archie-gateway.service"} {
if !strings.Contains(output.String(), missing) {
t.Fatalf("missing step %q: %s", missing, output.String())
}
}
}
func TestResumeUpdate(t *testing.T) {
for _, active := range []bool{false, true} {
t.Run(map[bool]string{false: "interrupted", true: "live"}[active], func(t *testing.T) {
root := t.TempDir()
t.Setenv("ARCHIE_UPDATE_STATE_DIR", root)
if err := os.Mkdir(filepath.Join(root, "transaction"), 0o700); err != nil {
t.Fatal(err)
}
called := filepath.Join(root, "called")
writeUpdateFixture(t, filepath.Join(root, "systemd-run"), "#!/bin/sh\nprintf '%s\\n' \"$@\" > '"+called+"'\n")
t.Setenv("PATH", root+":"+os.Getenv("PATH"))
lock, err := os.OpenFile(filepath.Join(root, "lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
t.Fatal(err)
}
defer lock.Close()
if active {
if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil {
t.Fatal(err)
}
}
resumed, err := resumeUpdate(t.Context())
if err != nil || resumed == active {
t.Fatalf("resumed=%v err=%v", resumed, err)
}
if !active {
data, err := os.ReadFile(called)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "--boot-recover") {
t.Fatalf("not a rollback: %s", data)
}
}
})
}
}
func writeUpdateFixture(t *testing.T, path, data string) {
t.Helper()
if err := os.WriteFile(path, []byte(data), 0o700); err != nil {
t.Fatal(err)
}
}
+26 -4
View File
@@ -944,7 +944,7 @@ type taskDispatcher struct {
active int
slotsFree *sync.Cond
repoTail map[string]chan struct{}
wg sync.WaitGroup
pending int
}
// SetMaxConcurrency accepts a new global limit without a restart. Running
@@ -1004,7 +1004,16 @@ func (d *taskDispatcher) Submit(
d.mu.Unlock()
}
d.wg.Go(func() {
d.mu.Lock()
d.pending++
d.mu.Unlock()
go func() {
defer func() {
d.mu.Lock()
d.pending--
d.mu.Unlock()
d.slotsFree.Broadcast()
}()
if previous != nil {
<-previous
}
@@ -1021,11 +1030,15 @@ func (d *taskDispatcher) Submit(
}()
}
process(ctx, task)
})
}()
}
func (d *taskDispatcher) Wait() {
d.wg.Wait()
d.mu.Lock()
defer d.mu.Unlock()
for d.pending > 0 {
d.slotsFree.Wait()
}
}
func (d *Daemon) poll(ctx context.Context) {
@@ -2214,3 +2227,12 @@ func (d *Daemon) RemoveWorktree(owner, repo, identity string, issue int) error {
}
return trees.Cleanup(owner, repo, issue)
}
// InFlight counts the same submitted work that graceful shutdown waits for,
// including tasks waiting for a repository or concurrency slot.
func (d *Daemon) InFlight() int {
dispatcher := d.taskDispatcher()
dispatcher.mu.Lock()
defer dispatcher.mu.Unlock()
return dispatcher.pending
}
+39
View File
@@ -0,0 +1,39 @@
package daemon
import (
"context"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func TestDispatcherWaitIncludesQueuedWork(t *testing.T) {
dispatcher := newTaskDispatcher(1, nil)
started := make(chan struct{}, 2)
release := make(chan struct{})
process := func() { started <- struct{}{}; <-release }
for range 2 {
dispatcher.Submit(t.Context(), &workflow.Task{Owner: "o", Repo: "r"}, func(_ context.Context, _ *workflow.Task) { process() })
}
<-started
dispatcher.mu.Lock()
count := dispatcher.pending
dispatcher.mu.Unlock()
if count != 2 {
t.Fatalf("in-flight count=%d, want running and queued task", count)
}
done := make(chan struct{})
go func() { dispatcher.Wait(); close(done) }()
select {
case <-done:
t.Fatal("drain completed with pending work")
default:
}
close(release)
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("drain did not finish")
}
}
+54
View File
@@ -0,0 +1,54 @@
package releaseupdate
import (
"fmt"
"regexp"
"strings"
"golang.org/x/mod/semver"
)
// SelectRelease compares release versions, never git-describe strings. Exact
// pins still have to exist in the catalog; a pin cannot invent a release.
func SelectRelease(tags []string, channel, pin string) (string, error) {
if channel == "" {
channel = "stable"
}
if channel != "stable" && channel != "next" && channel != "exact-pin" {
return "", fmt.Errorf("unknown release channel %q", channel)
}
pin = strings.TrimPrefix(pin, "v")
if channel == "exact-pin" && !semver.IsValid("v"+pin) {
return "", fmt.Errorf("exact-pin requires a semantic version")
}
fullVersion := regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+([+-].*)?$`)
newest := ""
for _, tag := range tags {
tag = strings.TrimPrefix(tag, "refs/tags/")
tag = strings.TrimPrefix(tag, "archied/")
if !fullVersion.MatchString(tag) || !semver.IsValid(tag) {
continue
}
if !releaseMatchesChannel(tag, channel, pin) {
continue
}
if semver.Compare(tag, newest) > 0 {
newest = tag
}
}
if newest == "" {
return "", fmt.Errorf("no release found for channel %s (pin %s)", channel, pin)
}
return strings.TrimPrefix(newest, "v"), nil
}
func releaseMatchesChannel(tag, channel, pin string) bool {
switch channel {
case "stable":
return semver.Prerelease(tag) == ""
case "exact-pin":
return tag == "v"+pin
default:
return true
}
}
+24
View File
@@ -0,0 +1,24 @@
package releaseupdate
import "testing"
func TestSelectRelease(t *testing.T) {
tags := []string{"archied/v1.9.0", "v1.10.0", "archied/v2.0.0-rc.2", "v2.0.0-rc.10", "archie/v9.0.0", "nonsense"}
for _, tc := range []struct{ channel, pin, want string }{
{"stable", "", "1.10.0"},
{"", "", "1.10.0"},
{"next", "", "2.0.0-rc.10"},
{"exact-pin", "1.9.0", "1.9.0"},
{"exact-pin", "2.0.0-rc.2", "2.0.0-rc.2"},
{"exact-pin", "9.0.0", ""},
{"exact-pin", "", ""},
{"invalid", "", ""},
} {
t.Run(tc.channel+tc.pin, func(t *testing.T) {
got, err := SelectRelease(tags, tc.channel, tc.pin)
if got != tc.want || (err != nil) != (tc.want == "") {
t.Fatalf("got %q, %v; want %q", got, err, tc.want)
}
})
}
}
+10 -2
View File
@@ -19,13 +19,21 @@ 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.
type CommandCatalog struct{ Command []string }
type CommandCatalog struct {
Command []string
ReleaseChannel string
Pin string
}
func (c CommandCatalog) Check(ctx context.Context) (Snapshot, error) {
if len(c.Command) == 0 {
return Snapshot{}, fmt.Errorf("update check command is empty")
}
output, err := exec.CommandContext(ctx, c.Command[0], c.Command[1:]...).Output()
cmd := exec.CommandContext(ctx, c.Command[0], c.Command[1:]...)
if c.ReleaseChannel != "" {
cmd.Env = append(cmd.Environ(), "ARCHIE_UPDATE_RELEASE_CHANNEL="+c.ReleaseChannel, "ARCHIE_UPDATE_PIN="+c.Pin)
}
output, err := cmd.Output()
if err != nil {
return Snapshot{}, fmt.Errorf("run update check: %w", err)
}
+215
View File
@@ -0,0 +1,215 @@
package releaseupdate
import (
"archive/zip"
"crypto/sha256"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"golang.org/x/sys/unix"
)
func TestUpdateTransaction(t *testing.T) {
for _, scenario := range []string{"healthy", "checksum", "unsafe-path", "missing-digest", "busy", "lock", "unhealthy", "crash"} {
t.Run(scenario, func(t *testing.T) {
f := newUpdateFixture(t, scenario)
var lock *os.File
if scenario == "lock" {
var err error
lock, err = os.OpenFile(filepath.Join(f.state, "lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
t.Fatal(err)
}
defer lock.Close()
if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil {
t.Fatal(err)
}
fixtureWrite(t, filepath.Join(f.state, "holder"), "fixture-owner", 0o600)
}
args := []string{}
if scenario == "busy" {
args = append(args, "--auto")
}
output, err := f.run(t, f.installer, args...)
refusal := map[string]string{"checksum": "checksum mismatch", "unsafe-path": "unsafe archive path", "missing-digest": "digest-pinned", "busy": "work in flight", "lock": "fixture-owner"}[scenario]
if refusal != "" {
if err == nil || !strings.Contains(output, refusal) {
t.Fatalf("wanted %q refusal; err=%v output=%s", refusal, err, output)
}
f.assertVersion(t, "old")
return
}
if err != nil {
t.Fatalf("installer: %v\n%s", err, output)
}
f.assertVersion(t, "old") // Staging cannot mutate a running executable.
old, err := os.Open(filepath.Join(f.bin, "archied"))
if err != nil {
t.Fatal(err)
}
defer old.Close()
watchdog := filepath.Join(f.state, "transaction", "watchdog")
output, err = f.run(t, watchdog)
if scenario == "crash" {
if err == nil {
t.Fatal("expected injected crash")
}
f.env = append(f.env, "CRASH_AFTER=")
output, err = f.run(t, watchdog, "--boot-recover")
}
if err != nil {
t.Fatalf("watchdog: %v\n%s", err, output)
}
want := "old"
if scenario == "healthy" {
want = "new"
}
f.assertVersion(t, want)
data := make([]byte, 100)
n, _ := old.Read(data)
if !strings.Contains(string(data[:n]), "old") {
t.Fatal("promotion overwrote the open old inode")
}
if _, err := os.Stat(filepath.Join(f.state, "transaction")); !os.IsNotExist(err) {
t.Fatalf("journal not retired: %v", err)
}
})
}
}
type updateFixture struct {
bin, state, installer string
env []string
}
func fixtureWrite(t *testing.T, path, data string, mode os.FileMode) {
t.Helper()
if err := os.WriteFile(path, []byte(data), mode); err != nil {
t.Fatal(err)
}
}
func newUpdateFixture(t *testing.T, scenario string) updateFixture {
t.Helper()
root := t.TempDir()
bin, state, fake := filepath.Join(root, "bin"), filepath.Join(root, "state"), filepath.Join(root, "fake")
for _, dir := range []string{bin, state, fake} {
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
}
scripts, err := filepath.Abs("../../scripts")
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"archied", "archie-state-store", "archie-gateway", "archie-ui", "archie-messaging"} {
fixtureWrite(t, filepath.Join(bin, name), "#!/bin/bash\n# old\nexit 0\n", 0o755)
}
config := filepath.Join(root, "config.toml")
fixtureWrite(t, config, "[services.state]\n[services.gateway]\n", 0o600)
archive := makeUpdateArchive(t, root, scripts, scenario)
sum := sha256.Sum256(archive)
if scenario == "checksum" {
sum[0]++
}
fixtureWrite(t, filepath.Join(root, "SHA256SUMS"), fmt.Sprintf("%x archie-core-archied-v2.0.0-linux-amd64.zip\n", sum), 0o600)
fixtureWrite(t, filepath.Join(fake, "curl"), `#!/bin/bash
out=""
for ((i=1;i<=$#;i++)); do
if [ "${!i}" = -o ]; then j=$((i+1)); out="${!j}"; fi
case "${!i}" in
*/SHA256SUMS) source="$FIXTURE/SHA256SUMS" ;;
*.zip) source="$FIXTURE/archive.zip" ;;
esac
done
if [ -n "$out" ]; then cp "$source" "$out"; exit; fi
if [ "$SCENARIO" = unhealthy ]; then exit 22; fi
busy=0
[ "$SCENARIO" = busy ] && busy=1
printf '{"status":"ok","version":"2.0.0","in_flight":%s}\n' "$busy"
`, 0o755)
for _, name := range []string{"systemctl", "systemd-run", "docker"} {
fixtureWrite(t, filepath.Join(fake, name), "#!/bin/bash\nexit 0\n", 0o755)
}
fixtureWrite(t, filepath.Join(fake, "git"), "#!/bin/bash\necho unexpected-git >&2\nexit 98\n", 0o755)
fixtureWrite(t, filepath.Join(fake, "mv"), `#!/bin/bash
/bin/mv "$@" || exit
if [ -n "$CRASH_AFTER" ] && [[ "$*" == *".archied.new"* ]]; then kill -KILL "$PPID"; fi
`, 0o755)
return updateFixture{bin: bin, state: state, installer: filepath.Join(scripts, "archie-update-install"), env: append(os.Environ(),
"PATH="+fake+":"+os.Getenv("PATH"), "FIXTURE="+root, "SCENARIO="+scenario,
"ARCHIE_BIN_DIR="+bin, "ARCHIE_CONFIG_PATH="+config, "ARCHIE_UPDATE_STATE_DIR="+state,
"ARCHIE_UPDATE_DAEMON_PREVIOUS=1.0.0", "ARCHIE_UPDATE_DAEMON_VERSION=2.0.0",
"ARCHIE_UPDATE_AGENT_PREVIOUS=1.0.0", "ARCHIE_UPDATE_AGENT_VERSION="+map[bool]string{true: "2.0.0"}[scenario == "missing-digest"],
"ARCHIE_UPDATE_HEALTH_TIMEOUT=1", "ARCHIE_UPDATE_OBSERVE_SECONDS=0", "ARCHIE_UPDATE_POLL_INTERVAL=0.01",
"ARCHIE_UPDATE_STATE_STORE_TARGET=", "CRASH_AFTER="+map[bool]string{true: "archied"}[scenario == "crash"],
)}
}
func makeUpdateArchive(t *testing.T, root, scripts, scenario string) []byte {
t.Helper()
file, err := os.Create(filepath.Join(root, "archive.zip"))
if err != nil {
t.Fatal(err)
}
z := zip.NewWriter(file)
files := map[string]string{"release.json": `{"required_topology":{"units":["archie-state-store","archie-gateway","archie-ui","archie-messaging","archied"],"config_sections":["services.state","services.gateway"]},"agent_image":"mutable:latest"}`}
for _, name := range []string{"archied", "archie-state-store", "archie-gateway", "archie-ui", "archie-messaging"} {
files[name] = "#!/bin/bash\n# new\nif [ \"$1\" = -version ]; then echo '" + name + " 2.0.0'; fi\nexit 0\n"
}
for _, name := range []string{"archie-update-install", "archie-update-watchdog", "archie-update-check"} {
data, err := os.ReadFile(filepath.Join(scripts, name))
if err != nil {
t.Fatal(err)
}
files[name] = string(data)
}
if scenario == "unsafe-path" {
files["../escape"] = "escape"
}
for name, body := range files {
header := &zip.FileHeader{Name: "archie-core-archied-v2.0.0-linux-amd64/" + name, Method: zip.Deflate}
header.SetMode(0o755)
w, err := z.CreateHeader(header)
if err != nil {
t.Fatal(err)
}
if _, err := w.Write([]byte(body)); err != nil {
t.Fatal(err)
}
}
if err := z.Close(); err != nil {
t.Fatal(err)
}
if err := file.Close(); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(file.Name())
if err != nil {
t.Fatal(err)
}
return data
}
func (f updateFixture) run(t *testing.T, path string, args ...string) (string, error) {
t.Helper()
cmd := exec.CommandContext(t.Context(), path, args...)
cmd.Env = f.env
data, err := cmd.CombinedOutput()
return string(data), err
}
func (f updateFixture) assertVersion(t *testing.T, want string) {
t.Helper()
data, err := os.ReadFile(filepath.Join(f.bin, "archied"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(data), "# "+want) {
t.Fatalf("wanted %s executable: %s", want, data)
}
}
+25
View File
@@ -0,0 +1,25 @@
package releaseupdate
import "fmt"
type Topology struct {
Units []string `json:"units"`
ConfigSections []string `json:"config_sections"`
}
// MigrationPlan preserves the release's dependency order. Unknown observations
// require every step to be checked manually rather than assuming a partial host.
func (t Topology) MigrationPlan(units, sections map[string]bool) []string {
var steps []string
for _, section := range t.ConfigSections {
if !sections[section] {
steps = append(steps, fmt.Sprintf("configure [%s]", section))
}
}
for _, unit := range t.Units {
if !units[unit] {
steps = append(steps, fmt.Sprintf("install and enable %s.service", unit))
}
}
return steps
}
+25
View File
@@ -0,0 +1,25 @@
package releaseupdate
import (
"reflect"
"testing"
)
func TestMigrationPlan(t *testing.T) {
topology := Topology{Units: []string{"state", "gateway", "ui", "daemon"}, ConfigSections: []string{"services.state"}}
for _, tc := range []struct {
name string
units, sections map[string]bool
want []string
}{
{"unknown", nil, nil, []string{"configure [services.state]", "install and enable state.service", "install and enable gateway.service", "install and enable ui.service", "install and enable daemon.service"}},
{"missing", map[string]bool{"state": true, "daemon": true}, map[string]bool{"services.state": true}, []string{"install and enable gateway.service", "install and enable ui.service"}},
{"complete", map[string]bool{"state": true, "gateway": true, "ui": true, "daemon": true}, map[string]bool{"services.state": true}, nil},
} {
t.Run(tc.name, func(t *testing.T) {
if got := topology.MigrationPlan(tc.units, tc.sections); !reflect.DeepEqual(got, tc.want) {
t.Fatalf("got %v, want %v", got, tc.want)
}
})
}
}