updater

package module
v0.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: AGPL-3.0 Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

updater

ci codecov

Auto-updater plugin for the Pilot Protocol daemon. Polls the GitHub releases endpoint hourly, hot-swaps the daemon, pilotctl, and gateway binaries when a newer SemVer tag appears, and exits so the supervisor restarts the new copy.

Install

import "github.com/pilot-protocol/updater"

Usage

u := updater.New(updater.Config{
    Repo:          "pilot-protocol/pilotprotocol",
    InstallDir:    "/home/user/.pilot/bin",
    Version:       "v1.10.5",
    CheckInterval: 1 * time.Hour,
    StatePath:     "/home/user/.pilot/auto-update.json", // {"enabled": bool}
})
u.Start()

One-shot check, for pilotctl update and similar commands:

u := updater.New(updater.Config{
    Repo:       "pilot-protocol/pilotprotocol",
    InstallDir: "/home/user/.pilot/bin",
    StatusPath: "/home/user/.pilot/update-state.json", // record the run
})
if err := u.RunOnce(); err != nil {
    // The check failed: report it and exit non-zero.
}
st := u.LastStatus() // st.LastResult is "up_to_date" or "updated"
if st.RestartError != "" {
    // Installed, but the daemon still runs the old version. The message
    // says how to restart it.
}

RunOnce returns the check's error. It never exits the calling process. If the release replaced pilot-updater, the daemon is still restarted onto the new binaries. A running updater service switches to its new binary the next time its service manager restarts it.

A RunOnce caller writes the status file only when it sets StatusPath (or StatePath); otherwise only LastStatus() has the result. pilotctl update does not do this yet. As of web4 main on 2026-09-24, cmd/pilotctl/updates.go sets neither path and ignores the error RunOnce returns. So manual updates are not recorded in update-state.json, and a failed pilotctl update still prints success and exits 0. That stays true until pilotctl passes StatusPath: ~/.pilot/update-state.json and checks the error, which needs a web4 change after this version is released.

Restarting the daemon

After installing new binaries the updater restarts the daemon onto them:

  • macOS: launchctl kickstart -k gui/<uid>/network.pilotprotocol.pilot-daemon.
  • Linux: SIGTERM, but only when systemd will start the daemon again. The daemon must run as the main program (ExecStart=) of a system service whose unit restarts it after a clean exit. pilot-daemon exits 0 on SIGTERM, so that means Restart=always or on-success. The updater finds the service from /proc/<pid>/cgroup and reads the unit file and its drop-ins. It does not run systemctl. After the SIGTERM it waits up to 30 s for a new daemon process on the new binary.

On Linux the daemon is left running the old version, with restart_error saying how to restart it, when:

  • it was started with pilotctl daemon start, which is how containers, WSL and CI run it because install.sh sets up no service there;
  • its unit has Restart=on-failure, as written by install.sh up to v1.9.0. Updates never rewrite the unit, and systemd does not restart a clean exit under that policy. Re-running install.sh rewrites the unit with Restart=always;
  • it runs under a systemd user service, or inside another service, such as a CI runner.

Stopping the daemon in any of those cases would take the node offline.

Pinning a version

Set PinnedVersion to lock the updater to a specific release tag. When set, the updater fetches the exact release (via /releases/tags/{tag}), applies it if it differs from the current install, then idles — it will not chase the latest release. Clear PinnedVersion (set to "") to resume auto-updating.

u := updater.New(updater.Config{
    Repo:          "pilot-protocol/pilotprotocol",
    InstallDir:    "/home/user/.pilot/bin",
    PinnedVersion: "v1.10.5",  // stay on this version
})
u.Start()

The in-process Service adapter is used when embedding into the daemon; a standalone sidecar binary built from this package is also supported.

Update status file

After every check the updater writes update-state.json so that other tools can tell whether updates actually work. Before this file existed, pilotctl update status could only show whether auto-update was switched on, and a node could fail every hourly check for weeks without anyone noticing.

The file goes to Config.StatusPath. When that is empty and StatePath is set, it goes next to the control file. For a standard install that is ~/.pilot/auto-update.json → ~/.pilot/update-state.json. With neither set, nothing is written.

The long-running updater and any one-shot RunOnce caller configured with the same path share the file. pilotctl update does not pass one yet (see above). Each writer takes an advisory lock on update-state.json.lock and merges its fields into what is already there, so concurrent writers from different processes do not lose each other's changes. Writes are atomic (temp file + rename). A writer that cannot get the lock within 5 s writes anyway and logs a warning.

{
  "updater_version": "v1.13.10",
  "repo": "pilot-protocol/pilotprotocol",
  "last_check_at": "2026-09-24T10:00:12Z",
  "last_check_trigger": "auto",
  "last_result": "failed",
  "last_error": "fetch latest release: GitHub API returned 403 (rate limit exceeded, resets at 2026-09-24T10:41:03Z; ...)",
  "consecutive_failures": 3,
  "last_success_at": "2026-09-24T07:00:09Z",
  "current_version": "v1.13.9",
  "latest_version": "v1.13.10",
  "last_update_at": "2026-09-01T12:35:40Z",
  "last_update_version": "v1.13.9",
  "loop_pid": 812,
  "loop_started_at": "2026-09-20T08:11:02Z",
  "next_check_at": "2026-09-24T11:00:12Z"
}
Field Meaning
last_result up_to_date, updated or failed.
last_error Why the last check failed. Empty after a success.
consecutive_failures Failed checks since the last success.
last_success_at The last check that completed without error.
current_version / latest_version The installed release, and the release it was compared against (the pin, when pinned).
restart_error New binaries were installed but the daemon is not running them. Either it was left on the old version because stopping it would have left it down (see Restarting the daemon) or the restart failed, or it was stopped and did not come back. Says how to restart it. Cleared by the next successful restart, and on Linux by the next check that finds the daemon running the installed binary.
loop_pid, loop_started_at The long-running updater process.
next_check_at When the loop wakes next. It is updated even while auto-update is disabled, so it doubles as a heartbeat.

Suggested readings for pilotctl update status and similar tools:

  • Updates failing: consecutive_failures > 0. Show last_error.
  • Updates stalled: last_success_at is more than 48 hours old while auto-update is enabled.
  • No updater running: auto-update is enabled, but the file is missing, loop_pid is not alive, or next_check_at is more than one interval in the past. This happens on Linux without systemd (containers, WSL, CI), where the installer cannot start the updater.
  • Daemon on the old version: restart_error is set. Show it: it names the command that restarts the daemon.

Use updater.ReadStatus(path) to read the file. A missing file returns an error matching errors.Is(err, fs.ErrNotExist).

GitHub API rate limits and GITHUB_TOKEN

The updater calls the GitHub REST API for the release list and for the build attestation. Without a token GitHub allows 60 requests per hour per IP, and a shared NAT, VPN or CI egress can use that up. When that happens the check fails with an error that says so, and it is recorded in the status file.

If GITHUB_TOKEN (or GH_TOKEN) is set in the updater's environment, it is sent to api.github.com, and only there, which raises the limit to 5,000 per hour. The token needs no scopes because the repository is public: a classic token with no scopes, or a fine-grained token with public read-only access, is enough. If GitHub rejects the token (401), the updater retries without it, so an expired token never stops updates.

To set it for the service:

  • systemd: sudo systemctl edit pilot-updater, add [Service] / Environment=GITHUB_TOKEN=<token>, then sudo systemctl restart pilot-updater.
  • launchd: add an EnvironmentVariables dict with GITHUB_TOKEN to ~/Library/LaunchAgents/network.pilotprotocol.pilot-updater.plist, then reload it with launchctl bootout / launchctl bootstrap.

Downloads

Release archives are 17–20 MB. Downloads no longer have a fixed total timeout (the old 30 s limit needed a sustained ~5 Mbit/s). Instead:

  • An attempt fails only when no data arrives for 60 s.
  • A dropped or stalled transfer resumes with an HTTP Range request from the bytes already on disk, or starts over if the server ignores Range. Up to 4 attempts are made. 5xx responses are retried and 4xx responses are not.
  • One file download is capped at 30 minutes in total.
  • Stop() aborts an in-flight download.

The SHA-256 match against the attested checksums.txt still gates every install.

No external tools (no gh)

The updater never runs gh or any other external tool. It checks the SLSA provenance of checksums.txt in-process with sigstore-go (attestation.go). The only command it runs is launchctl kickstart, which restarts the daemon under launchd on macOS. On Linux it reads /proc and the systemd unit files directly instead of running systemctl. TestNoExternalToolDependency fails the build if another exec is added.

Nodes stuck on v1.12.2–v1.13.4 (updater v0.2.3)

pilotprotocol releases v1.12.2 through v1.13.4 shipped updater v0.2.3, which ran gh attestation verify and refused every update when gh was not on its PATH. Service managers never put gh on the PATH: launchd's default is /usr/bin:/bin:/usr/sbin:/sbin, and most Linux hosts have no gh at all. So those nodes cannot update themselves. The updater log shows an hourly gh CLI required for SLSA attestation verification error. On macOS the log is ~/.pilot/updater.log. On Linux, read it with journalctl -u pilot-updater.

The broken updater cannot fix itself. On an affected node, do one of these:

  1. Re-run the installer (recommended). It installs the current binaries, including a gh-free updater, and restarts the services:

    curl -fsSL https://pilotprotocol.network/install.sh | sh
    
  2. Or run pilotctl update once from an interactive shell where gh is installed and logged in (gh auth status). That one-shot update uses your shell's PATH, installs the current release and replaces pilot-updater with a gh-free version. The old pilotctl update exits silently after doing so. Then restart both services so they run the new binaries: sudo systemctl restart pilot-updater pilot-daemon on Linux, or on macOS launchctl kickstart -k gui/$(id -u)/network.pilotprotocol.pilot-updater and the same command for network.pilotprotocol.pilot-daemon.

Check the result with pilotctl version and ~/.pilot/bin/pilot-updater --version. Do not work around the problem with PILOT_UPDATER_SKIP_ATTESTATION, because that switches off provenance checks.

Layout

File What it does
updater.go Updater: check loop, RunOnce, release polling, install, daemon restart.
supervisor.go Linux restart safety: finds the daemon's systemd service and checks its restart policy before any SIGTERM.
download.go Resumable asset downloads with idle and total-duration limits.
github.go GitHub API calls: optional GITHUB_TOKEN, rate-limit errors.
attestation.go In-process SLSA provenance verification of checksums.txt (sigstore-go).
status.go Status / update-state.json persistence and ReadStatus.
version.go SemVer parsing and comparison.
service.go *Service — coreapi.Service adapter. Build tag !no_updater.
service_disabled.go Stub when build tag no_updater is set.

Build tags

Tag Effect
no_updater Compiles a stub whose Start is a no-op.

License

AGPL-3.0-or-later. See LICENSE.

Documentation

Index

Constants

View Source
const (
	// ResultUpToDate: the check succeeded and nothing needed installing
	// (the installed version is the latest release, or the pinned one).
	ResultUpToDate = "up_to_date"
	// ResultUpdated: the check succeeded and a release was installed.
	ResultUpdated = "updated"
	// ResultFailed: the check failed; Status.LastError says why.
	ResultFailed = "failed"
)

Values of Status.LastResult.

View Source
const (
	// TriggerAuto marks a check run by the periodic loop (Start).
	TriggerAuto = "auto"
	// TriggerManual marks a one-shot check (RunOnce, e.g. `pilotctl update`).
	TriggerManual = "manual"
)

Values of Status.LastCheckTrigger.

View Source
const StatusFileName = "update-state.json"

StatusFileName is the default name of the file the updater writes after every check. When Config.StatusPath is empty and Config.StatePath is set, the status file lives next to the control file (for the standard install: ~/.pilot/auto-update.json -> ~/.pilot/update-state.json).

Variables

This section is empty.

Functions

func VerifyChecksum

func VerifyChecksum(archivePath, archiveName, checksumsPath string) error

VerifyChecksum checks the SHA256 of archivePath against the checksums file.

Types

type Config

type Config struct {
	CheckInterval time.Duration
	Repo          string // "owner/repo"
	InstallDir    string
	Version       string // updater's own version (used for user-agent)

	// PinnedVersion locks the updater to a specific release tag
	// (e.g. "v1.10.5"). When set, the updater installs exactly that
	// version — regardless of whether it is newer, older, or already
	// current — and will not chase the latest release. An empty
	// string (default) preserves the existing "always follow latest"
	// behaviour. Set to an empty string to un-pin and resume
	// auto-updating to the latest stable.
	PinnedVersion string

	// SkipAttestation disables SLSA attestation verification of
	// checksums.txt. This is the ONLY way to bypass attestation: when
	// false (the default), the updater fetches the GitHub SLSA provenance
	// bundle and verifies it in-process with sigstore-go (no gh CLI, no
	// external tooling required); if it cannot verify, the update is
	// refused (fails closed). Intended for test environments where the
	// test repos do not have real attestations. Leaving it false in
	// production keeps provenance verification mandatory. The SHA256
	// checksums.txt match is always enforced regardless of this flag.
	SkipAttestation bool

	// StatePath, when non-empty, points to a JSON control file
	// {"enabled": bool} that gates the AUTOMATIC update loop and is
	// re-read on every tick. When the file is absent or {"enabled":
	// false} the loop performs NO updates — so any deployment that sets
	// StatePath is OFF BY DEFAULT until explicitly enabled (e.g. via
	// `pilotctl update enable`). A manual one-shot RunOnce always runs,
	// ignoring this gate. An empty StatePath preserves the legacy
	// always-on loop behaviour for backward compatibility.
	StatePath string

	// StatusPath is where the updater records the outcome of every check
	// (see Status): last check time and result, last error, consecutive
	// failures, installed and latest versions, and whether the loop is
	// running. Empty means "update-state.json next to StatePath"; with
	// neither set, nothing is written (LastStatus still reports it).
	StatusPath string
}

Config holds the updater configuration.

type GitHubAsset

type GitHubAsset struct {
	Name               string `json:"name"`
	BrowserDownloadURL string `json:"browser_download_url"`
}

GitHubAsset represents a release asset.

type GitHubRelease

type GitHubRelease struct {
	TagName string        `json:"tag_name"`
	Assets  []GitHubAsset `json:"assets"`
}

GitHubRelease represents a subset of the GitHub release API response.

type Semver

type Semver struct {
	Major int
	Minor int
	Patch int
	// Pre holds the prerelease identifiers that follow the first hyphen,
	// without the leading hyphen. It is empty for a plain release tag.
	// "v1.2.3-rc1" yields "rc1"; "v1.2.3" yields "".
	Pre string
}

Semver represents a parsed semantic version.

func ParseSemver

func ParseSemver(s string) (Semver, error)

ParseSemver parses a version string like "v1.2.3" or "1.2.3" or "v1.2.3-rc1". It strips the "v" prefix and any "+build" metadata, keeps the numeric major.minor.patch triple, and retains the prerelease suffix in Pre.

func (Semver) Compare added in v0.2.5

func (v Semver) Compare(other Semver) int

Compare returns -1, 0 or +1 as v sorts before, equal to, or after other. Ordering follows semantic-version precedence: the numeric triple is compared first, then the prerelease suffix. A version carrying a prerelease suffix sorts before the same version without one, so "1.2.3-rc1" < "1.2.3".

func (Semver) NewerThan

func (v Semver) NewerThan(other Semver) bool

NewerThan returns true if v is strictly newer than other.

func (Semver) String

func (v Semver) String() string

String returns the version as "vMAJOR.MINOR.PATCH", with the prerelease suffix appended when present.

type Service

type Service struct{}

Service is the L11 plugin lifecycle adapter for the updater. The daemon does not register this today — cmd/updater is a standalone binary that uses updater.New / *Updater.Start directly. The adapter exists so the plugin package conforms to the L10 Service contract and so the no_updater build tag has a meaningful counterpart (see service_disabled.go).

When this plugin is eventually wired into cmd/daemon's plugin runtime, this Service will own the *Updater lifecycle. Today its Start/Stop are no-ops; it is registered nowhere.

func NewService

func NewService() *Service

NewService returns a Service ready for daemon.RegisterPlugin (when cmd/daemon eventually starts registering it). Distinct from updater.New, which constructs the standalone *Updater used by cmd/updater.

func (*Service) Name

func (s *Service) Name() string

func (*Service) Order

func (s *Service) Order() int

func (*Service) Start

func (s *Service) Start(_ context.Context, _ coreapi.Deps) error

func (*Service) Stop

func (s *Service) Stop(_ context.Context) error

type Status added in v0.2.5

type Status struct {
	// UpdaterVersion is the version of the updater that wrote the record.
	UpdaterVersion string `json:"updater_version,omitempty"`
	// Repo is the GitHub owner/repo releases are read from.
	Repo string `json:"repo,omitempty"`
	// PinnedVersion is the pin in force for the last check ("" = latest).
	PinnedVersion string `json:"pinned_version,omitempty"`

	// LastCheckAt is when the last check finished.
	LastCheckAt time.Time `json:"last_check_at,omitzero"`
	// LastCheckTrigger is TriggerAuto or TriggerManual.
	LastCheckTrigger string `json:"last_check_trigger,omitempty"`
	// LastResult is ResultUpToDate, ResultUpdated or ResultFailed.
	LastResult string `json:"last_result,omitempty"`
	// LastError is the error of the last check; empty when it succeeded.
	LastError string `json:"last_error,omitempty"`
	// ConsecutiveFailures counts failed checks since the last success.
	ConsecutiveFailures int `json:"consecutive_failures"`
	// LastSuccessAt is when a check last completed without error.
	LastSuccessAt time.Time `json:"last_success_at,omitzero"`

	// CurrentVersion is the installed release after the last check.
	CurrentVersion string `json:"current_version,omitempty"`
	// LatestVersion is the release the last check compared against: the
	// latest published release, or the pinned tag when pinned.
	LatestVersion string `json:"latest_version,omitempty"`

	// LastUpdateAt / LastUpdateVersion record the last release installed.
	LastUpdateAt      time.Time `json:"last_update_at,omitzero"`
	LastUpdateVersion string    `json:"last_update_version,omitempty"`
	// RestartError is set when new binaries were installed but the daemon
	// is not running them: it was left on the old version, or it was
	// stopped and did not come back. It says how to restart it. On Linux the
	// updater stops the daemon only when systemd will start it again, so a
	// daemon without such a service (e.g. `pilotctl daemon start` in a
	// container) is left running and reported here. Cleared by the next
	// successful restart and, on Linux, by the next check that finds the
	// daemon running the installed binary.
	RestartError string `json:"restart_error,omitempty"`

	// LoopPID and LoopStartedAt identify the long-running updater process
	// (the service started via Start). Absent when no loop ever ran.
	LoopPID       int       `json:"loop_pid,omitempty"`
	LoopStartedAt time.Time `json:"loop_started_at,omitzero"`
	// NextCheckAt is when the loop will next wake up (plus up to 30s of
	// jitter). A NextCheckAt well in the past means the loop is not running.
	NextCheckAt time.Time `json:"next_check_at,omitzero"`
}

Status is the machine-readable record of what the updater last did. It is persisted as JSON at Config.StatusPath after every check so that other tools (`pilotctl update status`, `daemon status`, support scripts) can tell whether updates are actually working, instead of only whether they are switched on.

The file can be shared by the long-running updater service and one-shot RunOnce callers configured with the same StatusPath (or StatePath). Each writer takes an advisory lock (StatusFileName + ".lock") and merges its fields into what is already on disk, so a manual run keeps the loop's LoopPID/NextCheckAt and the loop keeps the failure streak a manual run started. A RunOnce caller with neither path set writes nothing.

func ReadStatus added in v0.2.5

func ReadStatus(path string) (Status, error)

ReadStatus loads the status file written by the updater. A missing file returns an error satisfying errors.Is(err, fs.ErrNotExist), which callers should read as "the updater has never recorded a check here".

type Updater

type Updater struct {
	// contains filtered or unexported fields
}

Updater periodically checks GitHub Releases for new versions and optionally applies them.

func New

func New(cfg Config) *Updater

New creates a new Updater.

func (*Updater) LastStatus added in v0.2.5

func (u *Updater) LastStatus() Status

LastStatus returns the status recorded by this Updater's most recent check (or loop event). It is available even when no status file is configured, so a caller of RunOnce can report the outcome without reading the file.

func (*Updater) RunOnce added in v0.2.2

func (u *Updater) RunOnce() error

RunOnce runs the update check once synchronously and returns. Unlike Start, it does not enter a periodic loop — it performs a single check (checking the pinned version or latest release), applies the update if available, and returns. Useful for one-shot invocations from `pilotctl update` and similar CLI commands. It ALWAYS runs — the StatePath enabled-gate applies only to the automatic loop, so a manual `pilotctl update` works even when auto-update is disabled.

It returns the check's error (nil when already up to date or when the update was installed), so callers can report failure and exit non-zero. LastStatus describes the outcome in detail, and the same record is written to the status file when one is configured.

RunOnce never exits the calling process. When the release replaces the pilot-updater binary, the daemon is still restarted onto the new binaries; a separately running updater service picks up its new binary the next time its service manager restarts it.

func (*Updater) Start

func (u *Updater) Start()

Start begins the periodic check loop.

func (*Updater) Stop

func (u *Updater) Stop()

Stop signals the check loop to stop and waits for it to finish.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL