feat(releaseupdate): archied update check finds releases through go-selfupdate; archie-update-check is deleted

This commit is contained in:
sam committed 2026-10-07 01:12:11 +11:00
1 parent ceb25b95f7
commit 0b9769dbf2
15 files changed
+257 -385

No files matched your search

-32
View File
@@ -1,32 +0,0 @@
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
}
+48
View File
@@ -0,0 +1,48 @@
package archied
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// RunUpdate serves `archied update check`, printing the release snapshot as
// JSON. The channel defaults to the environment the installer passes on.
func RunUpdate(args []string, out, stderr io.Writer) int {
if len(args) == 0 || args[0] != "check" {
fmt.Fprintln(stderr, "usage: archied update check [-channel stable|next|exact-pin] [-pin version]")
return 2
}
flags := flag.NewFlagSet("update check", flag.ContinueOnError)
flags.SetOutput(stderr)
channel := flags.String("channel", envOr("ARCHIE_UPDATE_RELEASE_CHANNEL", "stable"), "stable, next, or exact-pin")
pin := flags.String("pin", os.Getenv("ARCHIE_UPDATE_PIN"), "exact release version")
if err := flags.Parse(args[1:]); err != nil {
return 2
}
catalog := releaseupdate.GitHubCatalog{Channel: func(context.Context) (string, string, error) { return *channel, *pin, nil }}
snapshot, err := catalog.Check(context.Background())
if err != nil {
fmt.Fprintln(stderr, err)
return 1
}
encoder := json.NewEncoder(out)
encoder.SetIndent("", " ")
if err := encoder.Encode(snapshot); err != nil {
fmt.Fprintln(stderr, err)
return 1
}
return 0
}
func envOr(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
@@ -118,23 +118,26 @@ type UpdateSettings struct {
Pin string `json:"pin" title:"Pinned version" doc:"The version exact-pin installs."`
}
// UpdateService runs the stored update commands, reading them on every call.
// statePath keeps each recipient's deferrals; healthURL reaches the installer.
// UpdateService checks GitHub on the stored release channel and installs
// through the script beside this binary. statePath keeps each recipient's
// deferrals; healthURL reaches the installer.
func UpdateService(reader ResourceReader, statePath, healthURL string) *releaseupdate.Service {
commands := releaseupdate.SettingsCommands{Load: updateCommands(reader), HealthURL: healthURL}
return &releaseupdate.Service{Catalog: commands, Installer: commands, StatePath: statePath, InstallType: installtype.Type()}
return &releaseupdate.Service{
Catalog: releaseupdate.GitHubCatalog{Channel: updateChannel(reader)},
Installer: releaseupdate.ScriptInstaller{HealthURL: healthURL},
StatePath: statePath,
InstallType: installtype.Type(),
}
}
// updateCommands reads the update-settings resource. An unstored kind is the
// updateChannel reads the update-settings resource. An unstored kind is the
// stable channel.
func updateCommands(reader ResourceReader) func(context.Context) (releaseupdate.Commands, error) {
return func(ctx context.Context) (releaseupdate.Commands, error) {
func updateChannel(reader ResourceReader) func(context.Context) (string, string, error) {
return func(ctx context.Context) (string, string, error) {
settings := UpdateSettings{Channel: "stable"}
if _, _, err := reader.Query(ctx, UpdateSettingsKind, func(value []byte) error {
_, _, err := reader.Query(ctx, UpdateSettingsKind, func(value []byte) error {
return json.Unmarshal(value, &settings)
}); err != nil {
return releaseupdate.Commands{}, err
}
return releaseupdate.ScriptCommands(settings.Channel, settings.Pin), nil
})
return settings.Channel, settings.Pin, err
}
}
-43
View File
@@ -2,7 +2,6 @@ package releaseupdate
import (
"fmt"
"regexp"
"strings"
"golang.org/x/mod/semver"
@@ -19,45 +18,3 @@ func ValidateChannel(channel, pin string) error {
}
return nil
}
// 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 err := ValidateChannel(channel, pin); err != nil {
return "", err
}
pin = strings.TrimPrefix(pin, "v")
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
@@ -1,24 +0,0 @@
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)
}
})
}
}
+15 -77
View File
@@ -19,31 +19,6 @@ import (
// 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.
type CommandCatalog struct {
Command []string
Env []string
}
func (c CommandCatalog) Check(ctx context.Context) (Snapshot, error) {
if len(c.Command) == 0 {
return Snapshot{}, fmt.Errorf("update check command is empty")
}
cmd := exec.CommandContext(ctx, c.Command[0], c.Command[1:]...)
cmd.Env = append(cmd.Environ(), c.Env...)
output, err := cmd.Output()
if err != nil {
return Snapshot{}, fmt.Errorf("run update check: %w", err)
}
var snapshot Snapshot
if err := json.Unmarshal(output, &snapshot); err != nil {
return Snapshot{}, fmt.Errorf("decode update check output: %w", err)
}
return snapshot, nil
}
// CommandInstaller runs the deployment's install command. HealthURL is
// passed as ARCHIE_HEALTH_URL when set.
type CommandInstaller struct {
@@ -137,67 +112,30 @@ func componentVersions(snapshot Snapshot) map[string]Component {
// ErrNotConfigured is returned when the step's command is unset.
var ErrNotConfigured = errors.New("updates are not configured")
// Commands is what a deployment runs to check for and install updates. Env
// is added to the check's environment.
type Commands struct {
Check []string
Install []string
Env []string
}
// ScriptCommands runs the update scripts a release installs beside this
// binary, selecting releases from channel. Only these scripts ever run, so a
// setting cannot name an arbitrary program. A missing script is unset.
func ScriptCommands(channel, pin string) Commands {
exe, err := os.Executable()
if err != nil {
return Commands{}
}
script := func(name string) []string {
path := filepath.Join(filepath.Dir(exe), name)
if info, err := os.Stat(path); err != nil || info.Mode()&0o111 == 0 {
return nil
}
return []string{path}
}
return Commands{
Check: script("archie-update-check"),
Install: script("archie-update-install"),
Env: []string{"ARCHIE_UPDATE_RELEASE_CHANNEL=" + channel, "ARCHIE_UPDATE_PIN=" + pin},
}
}
// SettingsCommands is both Catalog and Installer. It loads Commands on every
// call so an edited setting applies without a restart.
type SettingsCommands struct {
Load func(context.Context) (Commands, error)
// ScriptInstaller runs the install script a release places beside this binary.
type ScriptInstaller struct {
HealthURL string
}
func (s SettingsCommands) Check(ctx context.Context) (Snapshot, error) {
commands, err := s.Load(ctx)
func (s ScriptInstaller) path() string {
exe, err := os.Executable()
if err != nil {
return Snapshot{}, err
return ""
}
if len(commands.Check) == 0 {
return Snapshot{}, ErrNotConfigured
path := filepath.Join(filepath.Dir(exe), "archie-update-install")
if info, err := os.Stat(path); err != nil || info.Mode()&0o111 == 0 {
return ""
}
return CommandCatalog{Command: commands.Check, Env: commands.Env}.Check(ctx)
return path
}
func (s SettingsCommands) Install(ctx context.Context, snapshot Snapshot, meta InstallMeta, progress func(string)) (Result, error) {
commands, err := s.Load(ctx)
if err != nil {
return Result{}, err
}
if len(commands.Install) == 0 {
func (s ScriptInstaller) Install(ctx context.Context, snapshot Snapshot, meta InstallMeta, progress func(string)) (Result, error) {
path := s.path()
if path == "" {
return Result{}, ErrNotConfigured
}
return CommandInstaller{Command: commands.Install, HealthURL: s.HealthURL}.Install(ctx, snapshot, meta, progress)
return CommandInstaller{Command: []string{path}, HealthURL: s.HealthURL}.Install(ctx, snapshot, meta, progress)
}
// Installable reports whether an install command is set.
func (s SettingsCommands) Installable(ctx context.Context) bool {
commands, err := s.Load(ctx)
return err == nil && len(commands.Install) != 0
}
// Installable reports whether the install script is present.
func (s ScriptInstaller) Installable(context.Context) bool { return s.path() != "" }
+114
View File
@@ -0,0 +1,114 @@
package releaseupdate
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/creativeprojects/go-selfupdate"
"github.com/samcharles93/archie-core/internal/buildinfo"
)
// ReleaseSlug is the repository releases are published to.
const ReleaseSlug = "samcharles93/archie-core"
const changelogURL = "https://github.com/" + ReleaseSlug + "/blob/main/CHANGELOG.md"
// buildSuffix is the git-describe tail of an untagged build (1.7.0-4-g0736708).
var buildSuffix = regexp.MustCompile(`-[0-9]+-g[0-9a-f]+$`)
// GitHubCatalog finds the newest release on the selected channel that ships a
// linux-amd64 zip, and reports it against this build. Only one version covers
// every component, so the daemon and agent are offered the same release.
type GitHubCatalog struct {
// Channel returns the release channel and pin in force.
Channel func(context.Context) (channel, pin string, err error)
}
func (c GitHubCatalog) Check(ctx context.Context) (Snapshot, error) {
channel, pin, err := c.Channel(ctx)
if err != nil {
return Snapshot{}, err
}
if channel == "" {
channel = "stable"
}
release, err := detectRelease(ctx, channel, pin)
if err != nil {
return Snapshot{}, err
}
component := func(id, label, installed string) Component {
return Component{
ID: id, Label: label,
Installed: installed, Available: release.Version(),
Reference: release.AssetName, Changelog: changelogURL,
}
}
return Snapshot{Components: []Component{
component("daemon", "Gateway", installedVersion(buildinfo.Version)),
component("agent", "Runtime", installedAgent()),
}}, nil
}
// detectRelease resolves channel to one published release. A release with no
// zip for this platform is not installable, so it is never offered.
func detectRelease(ctx context.Context, channel, pin string) (*selfupdate.Release, error) {
if err := ValidateChannel(channel, pin); err != nil {
return nil, err
}
updater, err := selfupdate.NewUpdater(selfupdate.Config{
Validator: &selfupdate.ChecksumValidator{UniqueFilename: "SHA256SUMS"},
Filters: []string{`-linux-amd64\.zip$`},
OS: "linux",
Arch: "amd64",
Prerelease: channel == "next",
})
if err != nil {
return nil, err
}
repository := selfupdate.ParseSlug(ReleaseSlug)
var (
release *selfupdate.Release
found bool
)
if channel == "exact-pin" {
release, found, err = updater.DetectVersion(ctx, repository, "v"+strings.TrimPrefix(pin, "v"))
} else {
release, found, err = updater.DetectLatest(ctx, repository)
}
if err != nil {
return nil, fmt.Errorf("find releases: %w", err)
}
if !found {
return nil, errors.New("no published release with a linux-amd64 zip matches the channel")
}
return release, nil
}
func installedVersion(version string) string {
return buildSuffix.ReplaceAllString(version, "")
}
// installedAgent is the image the installer last switched to, recorded in a
// sidecar beside the binaries; without one it is the runtime this release was
// cut with. A malformed sidecar is unknown, not guessed.
func installedAgent() string {
exe, err := os.Executable()
if err != nil {
return installedVersion(buildinfo.Runtime)
}
data, err := os.ReadFile(filepath.Join(filepath.Dir(exe), "archie-agent.version"))
if errors.Is(err, os.ErrNotExist) {
return installedVersion(buildinfo.Runtime)
}
version := strings.TrimSpace(string(data))
if err != nil || strings.ContainsAny(version, " \n") || ValidateChannel("exact-pin", version) != nil {
return ""
}
return installedVersion(version)
}
+1 -1
View File
@@ -161,7 +161,7 @@ func makeUpdateArchive(t *testing.T, root, scripts, scenario string) []byte {
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"} {
for _, name := range []string{"archie-update-install", "archie-update-watchdog"} {
data, err := os.ReadFile(filepath.Join(scripts, name))
if err != nil {
t.Fatal(err)