Self-update from Go
Give a Go CLI an upgrade command and a once-a-day update banner that read its channel on the Updater, with checksums, rollback for daemons, and an offline test server.
git.prod.wtf/xeonr/updater/go-sdk is the Go package a CLI embeds to update
itself from the Updater. It reads the
channel manifest,
installs what it names over the running executable, and gives you the
upgrade command and the "newer version available" banner ready-made.
Install
go get git.prod.wtf/xeonr/updater/[email protected]The module is public (source),
so it needs no credentials and no GOPRIVATE.
It depends on cobra, Masterminds/semver and golang.org/x/term, and nothing
else.
Its platform package (git.prod.wtf/xeonr/updater/go-sdk/platform, from
v0.2.0) is the Updater's naming contract for release files: the platform ids
and the binary and archive filenames
Distribute a CLI
describes. The Updater and updater-cli both use it, so a build script in Go
can name its files with it rather than by hand.
Set up
package main
import (
"os"
selfupdate "git.prod.wtf/xeonr/updater/go-sdk"
"github.com/spf13/cobra"
)
// Stamped at build time; see "Stamp the version" below.
var version = "dev"
func main() {
u := selfupdate.New(selfupdate.Config{
AppURL: "https://updater.xeonr.io/<bucket>",
Version: version,
})
root := &cobra.Command{Use: "burrow", Version: version}
root.AddCommand(selfupdate.UpgradeCmd(u, "burrow"))
if err := root.Execute(); err != nil {
os.Exit(1)
}
}Config field | Meaning |
|---|---|
AppURL | The app: https://updater.xeonr.io/<bucket>. Empty leaves the updater unconfigured, and upgrade says so. |
Target | The target to follow. Defaults to stable. |
Version | This build's version. dev, empty or anything that is not semver counts as a development build, and every release is newer than it. |
Token | An updater token, for a private target. |
HTTPClient | The client for every request. Defaults to a plain http.Client. |
Logger | A *slog.Logger for warnings. Defaults to none. |
StateFile | Turns on the crash-loop guard. Leave it empty in a CLI. |
SanityArgs | What a downloaded binary is run with before it is installed. Defaults to --version. |
Executable | The binary to replace. Defaults to the running executable; tests point it at a scratch file. |
The upgrade command
UpgradeCmd(u, name) returns a cobra command named upgrade:
| Flag | Effect |
|---|---|
--check | Say whether a newer version exists, and install nothing. |
--force | Reinstall even when already on the latest version. |
--prerelease | Follow the prerelease target instead. |
$ burrow upgrade
current: 0.9.1
latest: 0.9.2 (stable)
Downloading https://updater.xeonr.io/<bucket>/update/stable/darwin-arm64/burrow-darwin-arm64 …
Upgraded to 0.9.2.An install goes like this:
- The command downloads the raw binary for this platform. If that fails, it downloads the archive and takes the executable out of it.
- It keeps the file only if it matches the manifest's SHA-256. The manifest's URLs may point at any host, but only bytes with that digest are installed.
- It runs the new binary once with
--version, and stops if that does not exit 0. - It renames the new binary over the old one. A symlink to the binary, such
as one in a Homebrew
bin/, keeps pointing where it did.
A failure at any step leaves the installed binary as it was.
When the binary's directory is not writable, such as /usr/local/bin, the
command re-runs itself under sudo on macOS and Linux. It does that only
when someone is at the terminal to answer the password prompt. Otherwise, and
always on Windows, it stops and says what to do instead: run as a user who can
write there, or reinstall somewhere you own.
Stamp the version
A release build has to know its own version, or it reports dev and is
offered every release forever. Set it with the linker:
go build -ldflags "-X main.version=0.9.2" ./cmd/burrowXeonr's shared CI stamps
main.version on every type: cli build, so a var version in package
main needs nothing more. If the variable lives elsewhere, name it with the
app's version_var setting.
The step that runs the new binary with --version needs that flag to exit 0.
Setting Version on the cobra root command provides it. A CLI with a
version subcommand instead can pass SanityArgs: []string{"version"}.
The update banner
Nudge prints one line to stderr when a newer release exists:
burrow 0.9.2 is available (current 0.9.1) — run `burrow upgrade` to update.root.PersistentPostRun = func(cmd *cobra.Command, _ []string) {
selfupdate.Nudge(cmd.Context(), u, os.Stderr, configDir)
}It asks the channel at most once a day, caching the answer in
<configDir>/update-check.json. Only that daily check can hold a command
up, for at most a second. If the channel has not answered by then, the
previous answer stands and the check is retried an hour later. Use v0.1.1 or
later: v0.1.0 waited only 200 ms, so on a real network the answer was never
saved and the banner never appeared.
It prints nothing for a development build, when CI is set, or when stderr
is not a terminal, so scripts and pipelines never see it. To let users turn it
off, check your own setting before calling it.
Private targets
A private target needs an updater token whose targets claim names it. Pass it
as Token:
u := selfupdate.New(selfupdate.Config{
AppURL: "https://updater.xeonr.io/<bucket>",
Target: "internal",
Version: version,
Token: os.Getenv("BURROW_TOKEN"),
})The token goes as a bearer header, and only to the app's own host. A download URL on another host never receives it.
Check and Apply directly
UpgradeCmd and Nudge are built on three calls you can use yourself:
rel, err := u.Check(ctx) // nil when this build is current
if err != nil || rel == nil {
return err
}
err = u.Apply(ctx, rel)Check answers nil, nil when nothing is newer. Latest answers the
published release without comparing it to anything. Errors you can test for:
| Error | Meaning |
|---|---|
selfupdate.ErrNoRelease | Nothing is published on this target for this platform. |
selfupdate.ErrNotConfigured | AppURL is empty. |
SetAppURL and SetTarget change the channel after New, for a channel that
comes from a flag.
Rollback for daemons
A process that updates itself unattended can install a release that starts
and then crashes. With StateFile set, the SDK keeps the previous binary as
<binary>.old and remembers what it installed:
func main() {
u := selfupdate.New(selfupdate.Config{
AppURL: "https://updater.xeonr.io/<bucket>",
Version: version,
StateFile: filepath.Join(dataDir, "selfupdate.json"),
})
if err := u.Guard(); errors.Is(err, selfupdate.ErrRolledBack) {
os.Exit(1) // your supervisor restarts into the restored binary
}
// … once the process has proved it works, such as its first successful connection:
_ = u.MarkHealthy()
}Call Guard first thing in main. A freshly installed binary that starts
twice without reaching MarkHealthy is rolled back on its third start, and
its release is held back. Check then skips that release until the channel
publishes a newer one, and upgrade installs it only with --force. A binary
that fails its --version run is held back straight away.
Leave StateFile empty in an interactive CLI. Without MarkHealthy calls,
its third run would count as a crash loop.
Testing
selfupdatetest.Issuer is an httptest server that serves the manifest
routes, binaries and archives for releases you publish to it. Tests that use
it need no network.
import "git.prod.wtf/xeonr/updater/go-sdk/selfupdatetest"
func TestUpgrade(t *testing.T) {
iss := selfupdatetest.NewIssuer(t)
iss.Publish(selfupdatetest.Release{
App: "burrow",
Version: "0.9.2",
Binary: selfupdatetest.Script("burrow", "0.9.2"),
})
u := selfupdate.New(selfupdate.Config{
AppURL: iss.AppURL(),
Version: "0.9.1",
Executable: scratchCopy, // never the test binary itself
})
// …
}| Method | Use |
|---|---|
RequireToken(target, token) | Make a target private. |
SetFault(...) | Make the raw binary 404 or fail its checksum, to exercise the archive fallback. |
SetDelay(d) | Slow every response, to test timeouts. |
Requests() | What was asked, with any credentials sent. |
Script builds a shell-script "binary" that answers --version, so tests that
install one run on macOS and Linux only. Point Config.Executable at a scratch
file, so Apply replaces that and not the test binary.