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
- Variables
- func ClearUnitRefreshPending(stateDir string) error
- func UnitGuardLine(bin, stateDir string) string
- type Config
- type Finish
- type Marker
- type Source
- type Startup
- type Status
- type Updater
- func (u *Updater) AckOutcome(o *pb.LastUpdate)
- func (u *Updater) Apply(ctx context.Context, req *pb.UpdateAgent, src Source) (*pb.CommandResult, Finish)
- func (u *Updater) Capabilities() []string
- func (u *Updater) Commit() (*pb.LastUpdate, error)
- func (u *Updater) Outcome() *pb.LastUpdate
- func (u *Updater) Pending() bool
- func (u *Updater) RefreshBusy() bool
- func (u *Updater) ReserveUnitRefresh() (release func(started bool), err error)
- func (u *Updater) Rollback(_ context.Context, req *pb.RollbackAgent) (*pb.CommandResult, Finish)
- func (u *Updater) RollbackNow(reason string) (Finish, error)
- func (u *Updater) Startup() Startup
- func (u *Updater) Watch(ctx context.Context, tick time.Duration, status func() Status) (*pb.LastUpdate, Finish, error)
Constants ¶
const ( FilePending = "update.pending" FileStarts = "update.starts" FileRolledBack = "update.rolledback" FileRolledBackWhy = "update.rolledback.reason" FileOutcome = "update.outcome" FileUnitRefreshPending = "unit-refresh.pending" CapUpdate = "update/1" CapGuard = "update-guard/1" CommitWindow = 5 * time.Minute )
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.
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).
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 ¶
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 ClearUnitRefreshPending ¶ added in v0.1.37
ClearUnitRefreshPending is called by the transient helper after it writes the final unit-refresh outcome.
func UnitGuardLine ¶
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
Log *slog.Logger
// RetryWait is the pause after ErrRetryLater.
RetryWait 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 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
}
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 (*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 ¶
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) 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 ¶
Pending reports whether this process is a new build inside its commit window.
func (*Updater) RefreshBusy ¶ added in v0.1.37
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
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 ¶
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) 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().