selfupdate

package
v0.16.397 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 26 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 selfupdate keeps the programs of a machine connected to a hub the same as the ones the hub serves (<hub>/dl/manifest.json, the file install.sh downloads from). It compares the SHA-256 of the installed files with the manifest, downloads what differs, checks the download against the manifest and puts it in place with a rename, so a running program is never cut. Then the caller restarts what it replaced.

The files are compared, not version numbers: the hub's binaries may all be "dev" builds, and a machine must still get the hub's latest ones.

Index

Constants

View Source
const (

	// ReleaseFile is the file at the top of a release that names its version and commit.
	ReleaseFile = ".harnessly-release.json"
	// DefaultKeep is the number of newest releases kept on the disk (the active and the previous ones count, and stay anyway).
	DefaultKeep = 3
	// DefaultHealthTimeout is the time a restarted service has to pass its health check.
	DefaultHealthTimeout = 90 * time.Second
)
View Source
const (
	// ChatsStarting is a runtime whose conversations are not loaded yet: it listens and serves nothing.
	ChatsStarting = "starting"
	// ChatsReady is a runtime that finished the work of its start.
	ChatsReady = "ready"
	// DefaultSettleTimeout is how long the next service waits for the chats of the one before it.
	DefaultSettleTimeout = 5 * time.Minute
)
View Source
const (
	// DefaultInterval is the time between checks.
	DefaultInterval = time.Hour
	// FirstDelay is the wait before the first check after a start: an update right after one would restart the
	// program before the page has had a look at it.
	FirstDelay = 2 * time.Minute
)
View Source
const DefaultMinGap = 24 * time.Hour

DefaultMinGap is the window of a runtime that was not told another one (RUNTIME_UPDATE_MIN_GAP).

View Source
const MinInterval = 30 * time.Second

MinInterval is the shortest time between checks an environment can ask for: a check is a request to the hub, and a fleet of machines checking every few seconds would be a load of its own.

Variables

View Source
var DefaultParts = []string{"bin", ReleaseFile}

DefaultParts is what a delta replaces unless RUNTIME_FLEET_PARTS says otherwise.

View Source
var ErrBusy = errors.New("an update is already going on")

ErrBusy: an update is already going on.

View Source
var ErrDeltaBase = errors.New("the running release is not the one this delta was cut against")

ErrDeltaBase: the machine does not run the release this delta was cut against; nothing was changed. The whole release is the answer.

View Source
var ErrFleet = errors.New("this machine is updated by its rollout: stage and activate a release")

ErrFleet: this machine takes its releases from the rollout, not from the hub.

View Source
var ErrManual = errors.New("this machine cannot replace its own programs: run the update command")

ErrManual: this machine cannot replace its own programs; the command is needed.

View Source
var ErrTooSoon = errors.New("the machine took a release too recently")

ErrTooSoon: the last activation is closer than the machine's window allows; nothing was changed.

Functions

func CutDelta

func CutDelta(tarball, out, head string, parts []string) (string, error)

CutDelta writes a delta from a whole release tarball: the members under release/<part> for each part, and nothing else. It fails when the tarball lacks a part or was not packed from commit head (the release file says so), so a delta is always made of the bytes of the very release it stands for. Returns the sha256 of the delta.

func FleetOn

func FleetOn(getenv func(string) string) bool

FleetOn says whether the environment asks for fleet mode: RUNTIME_UPDATE_MODE=fleet. Without it a runtime updates from its hub (or not at all) exactly as before.

func GapFromEnv

func GapFromEnv(raw string, def time.Duration) time.Duration

GapFromEnv reads a window between updates: a duration ("24h", "90m"), or 0 or off for none; def when unset or unreadable.

func IntervalFromEnv

func IntervalFromEnv(raw string, def time.Duration) time.Duration

IntervalFromEnv reads RUNTIME_UPDATE_INTERVAL ("2m", "1h"): the time between checks; def when unset or unreadable, MinInterval when shorter than that.

func ShortHostname

func ShortHostname() string

ShortHostname is this machine's name up to the first dot.

Types

type File

type File struct {
	Name string
	Path string
	// Optional: a hub that does not serve it is no error, and a machine without it gets it.
	Optional bool
}

File is one installed program: its name in the manifest ("agent", "runtime") and where it is.

type Fleet

type Fleet struct {
	// Root holds releases/, current and deployed.json.
	Root string
	// Keep is the number of newest releases kept (DefaultKeep when zero).
	Keep int
	// Parts are the top-level names a delta may replace; a delta holding anything else is refused.
	Parts []string
	// Restart restarts the services that run from current; nil means nothing to restart.
	Restart func(ctx context.Context) error
	// Probe answers the version the services serve now, or an error while they do not answer; nil skips the check.
	Probe func(ctx context.Context) (string, error)
	// HealthTimeout bounds the wait for Probe (DefaultHealthTimeout when zero).
	HealthTimeout time.Duration
	// PollEvery is the pause between probes (2 s when zero).
	PollEvery time.Duration
	// InUse tells that a release directory is still used by something that cannot be seen from here (a unit that
	// names it, a process that runs from it); nil means nothing is.
	InUse func(dir string) bool
	// Log gets one line per step; may be nil.
	Log func(msg string)
	// Services are the services that run from current, when each can be restarted on its own (fleet_stagger.go): they
	// are restarted one at a time, in this order, by RestartOne, and Restart and Probe are not used.
	Services []Service
	// RestartOne restarts the service of that name; nil restarts nothing.
	RestartOne func(ctx context.Context, name string) error
	// SettleTimeout bounds the wait for a restarted service's chats before the next one (DefaultSettleTimeout when zero).
	SettleTimeout time.Duration
	// MinGap is the machine's window: Activate refuses a release that comes sooner after the last one (ErrTooSoon).
	// Zero is no window. Force lets one activation through, for a rollout a person asked for.
	MinGap time.Duration
	Force  bool
	// Units is the machine's unit files (fleet_units.go): Activate renders and writes them after current
	// moves and before the services restart; nil leaves the units alone, as before.
	Units *UnitsSpec
	// UnitsErr is why the spec named in the environment could not be read; Activate refuses while it is set.
	UnitsErr error
	// UnitDir is the folder of the units (/etc/systemd/system when empty); Host names the machine for the pairs of the
	// spec; Systemctl replaces the real command in tests.
	UnitDir   string
	Host      string
	Systemctl func(ctx context.Context, args ...string) error
	// Now is the clock (time.Now when nil).
	Now func() time.Time
}

Fleet manages the releases of one machine.

func FleetFromEnv

func FleetFromEnv(getenv func(string) string, log func(string)) *Fleet

FleetFromEnv builds the machine's Fleet from its environment; nil when RUNTIME_FLEET_ROOT is not set.

RUNTIME_FLEET_ROOT        the folder holding releases/ and current
RUNTIME_FLEET_KEEP        releases kept (3)
RUNTIME_FLEET_PARTS       comma-separated top-level names of a release a delta may replace
RUNTIME_FLEET_RESTART     a shell command that restarts the services that run from <root>/current
RUNTIME_FLEET_HEALTH_URL  an address that answers 200 with {"version":"…"} once the services serve a release
RUNTIME_FLEET_HEALTH_TIMEOUT  seconds to wait for it (90)
RUNTIME_FLEET_SERVICES    name=health-address pairs, comma-separated: the services are restarted one at a time,
                          RUNTIME_FLEET_RESTART runs once for each with its name in FLEET_SERVICE
RUNTIME_FLEET_SETTLE_TIMEOUT  seconds the next service waits for the chats of the one before it (300)
RUNTIME_FLEET_MIN_GAP     the shortest time between two activations ("24h"); unset or 0 is no window
RUNTIME_FLEET_UNITS_SPEC  a units spec (fleet_units.go): Activate writes the machine's unit files from it and
                          reloads systemd once; unset leaves the units alone. RUNTIME_FLEET_UNIT_DIR is their
                          folder (/etc/systemd/system), RUNTIME_FLEET_HOST the machine's name in the spec
                          (the short hostname)

func (*Fleet) Activate

func (f *Fleet) Activate(ctx context.Context, version, sha string) error

Activate points current at a staged release, restarts the services and waits for them to serve its version. When any step fails the previous release is put back and the services are restarted again; the error says why.

func (*Fleet) Active

func (f *Fleet) Active() string

Active is the release current points to, or "" when there is none.

func (*Fleet) Dir

func (f *Fleet) Dir(version, sha string) string

Dir is the directory a staged release of this version and checksum lives in.

func (*Fleet) Prune

func (f *Fleet) Prune(previous string) []string

Prune removes the releases beyond the Keep newest, except the active one, the given previous one and any that InUse reports. It returns the directories removed.

func (*Fleet) ReloadUnits

func (f *Fleet) ReloadUnits(ctx context.Context, ch UnitsChange) error

ReloadUnits asks systemd once to reload and once to enable the new units of a change.

func (*Fleet) Rollback

func (f *Fleet) Rollback(ctx context.Context) error

Rollback puts the release that was active before the last activation back (deployed.json names it).

func (*Fleet) Stage

func (f *Fleet) Stage(in StageInput) (string, error)

Stage unpacks a release without touching anything that runs and returns its directory. A staged release is not unpacked again. The tarball is deleted when it was used.

func (*Fleet) Status

func (f *Fleet) Status() FleetStatus

Status reads the releases on the disk.

type FleetStatus

type FleetStatus struct {
	Root     string   `json:"root"`
	Active   string   `json:"active,omitempty"`
	Version  string   `json:"version,omitempty"`
	Commit   string   `json:"commit,omitempty"`
	Staged   []string `json:"staged,omitempty"`
	Deployed string   `json:"deployedAt,omitempty"`
}

FleetStatus is what a machine in fleet mode tells.

type Health

type Health struct {
	Version string
	// Chats is starting, restoring or ready; empty from a service that does not say, which has nothing to wait for.
	Chats string
}

Health is what a service answers about itself.

type Release

type Release struct {
	Version string `json:"version"`
	Commit  string `json:"commit,omitempty"`
	BuiltAt string `json:"builtAt,omitempty"`
}

Release is what ReleaseFile holds.

func ReadRelease

func ReadRelease(dir string) (Release, error)

ReadRelease reads the release file of a release directory.

type Service

type Service struct {
	Name string
	// Probe answers what the service serves now, or an error while it does not answer.
	Probe func(ctx context.Context) (Health, error)
}

Service is one of the services that run from current.

type StageInput

type StageInput struct {
	Version string
	// Tarball is the file: a whole release (one top-level directory `release/`) or, with DeltaBase, a delta.
	Tarball string
	// SHA256 is the checksum the tarball must have.
	SHA256 string
	// DeltaBase is the commit the delta was cut against; empty for a whole release.
	DeltaBase string
}

StageInput says what to stage.

type Status

type Status struct {
	// Mode is "auto" when this machine can replace its programs itself, "manual" when it needs Command.
	Mode string `json:"mode"`
	// Checked says whether a check has been made since the start.
	Checked bool `json:"checked"`
	// UpToDate: the installed programs are the hub's (meaningful once Checked).
	UpToDate bool `json:"upToDate"`
	// Applying: an update is being downloaded and put in place.
	Applying bool `json:"applying"`
	// Version is what the hub calls its programs (may be "dev").
	Version string `json:"version,omitempty"`
	// CheckedAt is the time of the last check, RFC 3339.
	CheckedAt string `json:"checkedAt,omitempty"`
	// Error is the last check's or update's failure, for the person.
	Error string `json:"error,omitempty"`
	// Command updates this machine from its shell (run where it was installed).
	Command string `json:"command"`
	// Fleet is the state of the releases on this machine, in fleet mode only (fleet.go).
	Fleet *FleetStatus `json:"fleet,omitempty"`
	// NextAuto is when the machine may next update by itself, while its window holds an update back (window.go).
	NextAuto string `json:"nextAuto,omitempty"`
}

Status is what the page is told.

type UnitsChange

type UnitsChange struct {
	// Before holds the text each touched file had; nil means it did not exist.
	Before map[string]*string
	// Written and Removed are the files that changed.
	Written, Removed []string
	// Enable are the new units that are to be enabled.
	Enable []string
}

UnitsChange is what a plan did to the unit folder, enough to put it back.

func ApplyUnits

func ApplyUnits(dir string, plan UnitsPlan, dry bool) (UnitsChange, error)

ApplyUnits writes the plan into dir: only the files whose text differs, each through a temporary file and a rename. With dry nothing is written and the change says what would be. A file the plan removes is removed only if it exists.

func (UnitsChange) Empty

func (c UnitsChange) Empty() bool

Empty says nothing in the folder changed.

func (UnitsChange) Restore

func (c UnitsChange) Restore(dir string) error

Restore puts the unit folder back as the change found it.

type UnitsFile

type UnitsFile struct {
	// Path is relative to the unit folder, like `runtime-gate-{{.user}}.service` or `x.service.d/memory.conf`.
	Path    string `json:"path"`
	Content string `json:"content"`
	// PerPair renders the file once for each pair of the machine.
	PerPair bool `json:"perPair,omitempty"`
	// Enable enables the unit when it is a new file (a service, socket or timer, not a drop-in).
	Enable bool `json:"enable,omitempty"`
}

UnitsFile is one file of the unit folder. Path and Content are Go templates (text/template, a missing key is an error) over {{.version}}, {{.release}} (the folder current points at) and the variables of the spec and the pair. A file that renders to nothing (an empty Content, or a template whose condition is false) must not exist.

type UnitsPair

type UnitsPair struct {
	Host string            `json:"host,omitempty"`
	Vars map[string]string `json:"vars"`
}

UnitsPair is one pair: its variables are available to the templates of a file marked PerPair, on top of Vars.

type UnitsPlan

type UnitsPlan struct {
	Want   map[string]string
	Remove []string
	Enable []string
}

UnitsPlan is what a spec comes to on a machine: the files it wants and the ones it does not.

type UnitsSpec

type UnitsSpec struct {
	Schema int `json:"schema"`
	// Vars are available to every template as {{.name}}.
	Vars map[string]string `json:"vars,omitempty"`
	// Pairs are the people's pairs of runtimes. A pair with a Host is for the machine of that name only; the machine
	// takes its own pairs and the ones without a Host.
	Pairs []UnitsPair `json:"pairs,omitempty"`
	// Files are the unit files and drop-ins.
	Files []UnitsFile `json:"files"`
	// Remove are files (relative to the unit folder) that must not exist; they are removed and their units disabled.
	Remove []string `json:"remove,omitempty"`
}

UnitsSpec says which unit files a machine has, as templates over its pairs.

func ReadUnitsSpec

func ReadUnitsSpec(path string) (UnitsSpec, error)

ReadUnitsSpec reads and checks a spec file.

func (UnitsSpec) Plan

func (s UnitsSpec) Plan(host, version, release string) (UnitsPlan, error)

Plan renders the spec for the machine named host. version and release are the new release's number and folder.

type Updater

type Updater struct {
	HubURL string
	Files  []File
	GOOS   string
	GOARCH string
	// Auto makes Run apply an update by itself; otherwise it only checks.
	Auto bool
	// Sudo: the install command needs root (a system install).
	Sudo bool
	// Client makes the requests; nil means one that honours the proxy environment.
	Client *http.Client
	// Interval is the time between checks; zero means DefaultInterval.
	Interval time.Duration
	// Applied runs after the files were replaced, with the names of those replaced (the caller restarts them).
	Applied func(names []string)
	// Log gets one line per failure; may be nil.
	Log func(msg string, err error)
	// Fleet switches to fleet mode (fleet.go): releases are rolled out to this machine from outside, so it neither
	// compares its programs with the hub's nor replaces them by itself. Nil keeps the behaviour above.
	Fleet *Fleet
	// MinGap is the shortest time between an update and the next one Run applies by itself (window.go); zero is no
	// window. StateFile remembers the last update across the restart it causes; Now is the clock (time.Now when nil).
	MinGap    time.Duration
	StateFile string
	Now       func() time.Time
	// contains filtered or unexported fields
}

Updater checks and applies. Set HubURL, Files, GOOS and GOARCH.

func (*Updater) Apply

func (u *Updater) Apply(ctx context.Context) error

Apply checks and replaces what differs; Applied runs when something was replaced.

func (*Updater) Check

func (u *Updater) Check(ctx context.Context) (Status, error)

Check compares the installed files with the hub's and records the answer. In fleet mode there is nothing to compare.

func (*Updater) Command

func (u *Updater) Command() string

Command is the shell command that updates this machine by the hub's installer.

func (*Updater) Run

func (u *Updater) Run(ctx context.Context)

Run checks after FirstDelay and then every Interval until ctx ends, applying what it finds when Auto. Start it with go.

func (*Updater) Status

func (u *Updater) Status() Status

Status is the last answer.

func (*Updater) Writable

func (u *Updater) Writable() bool

Writable says whether every file's folder lets this process put a new file there (and so replace the file).

Jump to

Keyboard shortcuts

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