update

package
v0.2.0-dev.11 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 22 Imported by: 0 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.

Documentation

Overview

Package update is the node agent's self-update: verify a release the owner signed, swap the executable, re-exec, and undo it if the new build does not come up. The protocol and the state machine are specified in agent.proto ("UPDATE"); this package is the filesystem and decision half, internal/node/agent is the wiring (commands, Hello, the download client, draining before exec).

Trust: the ed25519 key compiled into this binary (buildinfo.ReleaseKey) is the only thing that decides what may be installed. A build without the key never updates itself.

Index

Constants

View Source
const (
	FilePending            = "update.pending"
	FileStarts             = "update.starts"
	FileRolledBack         = "update.rolledback"
	FileRolledBackWhy      = "update.rolledback.reason"
	FileOutcome            = "update.outcome"
	FilePrev               = "update.prev"
	FileUnitRefreshPending = "unit-refresh.pending"
	CommitWindow           = 5 * time.Minute
	DefaultIdleTimeout     = 90 * time.Second
)

Files in the state dir (mode 0600). update.starts and the guard's update.rolledback[.reason] are written by the unit's ExecStartPre script (GuardScript), everything else by this package.

View Source
const (
	ReasonNotCommitted  = "not_committed"
	ReasonBuiltMismatch = "built_mismatch"
	ReasonCrashLoop     = "crash_loop"
	ReasonApplyFailed   = "apply_failed"
	ReasonManual        = "manual"
	ReasonInterrupted   = "failed: interrupted"
	ReasonExec          = "failed: exec"
	ReasonNoPrevious    = "failed: no_previous"
)

Reasons of a rollback (LastUpdate.reason vocabulary of agent.proto).

View Source
const GuardScript = `m="$2/update.pending"; c="$2/update.starts"; ` +
	`if [ ! -f "$m" ]; then rm -f "$c"; exit 0; fi; ` +
	`n=$(cat "$c" 2>/dev/null); case "$n" in ""|*[!0-9]*) n=0;; esac; n=$((n+1)); echo "$n" > "$c"; ` +
	`[ "$n" -ge 3 ] || exit 0; ` +
	`[ -f "$1.prev" ] || exit 0; ` +
	`mv -f "$1.prev" "$1" || exit 0; ` +
	`mv -f "$m" "$2/update.rolledback"; echo crash_loop > "$2/update.rolledback.reason"; rm -f "$c"; exit 0`

GuardScript is the crash-loop guard the generation 2 systemd unit runs as ExecStartPre, one line of POSIX sh. Arguments: $1 the binary, $2 the state dir. While update.pending exists it counts the supervisor's starts in update.starts (a re-exec is not a supervisor start, so only real crashes count); the third start restores <bin>.prev and leaves update.rolledback{,.reason} for the restored build to report. It always exits 0: a broken guard must never keep the agent from starting.

It avoids backslashes, single quotes and percent signs, so it survives systemd's command-line parsing once every $ is doubled (UnitGuardLine does that).

Variables

View Source
var (
	// ErrRetryLater is what a Fetcher returns for "the panel's download slots are busy": waited out, not counted as a failed attempt.
	ErrRetryLater = errors.New("update: download slot busy, retry later")
	// ErrPermanent wraps a download error that retrying cannot fix (name not in the manifest, no bundle).
	ErrPermanent = errors.New("update: permanent download error")
	// ErrNoPrevious means there is no <exe>.prev to go back to.
	ErrNoPrevious  = errors.New("no_previous")
	ErrRefreshBusy = errors.New("unit refresh busy")
)

Functions

func BusySourceFailure

func BusySourceFailure(code string, err error) error

BusySourceFailure switches immediately without consuming the source's transient retry budget.

func ClearUnitRefreshPending added in v0.1.37

func ClearUnitRefreshPending(stateDir string) error

ClearUnitRefreshPending is called by the transient helper after it writes the final unit-refresh outcome.

func IsOverflow

func IsOverflow(err error) bool

IsOverflow reports that a source tried to append past the signed file size.

func PermanentSourceFailure

func PermanentSourceFailure(code string, err error) error

PermanentSourceFailure drops this source for the current update command.

func TransientSourceFailure

func TransientSourceFailure(code string, err error) error

TransientSourceFailure makes a network or transport failure eligible for the per-source retry budget.

func UnitGuardLine

func UnitGuardLine(bin, stateDir string) string

UnitGuardLine is the ExecStartPre line for a unit: the script as one single-quoted word ($ doubled for systemd), then $0 and the two arguments. The leading "-" makes systemd ignore a failing guard.

Types

type Config

type Config struct {
	StateDir    string
	ExePath     string // default: the running executable, symlinks resolved, taken once at New
	Version     string
	Built       int64
	Key         ed25519.PublicKey // nil = unsigned build: no self-update
	UnitGen     int               // MISTGATE_UNIT_GEN: >= 2 means the unit carries the crash-loop guard
	Exec        func(path string, argv, env []string) error
	Args        []string // default os.Args
	Env         []string // default os.Environ()
	Now         func() time.Time
	GOOS        string // default runtime.GOOS
	GOARCH      string
	Window      time.Duration // commit window, default CommitWindow
	Backoff     []time.Duration
	Timeout     time.Duration // whole download, default 10 min
	IdleTimeout time.Duration // no download data, default 90 s
	Log         *slog.Logger
	// RetryWait is the pause after ErrRetryLater.
	RetryWait time.Duration
	// Source policy timing knobs. Zero values select the production policy.
	SourceStallTimeout time.Duration
	SourceSlowAfter    time.Duration
	SourceSlowWindow   time.Duration
	SourceSlowInterval time.Duration
	SourceSlowBytes    uint64
	SourceBackoff      []time.Duration
}

Config describes the running binary and its environment. Zero values are production defaults except Exec, which the caller sets to syscall.Exec (nil means "do not exec", for tests).

type FetchFailure

type FetchFailure struct {
	Code  string
	Class fetchFailureClass
	Err   error
}

FetchFailure carries a short, safe-to-report code for one source failure.

func (*FetchFailure) Error

func (e *FetchFailure) Error() string

func (*FetchFailure) Is

func (e *FetchFailure) Is(target error) bool

func (*FetchFailure) Unwrap

func (e *FetchFailure) Unwrap() error

type Fetcher

type Fetcher struct {
	Kind  string
	Fetch func(context.Context, uint64, io.Writer) (total uint64, err error)
}

Fetcher is one ordered way to fetch the signed file. Fetch always resumes at offset and appends to w.

type FetcherSource

type FetcherSource interface {
	Fetchers(m *release.Manifest, f release.File) []Fetcher
}

FetcherSource optionally builds the sources requested by an UpdateAgent. Without it the updater keeps the historical single-panel path.

type Finish

type Finish func() error

Finish ends an update or a rollback: it re-executes the new binary. The agent calls it after the CommandResult is on the wire and the engines are drained. An error means exec failed; the previous binary is back in place and the agent must exit so the supervisor restarts it.

type Marker

type Marker struct {
	FromVersion string   `json:"from_version"`
	FromBuilt   int64    `json:"from_built"`
	ToVersion   string   `json:"to_version"`
	ToBuilt     int64    `json:"to_built"`
	StartedUnix int64    `json:"started_unix"`
	RequestID   string   `json:"request_id,omitempty"`
	PreFailed   []string `json:"pre_failed,omitempty"` // inbounds FAILED before the update (not the new build's fault)
}

Marker is the content of update.pending (and, after a crash-loop restore, of update.rolledback).

type Source

type Source interface {
	// Fetch appends the named file to w from byte offset, returning the file's total size as the panel reported it.
	Fetch(ctx context.Context, name string, offset uint64, w io.Writer) (total uint64, err error)
	Failed() []string
	Now() time.Time
	LocalNow() time.Time
}

Source is what the agent lends to one update: the download client, its corrected clock and the inbounds that are FAILED right now (the gate compares against them: a node that already had a broken inbound must not roll back for it).

type Startup

type Startup struct {
	Pending *Marker // the new build, just exec'd: the caller must run Watch
	Finish  Finish  // a rollback that has to be executed now
}

Startup reads the marker files before the agent connects. It may decide to roll back at once, in which case Finish is set and the caller must drain and run it before doing anything else.

type Status

type Status struct {
	Settled   bool     // connected to the panel, desired state applied, quiet for a while
	NewFailed []string // inbounds FAILED now that were not FAILED before the update
}

Status is what the agent tells Watch about itself.

type Updater

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

Updater is safe for concurrent use; one update or rollback runs at a time.

func New

func New(cfg Config) *Updater

New fills the defaults. It touches no file.

func (*Updater) AckOutcome

func (u *Updater) AckOutcome(o *pb.LastUpdate)

func (*Updater) Apply

func (u *Updater) Apply(ctx context.Context, req *pb.UpdateAgent, src Source) (*pb.CommandResult, Finish)

Apply executes one UpdateAgent. The CommandResult always goes back to the panel; a non-nil Finish means the binary was swapped and the caller must send the result, drain the engines and call it.

func (*Updater) Capabilities

func (u *Updater) Capabilities() []string

Capabilities lists "update/1" only when this process can really update itself: signed build, Linux, and a writable executable directory (false under the generation 1 unit, which is what keeps old nodes on "update by hand once"); "update-guard/1" when the unit carries the crash-loop guard.

func (*Updater) Commit

func (u *Updater) Commit() (*pb.LastUpdate, error)

Commit makes the update permanent: outcome ok, marker and start counter gone. The previous binary stays as .prev (the manual rollback target).

func (*Updater) IdleTimeout

func (u *Updater) IdleTimeout() time.Duration

IdleTimeout is the no-data limit used by this updater. Link-only downloads use the same value so the two update transports expose one idle-time contract.

func (*Updater) Outcome

func (u *Updater) Outcome() *pb.LastUpdate

Outcome is the Hello.last_update to send now (nil = none). AckOutcome forgets it once a HelloAck for that Hello arrived; an outcome that was replaced in between stays.

func (*Updater) Pending

func (u *Updater) Pending() bool

Pending reports whether this process is a new build inside its commit window.

func (*Updater) RefreshBusy added in v0.1.37

func (u *Updater) RefreshBusy() bool

RefreshBusy reports an update download, commit window, or a refresh reservation that makes a service restart unsafe.

func (*Updater) ReserveUnitRefresh added in v0.1.37

func (u *Updater) ReserveUnitRefresh() (release func(started bool), err error)

ReserveUnitRefresh excludes update and rollback work, then leaves a state-dir marker for the transient refresh helper and the process that systemd starts after the restart. release(true) drops this process's memory lock but leaves the marker for the helper to clear when its active-state check finishes; release(false) cancels a launch that did not start.

func (*Updater) Rollback

func (u *Updater) Rollback(_ context.Context, req *pb.RollbackAgent) (*pb.CommandResult, Finish)

Rollback executes one RollbackAgent: .prev over the executable (consumed: a second call answers no_previous).

func (*Updater) RollbackNow

func (u *Updater) RollbackNow(reason string) (Finish, error)

RollbackNow is the self-rollback of a new build that did not commit: .prev over the executable, outcome rolled_back with the reason, marker removed. It does not exec; the returned Finish does.

func (*Updater) Startup

func (u *Updater) Startup() Startup

func (*Updater) Watch

func (u *Updater) Watch(ctx context.Context, tick time.Duration, status func() Status) (*pb.LastUpdate, Finish, error)

Watch runs in the new build until the update commits or the window ends. Every tick it asks status; the update commits after two consecutive polls that are Settled (connected, desired state applied) without a new FAILED inbound. At the deadline it rolls back: apply_failed when it was settled but an inbound is FAILED, else not_committed. It returns the committed outcome, or the Finish of a rollback (the caller drains and runs it), or ctx.Err().

Jump to

Keyboard shortcuts

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