Documentation
¶
Overview ¶
Package osupdate reads the package and kernel state already present on an apt host. It never refreshes package lists and its only apt invocation is a simulation.
Index ¶
- Constants
- Variables
- func BootIDHash(bootID string) string
- func CanAdvertiseCapability(goos string, uid int, underSystemd, hasSystemdRun bool) bool
- func CapabilityAvailable() bool
- func IsRoot() bool
- func ParseSpec(action, mode, reboot, jobID string) (Spec, *Refusal)
- func SystemdRun(exe, statusPath string) func(context.Context, Spec) error
- func ValidJobID(s string) bool
- func WriteStatus(path string, s Status) error
- type Answer
- type Config
- type Controller
- func (c *Controller) Active() bool
- func (c *Controller) Current() (Status, bool)
- func (c *Controller) Poll(onEnd func(Status))
- func (c *Controller) SetSettled(f func() (bool, int))
- func (c *Controller) Start(ctx context.Context, spec Spec) Answer
- func (c *Controller) Supported() *Refusal
- func (c *Controller) Watch(ctx context.Context, every time.Duration, onEnd func(Status))
- type Failure
- type Host
- type Job
- type Monitor
- type Reader
- type Refusal
- type Runner
- type Spec
- type Status
Constants ¶
const ( AnswerStarted = "started" AnswerRunning = "running" AnswerUnsupported = "unsupported" // AnswerFinished: the request repeats the job id of the last job, which is over. Nothing is started; Result, Code and // Reason are that job's. AnswerFinished = "finished" )
Answers of Controller.Start: the params.state of the CommandResult of UpdateOs (agent.proto "OS UPDATES").
const ( // JobTimeout bounds the waits and quick steps of a job. An apt that has started is never cut by it: dpkg killed in the // middle of a transaction leaves the host half configured. Only the unit's RuntimeMaxSec stops a hung one. JobTimeout = 60 * time.Minute // LockWait is how long the job waits for another package manager before it starts. LockWait = 15 * time.Minute // UpdateTimeout cuts "apt-get update" (it is not a dpkg transaction, so cutting it is safe). UpdateTimeout = 5 * time.Minute // RebootGrace is the pause between writing the "rebooting" status and the reboot command: it lets the agent see the // phase and tell the panel before the host goes down. RebootGrace = 10 * time.Second // RebootWait is how long the job waits for the host to go down after the reboot command was accepted. RebootWait = 10 * time.Minute // MinUptime is the shortest time a host must have been up before a job reboots it: a panel that asks again and again // cannot keep a node in a reboot loop. MinUptime = 10 * time.Minute // RuntimeMaxSec is the unit's backstop behind JobTimeout. RuntimeMaxSec = 4500 )
const ( FingerprintInterval = 5 * time.Minute FullReadInterval = 6 * time.Hour )
const ( RebootsFileName = "os-reboots.json" MaxRebootsHour = 1 MaxRebootsDay = 3 )
The reboot history: a node reboots for the panel's jobs at most once an hour and three times a day, however many commands arrive and whatever the panel (or whoever holds it) asks. It is a file next to the job's status file, so it survives a restart of the agent and the reboot itself. Jobs started by hand (manual- ids of the command line) are not limited: the owner is at the keyboard. A history that cannot be trusted (unreadable, or ahead of the clock) stops a panel job's reboot.
const ( ActionRefresh = "refresh" ActionUpgrade = "upgrade" ActionReboot = "reboot" ModeSecurity = "security" ModeAll = "all" RebootNever = "never" RebootIfRequired = "if_required" RebootAlways = "always" )
The enumerated vocabulary of a job. Nothing else is ever accepted from the wire or the command line.
const ( CodeUnsupportedOS = "unsupported_os" CodeNoSystemd = "no_systemd" CodeBadRequest = "bad_request" CodeBusy = "busy" CodeDiskFull = "disk_full" CodeAptLock = "apt_lock" CodeDpkgBroken = "dpkg_broken" CodeSecuritySource = "security_source_failed" CodeRefreshFailed = "refresh_failed" CodeInstallFailed = "install_failed" CodeAutoReboot = "auto_reboot_conflict" CodeDpkgInterrupted = "dpkg_interrupted" CodeAwgModuleMissing = "awg_module_missing" CodeBootFull = "boot_full" CodeInitramfsMissing = "initramfs_missing" CodeRebootFailed = "reboot_failed" CodeTimeout = "timeout" CodeInterrupted = "interrupted" CodeCancelled = "cancelled" CodeLaunchFailed = "launch_failed" CodeKernelNotSwitched = "kernel_not_switched" CodeAwgNotLoaded = "awg_module_not_loaded" CodeInboundFailed = "inbound_failed" // CodeKernelUnknown: the kernel the next boot starts could not be told, so no check of it is possible. CodeKernelUnknown = "kernel_unknown" // CodeKernelOlder: the next boot would start an older kernel than the running one. CodeKernelOlder = "kernel_older" // CodeAwgBuildFailed: the AmneziaWG module's own DKMS build failed. The job stops; nothing is removed or installed after it. CodeAwgBuildFailed = "awg_module_build_failed" // CodeBootDefaultCustom: what GRUB starts is not "the newest kernel": a custom default, a saved or next entry, or not GRUB. CodeBootDefaultCustom = "boot_default_custom" // CodeBootEntryMissing: /boot/grub/grub.cfg does not name the image of the kernel the next boot starts. CodeBootEntryMissing = "boot_entry_missing" // CodeRebootLimit: the node reboots at most once an hour and three times a day for jobs of the panel. CodeRebootLimit = "reboot_limit" // CodeTooSoon: the host booted less than MinUptime ago; a second reboot so soon is not done. CodeTooSoon = "too_soon" )
Codes of a refusal or a failed job (OsJob.code). The vocabulary is part of agent.proto "OS UPDATES".
const ( PhasePreflight = "preflight" PhaseWaitingLock = "waiting_lock" PhaseRepairing = "repairing" PhaseRefreshing = "refreshing" PhaseInstalling = "installing" PhaseAwgModule = "awg_module" PhaseChecking = "checking" PhaseRebooting = "rebooting" )
Job phases (OsJob.phase).
const ( StateRunning = "running" StateDone = "done" StateFailed = "failed" RebootDone = "done" RebootNotRequired = "not_required" RebootHeld = "held" RebootNotAsked = "not_asked" )
Job states (OsJob.state) and the reboot results (OsJob.reboot).
const ( // Stale is how long a running job may go without a heartbeat before the agent calls it dead. Stale = 2 * time.Minute // HeartbeatEvery is the job's heartbeat. HeartbeatEvery = 15 * time.Second )
const NoteSecurityLeftoverFailed = "security_leftover_failed"
NoteSecurityLeftoverFailed is a non-fatal result note: unattended-upgrade completed, but its named security leftovers did not install.
const SettleMax = 5 * time.Minute
SettleMax is how long the agent waits, after a reboot, for the engines to be restored before it reports the result.
const StatusFileName = "os-update.json"
StatusFileName is the job's state file in the agent's state directory (mode 0600). The job writes it with a heartbeat; the agent reads it, also after its own restart and after a reboot of the host.
const UnitName = "mistgate-os-update"
UnitName is the transient systemd unit a job lives in: `journalctl -u mistgate-os-update` is where its output is. systemd refuses a second unit of the same name while one exists, which is one more guard against two jobs.
Variables ¶
var Codes = []string{CodeUnsupportedOS, CodeNoSystemd, CodeBadRequest, CodeBusy, CodeDiskFull, CodeAptLock, CodeDpkgBroken, CodeSecuritySource, CodeRefreshFailed, CodeInstallFailed, CodeAutoReboot, CodeDpkgInterrupted, CodeAwgModuleMissing, CodeBootFull, CodeInitramfsMissing, CodeRebootFailed, CodeTimeout, CodeInterrupted, CodeCancelled, CodeLaunchFailed, CodeKernelNotSwitched, CodeAwgNotLoaded, CodeInboundFailed, CodeKernelUnknown, CodeKernelOlder, CodeAwgBuildFailed, CodeTooSoon, CodeBootDefaultCustom, CodeBootEntryMissing, CodeRebootLimit}
Codes lists every code a job or a refusal can carry; the panel checks an incoming job against it.
var Phases = []string{PhasePreflight, PhaseWaitingLock, PhaseRepairing, PhaseRefreshing, PhaseInstalling, PhaseAwgModule, PhaseChecking, PhaseRebooting}
Phases lists the phases of a running job.
var RebootBlockers = []string{CodeInitramfsMissing, CodeBootEntryMissing, CodeAwgModuleMissing, CodeDpkgInterrupted, CodeKernelOlder, CodeBootDefaultCustom}
RebootBlockers are the codes of Codes that the reader's reboot preview (OsStatus.reboot_blockers) can carry.
Functions ¶
func BootIDHash ¶
BootIDHash is the first 16 hex characters of the SHA-256 of a boot id (the contents of /proc/sys/kernel/random/boot_id): what OsStatus.boot_id_hash carries, so that the panel can tell its own server from another one without a reading of its own.
func CanAdvertiseCapability ¶
CanAdvertiseCapability is the pure part of capability detection, exposed for platform-matrix tests.
func CapabilityAvailable ¶
func CapabilityAvailable() bool
CapabilityAvailable is deliberately strict: S1 reads are offered only from the supported root systemd agent unit.
func IsRoot ¶
func IsRoot() bool
IsRoot reports whether the current process has the privileges required for panel-host reads in v1.
func ParseSpec ¶
ParseSpec checks the enumerated fields of UpdateOs (or of the command line). Allowed combinations: refresh + never; upgrade + (security | all) + (never | if_required); reboot + (if_required | always). The reboot value of the command line may be spelled if-required. An empty jobID is accepted: the caller makes one.
func SystemdRun ¶
SystemdRun starts a job as a transient root unit. The unit has no sandbox of its own (a package install needs the whole system) and none of the agent's: it is a separate process tree outside the agent's cgroup and its memory limit, so the agent's unit is not loosened for it and an agent restart does not stop the job. systemd-run returns when the unit starts; how the job ends is in its status file.
func ValidJobID ¶
ValidJobID: an id made by the panel (osj_...) or by a hand-started run (manual-<unix>).
func WriteStatus ¶
WriteStatus replaces the file atomically and flushes it: the file with phase "rebooting" has to be on disk when the host goes down.
Types ¶
type Answer ¶
type Answer struct {
State string
Code, Reason string
JobID string
Since int64
Result string // finished: done or failed
}
Answer says what happened to a request. Code and Reason are set for "unsupported"; JobID and Since (Unix seconds) for "started", "running" and "finished".
type Config ¶
type Config struct {
StatusPath string
Host Host
// Launch starts the job detached from the caller (a transient systemd unit); the job writes StatusPath.
Launch func(ctx context.Context, spec Spec) error
// Excluded names the other host work that is going on (an agent update, a unit refresh, the AmneziaWG module build,
// the security-updates task), "" when there is none. A job never runs next to one of them.
Excluded func(ctx context.Context) string
// Settled is asked after a reboot: whether the node restored its engines, and how many inbounds failed to come up.
// Nil = nothing to wait for.
Settled func() (settled bool, failedInbounds int)
Now func() time.Time
}
Config is what the agent hands the Controller: the real machine and launcher, or fakes in a test.
type Controller ¶
type Controller struct {
// contains filtered or unexported fields
}
Controller is the agent side of OS jobs: it checks and starts one, allows only one at a time, follows it through its status file (also across an agent restart and a reboot) and reports how each job ended. It installs nothing itself.
func New ¶
func New(cfg Config) *Controller
func (*Controller) Active ¶
func (c *Controller) Active() bool
Active says whether an OS job is going right now (its heartbeat is fresh). Other host work asks it before it starts.
func (*Controller) Current ¶
func (c *Controller) Current() (Status, bool)
Current is the job OsStatus.job carries: the running one, or the last one not reported yet.
func (*Controller) Poll ¶
func (c *Controller) Poll(onEnd func(Status))
Poll looks at the status once. A job whose heartbeat stopped is finished here: done when the host rebooted as the job said it would (and the node came back as expected), failed otherwise. A finished job that was not reported yet is handed to onEnd, then marked reported. Call it every few seconds.
func (*Controller) SetSettled ¶
func (c *Controller) SetSettled(f func() (bool, int))
SetSettled sets the after-reboot question (the agent that owns the engines exists only after the Controller does).
func (*Controller) Start ¶
func (c *Controller) Start(ctx context.Context, spec Spec) Answer
Start begins a job. Anything that is not a start is a no-op that says why, so a repeated request while a job runs changes nothing. A job that cannot even be launched is "unsupported" with code launch_failed.
func (*Controller) Supported ¶
func (c *Controller) Supported() *Refusal
Supported is the cheap part of the preflight the agent can answer without root work: a system the job runs on, with systemd. The job checks it again.
type Failure ¶
type Failure struct {
Code, Detail, Package string
AptLockHolder string
AptLockMinutes uint32
// Reasons are all codes that blocked a reboot, the first being Code.
Reasons []string
}
Failure is why a job did not end well. Code is one of the Code* constants; Detail is one short English sentence (what the status file, the event and the UI carry, never package-manager output); Package is the package at fault, when one is.
type Host ¶
type Host struct {
ReadFile func(path string) ([]byte, error)
// WriteFile replaces a file atomically (the module source's compat.h is repaired through it).
WriteFile func(path, body string) error
// Size is the size of a file, ok = false when there is none.
Size func(path string) (int64, bool)
// Glob lists the paths that match a pattern.
Glob func(pattern string) []string
// FreeMB is the free space of the filesystem holding path; ok = false when it cannot be read.
FreeMB func(path string) (int64, bool)
// AptBusy says whether dpkg, apt or unattended-upgrades hold a lock.
AptBusy func() bool
// AptLockInfo returns the validated process name holding an apt lock, when readable.
AptLockInfo func() (string, int64)
// HoldAptLock takes the dpkg frontend lock and keeps it until release is called (or the process ends), so that no other
// package manager starts between the last check before a reboot and the reboot. An error means somebody holds it.
HoldAptLock func() (release func(), err error)
// BuilderLock is the same non-blocking AmneziaWG lock as prepare-kernel and kmod-sync.
BuilderLock func() (release func(), acquired bool, err error)
// Sleep waits d or until ctx ends.
Sleep func(ctx context.Context, d time.Duration)
Now func() time.Time
}
Host is the part of the machine a job looks at besides the commands it runs. The real one reads the live system; a test builds a fake, so no test touches the host it runs on.
func RealHost ¶
func RealHost() Host
RealHost is the live machine. The lock probe needs root (it opens the lock files for writing).
func (Host) BootID ¶
BootID is the kernel's id of this boot: it changes when, and only when, the host restarts.
func (Host) KernelRunning ¶
KernelRunning is the release of the running kernel.
func (Host) ModuleLoaded ¶
ModuleLoaded: the AmneziaWG kernel module is loaded now.
type Job ¶
type Job struct {
Spec Spec
StatusPath string // "" = no status file
Timeout time.Duration
LockWait time.Duration
Out io.Writer
Run awgprep.Runner
Host Host
Heartbeat time.Duration
// RebootLogPath is where the reboots of panel jobs (osj_) are counted; "" = os-reboots.json next to StatusPath.
RebootLogPath string
// RebootGrace and RebootWait are zero in production (the constants above); tests shorten them.
RebootGrace time.Duration
RebootWait time.Duration
}
Job is one run of an OS job (what `mistgate-node host os-update --yes` does): preflight, lock wait, repair, refresh, install, the AmneziaWG module for a new kernel, the reboot checks and, as the very last step, the reboot. It writes StatusPath, which the agent follows.
type Monitor ¶
type Monitor struct {
// contains filtered or unexported fields
}
Monitor runs the expensive read only when apt/dpkg/boot inputs change, and at least every six hours. Fingerprinting itself is filesystem metadata only.
func NewMonitor ¶
func (*Monitor) Poll ¶
Poll checks filesystem metadata and reads only when forced, changed, or six hours have passed. It returns the newest result, whether the public snapshot changed, and whether a full read ran.
type Reader ¶
Reader inspects the host. Root is a test-only filesystem root; commands should be replaced when it is set.
type Refusal ¶
type Refusal struct {
Code, Reason string
}
Refusal is a request the node will not run, with the code the caller gets back.
type Runner ¶
Runner executes one local command and returns its combined output. Tests replace it with fixture-backed responses.
type Spec ¶
type Spec struct {
JobID string
Action string
Mode string
Reboot string
// AwgRequired: AmneziaWG inbounds run on the kernel module, so a reboot into a kernel without the module is refused.
// The agent sets it from the backend the engine really uses; the job also looks at the module's use count itself.
AwgRequired bool
}
Spec is one job as the node understands it. Every field is checked by ParseSpec; a Spec never carries free text.
type Status ¶
type Status struct {
JobID string `json:"job_id"`
Action string `json:"action"`
Mode string `json:"mode,omitempty"`
// RebootPolicy is the reboot value of the request (never | if_required | always).
RebootPolicy string `json:"reboot_policy"`
State string `json:"state"`
Phase string `json:"phase,omitempty"`
Started int64 `json:"started"` // Unix seconds, the host clock
Updated int64 `json:"updated"` // the last heartbeat
Finished int64 `json:"finished,omitempty"`
// Back is when the agent first saw the host on a new boot (a job that rebooted it).
Back int64 `json:"back,omitempty"`
Code string `json:"code,omitempty"`
Reason string `json:"reason,omitempty"` // one fixed English sentence, never package-manager output
NoteCode string `json:"note_code,omitempty"`
Note string `json:"note,omitempty"`
Package string `json:"package,omitempty"`
AptLockHolder string `json:"apt_lock_holder,omitempty"`
AptLockMinutes uint32 `json:"apt_lock_minutes,omitempty"`
Reasons []string `json:"reasons,omitempty"` // every code that blocked the reboot
Upgraded uint32 `json:"upgraded,omitempty"`
Reboot string `json:"reboot,omitempty"`
HeldReason string `json:"held_reason,omitempty"`
SourcesFailed []string `json:"sources_failed,omitempty"`
KernelFrom string `json:"kernel_from,omitempty"`
KernelTo string `json:"kernel_to,omitempty"`
KernelNow string `json:"kernel_now,omitempty"`
BootID string `json:"boot_id,omitempty"` // the boot the job started on
AwgRequired bool `json:"awg_required,omitempty"`
// AwgSource says what the job found in the module's source: "patched" (it repaired a known-bad compat.h) or
// "unknown:<12 hex of its sha256>" (a file Mistgate does not know, left as it was). Empty = nothing to say.
AwgSource string `json:"awg_source,omitempty"`
Reported bool `json:"reported,omitempty"`
}
Status is the state file. The job is its only writer until it ends; after that the agent writes it, once, to set Reported (and, for a job that rebooted the host, to record how the node came back).
func ReadStatus ¶
ReadStatus returns the status at path; ok is false when there is none (never ran, or unreadable garbage).