Documentation
¶
Overview ¶
Package awgprep puts the AmneziaWG kernel module on a node.
Two callers share it. `mistgate-node awg prepare-kernel` is the explicit, root-only command: it prints the plan and runs it with --yes. The agent (Controller, ctl.go) starts the same command, in the background, when the panel asks for it ("awg-prepare/1", agent.proto "AWG AND WARP"): the agent never installs a package inside its own hardened unit; it starts a separate transient systemd unit that runs the command, and follows it through a status file (status.go).
The userspace backend (amneziawg-go inside the agent) is the default and needs none of this; the module is for nodes where its much smaller per-peer memory matters (1.8 KiB against 26 KiB).
Index ¶
- Constants
- func CompatChanged(rs []CompatResult) bool
- func CompatErr(rs []CompatResult) error
- func CompatUnknownSHA(rs []CompatResult) string
- func DKMSFailureKernel(out string) string
- func ExecRunner(ctx context.Context, w io.Writer, dir string, cmd ...string) (string, error)
- func FileLocked(path string) bool
- func IsAptLockOutput(out string) bool
- func KmodDKMSInstalled(ctx context.Context, run Runner) (bool, error)
- func KmodHookBody(nodePath, stateDir string) (string, error)
- func KmodSystemdArgs(exe, statusPath string, mode KmodMode) ([]string, error)
- func KmodSystemdRun(exe, statusPath string, mode KmodMode) func(context.Context) error
- func ModuleReady() bool
- func OwnDKMSFailure(out string) bool
- func ParseOSRelease(r io.Reader) map[string]string
- func RealSourceDirs() []string
- func Run(ctx context.Context, w io.Writer, steps []Step, src string, run Runner, ...) error
- func RunKmodSync(ctx context.Context, cfg KmodConfig) error
- func SafePath(p string) bool
- func Short(err error) (code, detail string)
- func SystemdRun(exe, statusPath string) func(ctx context.Context) error
- func TryBuilderLock() (func(), bool, error)
- func UnknownSourceNote(sha12 string) string
- func Verify(w io.Writer, sys Sys) error
- func WaitAptLock(ctx context.Context, w io.Writer, steps []Step, sys Sys, max time.Duration) error
- func WriteKmodStatus(path string, st KmodStatus) error
- func WriteStatus(path string, s Status) error
- type Answer
- type CompatResult
- type CompatState
- type Config
- type Controller
- type Env
- type Failure
- type FileOp
- type Job
- type KmodConfig
- type KmodController
- type KmodMode
- type KmodRebuild
- type KmodStatus
- type Progress
- type Runner
- type Status
- type Step
- type Sys
- type Unsupported
Constants ¶
const ( AnswerReady = "ready" // the module is loaded and usable AnswerNeedsPrepare = "needs_prepare" // it is not, and a run is possible AnswerStarted = "started" // a run began just now AnswerRunning = "running" // one is going already AnswerUnsupported = "unsupported" // it cannot be done here )
Answers of Controller.Check and Start: the "state" of the CommandResult of PrepareAwgKernel (agent.proto).
const ( StateRunning = "running" StateDone = "done" StateFailed = "failed" )
Status states, as the job writes them.
const ( // JobTimeout is the hard limit of one run: up to 30 minutes for package-manager locks, then time to install and build. JobTimeout = 45 * time.Minute // LockWait bounds the wait for package-manager locks before the first command. Fresh VPS images can run unattended // upgrades for several minutes after boot; five minutes made the panel fail while that normal work was still running. LockWait = 30 * time.Minute // Stale is how long a "running" status may go without a heartbeat before the agent calls the job dead. Stale = 2 * time.Minute )
const ( KmodHookPath = "/etc/apt/apt.conf.d/99mistgate-awg" KmodUnitName = "mistgate-awg-kmod" KmodStatusFileName = "awg-kmod.json" KmodBootBudget = 180 * time.Second KmodRuntimeMaxSec = 240 KmodUnitMaxSec = 3600 KmodRunBudget = 55 * time.Minute KmodLockWait = 30 * time.Minute KmodHeartbeat = 5 * time.Second KmodStatusStale = 30 * time.Second )
const ( CodeContainer = "container" CodeDistro = "distro" CodeUnknownKernel = "unknown_kernel" CodeSecureBoot = "secure_boot" CodeNoSystemd = "no_systemd" CodeTimeout = "timeout" CodeAptLock = "apt_lock" CodeStepFailed = "step_failed" CodeSourceMoved = "source_moved" CodeModuleNotLoad = "module_not_loaded" CodeModuleUnusable = "module_unusable" CodeBuildFailed = "module_build_failed" // the module does not compile for this kernel (an API it has no answer for yet) CodeInterrupted = "interrupted" CodeLaunchFailed = "launch_failed" CodeBusy = "busy" )
Codes of Unsupported.Code and Failure.Code: a stable vocabulary (agent.proto "AWG AND WARP"), the UI words them.
const BuilderLockPath = "/run/mistgate-awg-kmod.lock"
const UnitName = "mistgate-awg-prepare"
UnitName is the transient systemd unit the automatic run lives in: `journalctl -u mistgate-awg-prepare` is where its full output is. systemd refuses a second unit of the same name while one runs, which is one more guard against two runs.
Variables ¶
This section is empty.
Functions ¶
func CompatChanged ¶
func CompatChanged(rs []CompatResult) bool
CompatChanged says whether any result is a file that was patched.
func CompatErr ¶
func CompatErr(rs []CompatResult) error
CompatErr is the first read or write failure among the results.
func CompatUnknownSHA ¶
func CompatUnknownSHA(rs []CompatResult) string
CompatUnknownSHA is the start of the hash of the first file Mistgate does not know, "" when there is none.
func DKMSFailureKernel ¶
DKMSFailureKernel is the kernel release the dkms failure in the output is for, "" when it does not name one.
func ExecRunner ¶
ExecRunner is the real Runner: the command's output goes to w and is returned. apt never asks (DEBIAN_FRONTEND), the messages are in English (the lock detection reads them) and needrestart only lists what it would restart: a package install must not restart the services of a production node behind the owner's back.
func FileLocked ¶
FileLocked says whether another process holds a POSIX record lock on the file at path (a missing or unreadable file is not locked). The caller must be able to open it for writing: run as root.
func IsAptLockOutput ¶ added in v0.1.67
IsAptLockOutput reports whether apt or dpkg said that another package manager holds a lock.
func KmodDKMSInstalled ¶
KmodDKMSInstalled accepts held and half-configured installed packages by their dpkg state letter.
func KmodHookBody ¶
func KmodSystemdArgs ¶
func KmodSystemdRun ¶
func ModuleReady ¶
func ModuleReady() bool
ModuleReady says whether the module is loaded and speaks AWG 3.1: what the engine needs to take the kernel backend.
func OwnDKMSFailure ¶
OwnDKMSFailure reports whether apt or dpkg output shows the AmneziaWG module's own DKMS build failing.
func ParseOSRelease ¶
ParseOSRelease reads KEY=value lines (values may be quoted).
func RealSourceDirs ¶
func RealSourceDirs() []string
RealSourceDirs lists the module source trees of this machine.
func Run ¶
func Run(ctx context.Context, w io.Writer, steps []Step, src string, run Runner, sys Sys, limit time.Duration, progress Progress) error
Run executes the plan (steps already have {src} replaced by src) and then verifies the module: the module is loaded (/sys/module, not modinfo: on ARM two trees can hold one name), speaks genl v3 with room for the 3.1 attributes, and is loaded at boot (modules-load.d). Nothing is rolled back on failure, except the module's own packages when it did not build (buildFailure); the error says where it stopped. limit is only used to word a timeout (the caller owns the deadline of ctx).
func RunKmodSync ¶
func RunKmodSync(ctx context.Context, cfg KmodConfig) error
RunKmodSync implements the root-only command. Patch-only never reads package state or writes any file except known compat.h files; the other modes use the common lock and the live job heartbeats to avoid overlapping another builder.
func SafePath ¶
SafePath is the existing systemd path rule shared by unit rendering and hook generation.
func Short ¶
Short returns the Failure behind err (a plain error is a step failure), for the status file.
func SystemdRun ¶
SystemdRun launches the job as a transient systemd unit: root, outside the agent's sandbox and its cgroup limits (the agent's unit has ProtectSystem=strict, a tiny capability set and MemoryMax; a package install and a compiler need none of those restrictions removed from the agent, they need to not be the agent). The unit also outlives an agent restart. RuntimeMaxSec is the backstop behind the job's own timeout. systemd-run returns once the unit started; how the job ends is in its status file.
func TryBuilderLock ¶
TryBuilderLock takes the one non-blocking lock shared by every AmneziaWG module builder.
func UnknownSourceNote ¶
UnknownSourceNote words the reason a build fails on a source Mistgate does not know.
func Verify ¶
Verify is also the whole of --verify-only. A module that works but cannot be set to load at boot is a failure: the node would lose it at the next reboot, and "kernel" mode has no fallback.
func WaitAptLock ¶
WaitAptLock waits, at most max, until no other package manager holds the dpkg or apt lock, instead of letting the first apt-get fail at once. It returns nil when the lock is free or the plan uses no apt; an apt_lock Failure when it never was.
func WriteKmodStatus ¶
func WriteKmodStatus(path string, st KmodStatus) error
func WriteStatus ¶
WriteStatus replaces the file atomically.
Types ¶
type Answer ¶
Answer says what is the case on this node. Code and Reason are set for "unsupported"; Kernel for "started" and "needs_prepare"; Since (Unix seconds) for "running" and "started".
type CompatResult ¶
type CompatResult struct {
State CompatState
Path string
SHA12 string // the first 12 hex characters of the sha256 the file had when it was read ("" = unreadable or absent)
Changed bool
Err string // why a read or a write failed
}
CompatResult is the outcome for one compat.h.
func FixCompat ¶
FixCompat looks at <dir>/compat/compat.h for every module source dir (the DKMS trees under /usr/src, or the clone of the Debian recipe's src/ directory) and repairs a known-bad one. check = true changes nothing. One result per dir, in the order of dirs; what it did is also written to w (nil = nowhere). sys needs ReadFile and, unless check, WriteFile (atomic: a temporary file and a rename, so a failure leaves the old file).
type CompatState ¶
type CompatState string
CompatState says what FixCompat found in one compat.h.
const ( CompatAbsent CompatState = "absent" // the source has no compat/compat.h (not installed) CompatOK CompatState = "ok" // a file known to build on every kernel (also one this function patched earlier) CompatPatched CompatState = "patched" // the known-bad file was replaced just now CompatNeedsPatch CompatState = "needs_patch" // a known-bad file; check mode, or the patch could not be written (Err says) CompatUnknown CompatState = "unknown" // a file Mistgate does not know: nothing was changed )
type Config ¶
type Config struct {
StatusPath string
// Env reads the machine (os-release, kernel, container, Secure Boot, systemd).
Env func(ctx context.Context) Env
// Ready says whether the module is loaded and usable (the same probe the engine uses to take it).
Ready func() bool
// Launch starts the job detached from the caller (a transient systemd unit); the job writes StatusPath.
Launch func(ctx context.Context) error
Now func() time.Time // nil = time.Now (the host clock: the job writes the host clock too)
}
Config is what the agent hands the Controller: the real machine, or a fake in a test.
type Controller ¶
type Controller struct {
// contains filtered or unexported fields
}
Controller is the agent side of the automatic preparation: it decides whether a run is needed and possible, starts one, allows only one at a time, and reports how each run ended. It installs nothing itself.
func New ¶
func New(cfg Config) *Controller
func (*Controller) Check ¶
func (c *Controller) Check(ctx context.Context) Answer
Check answers without changing anything (the dry run).
func (*Controller) Poll ¶
func (c *Controller) Poll(onEnd func(Status))
Poll looks at the status once. A run whose heartbeat stopped is declared failed (the host rebooted, the unit was killed); a finished run that was not reported yet is handed to onEnd, then marked reported. Call it every few seconds.
func (*Controller) Start ¶
func (c *Controller) Start(ctx context.Context) Answer
Start begins a run when one is needed and possible. Anything else is a no-op that says why (ready, running, unsupported), so a repeated request while a run is going changes nothing. A job that cannot even be launched is "unsupported" with code launch_failed: the automatic way does not work on this node, the manual one still does.
type Env ¶
type Env struct {
OSRelease map[string]string // /etc/os-release
Kernel string // uname -r
NodePath string // the installed node binary, for the Ubuntu apt hook
StateDir string // the agent's state directory, for the Ubuntu apt hook
CPUs int
Container string // virtualisation of a container kind ("lxc", "openvz", "docker", ...), "" = none
SecureBoot bool
Systemd bool // systemd-run is there and systemd is the init (the automatic run needs it)
// Leftover are the module's packages an earlier run left half-installed (dpkg unpacked or half-configured): apt
// refuses every install on the host until they are configured or gone.
Leftover []string
}
Env is what the plan depends on; the Linux code reads it from the machine (real_linux.go), a test builds it by hand.
type Failure ¶
type Failure struct {
Code, Detail, Long string
}
Failure is why a run did not end with a loaded module. 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: that is in the journal of the job); Long, when set, is the fuller text the command prints to a person.
type FileOp ¶ added in v0.1.49
FileOp is one file change in a plan. Remove deletes a file if it exists; otherwise Run writes Body atomically with mode 0644, creating its parent directory with mode 0755.
type Job ¶
type Job struct {
StatusPath string // "" = no status file (a run by hand)
Timeout time.Duration // 0 = JobTimeout
Out io.Writer
Env Env
Auto bool // PlanAuto instead of Plan (a run the panel asked for)
Run Runner
Sys Sys
Src string
Now func() time.Time // nil = time.Now
Heartbeat time.Duration // 0 = 15 s
}
Job is one run of the plan: what `awg prepare-kernel --yes` does, plus a hard timeout, a bounded wait for the apt lock and, when StatusPath is set, the status file the agent follows.
type KmodConfig ¶
type KmodConfig struct {
Mode KmodMode
StatusPath string
NodePath string
StateDir string
Out io.Writer
Run Runner
Sys Sys
SecureBoot func(context.Context) bool
Now func() time.Time
Heartbeat time.Duration
Budget time.Duration // boot only; zero = KmodBootBudget
LockWait time.Duration // after-apt and repair only; zero = KmodLockWait
}
type KmodController ¶
type KmodController struct {
StatusPath string
NeedBoot func() bool
Launch func(context.Context) error
Now func() time.Time
// contains filtered or unexported fields
}
KmodController launches a boot sync and exposes the heartbeat to inbound reconciliation.
func NewKmodController ¶
func (*KmodController) Active ¶
func (c *KmodController) Active() bool
Active reports a fresh unit heartbeat.
func (*KmodController) Current ¶
func (c *KmodController) Current() (KmodStatus, bool)
Current returns the last status, whether or not its heartbeat is fresh.
func (*KmodController) Running ¶
func (c *KmodController) Running() (KmodStatus, bool)
type KmodRebuild ¶
type KmodStatus ¶
type KmodStatus struct {
Mode KmodMode `json:"mode"`
State string `json:"state"`
Started int64 `json:"started"`
Updated int64 `json:"updated"`
Rebuilt []KmodRebuild `json:"rebuilt,omitempty"`
Failed []KmodRebuild `json:"failed,omitempty"`
}
KmodStatus is shared by the apt hook, the transient unit and the agent. Rebuilt is persisted in the same file so a module that failed to load cannot trigger an endless rebuild on every agent start.
func ReadKmodStatus ¶
func ReadKmodStatus(path string) (KmodStatus, bool, error)
type Progress ¶
type Progress func(i, n int)
Progress is told before step i of n (1-based) starts. Optional.
type Runner ¶
Runner executes one command and returns its combined output (also streamed to w by the real one).
type Status ¶
type Status struct {
State string `json:"state"`
Kernel string `json:"kernel,omitempty"` // the release the module is built for
Started int64 `json:"started"` // Unix seconds, the host clock
Updated int64 `json:"updated"` // the last heartbeat
Finished int64 `json:"finished,omitempty"`
Step int `json:"step,omitempty"`
Steps int `json:"steps,omitempty"`
Code string `json:"code,omitempty"` // failed: a Code* constant
Reason string `json:"reason,omitempty"` // failed: one short English sentence
Reported bool `json:"reported,omitempty"`
}
Status is the file the job writes in the agent's state directory (mode 0600) and the agent reads. The job is the only writer until it ends; after that only the agent writes, once, to set Reported.
type Step ¶
type Step struct {
Desc string
Cmd []string
Files []FileOp
Dir string
Check func(out string) error
// Prep runs before the command, with the source directory ({src} replaced): the Debian recipe makes the module source
// right here (FixCompat) before the compiler sees it. An error fails the step.
Prep func(src string, w io.Writer) error
// Build marks the step that compiles the module: its failure is module_build_failed. An apt step is one too when its
// output shows the DKMS build of the module failing.
Build bool
// Undo runs when the step fails because the module did not build. A DKMS package whose build failed stays
// half-configured, and apt then refuses every later install on the host; Undo removes it again.
Undo []string
// RunKernel is the release of the running kernel the plan was made for. Undo only removes the module when the failed build
// was for that kernel: a build that fails for another (the new kernel's headers configured on the side) leaves the module
// that works for the running kernel alone. "" = not known, which keeps the removal.
RunKernel string
}
Step is one command or a set of file changes in the plan. Dir is optional. Check, when set, runs after the command and fails the step with its error (the pinned commit of the clone).
func Plan ¶
Plan returns the steps for this machine, or an *Unsupported that says why the module cannot be installed here. notes are facts the owner should read before confirming.
type Sys ¶
type Sys struct {
WriteFile func(path, body string) error
RemoveFile func(path string) error
// ReadFile reads a file (the module source's compat.h). Nil = unavailable.
ReadFile func(path string) ([]byte, error)
// SourceDirs lists the DKMS module source trees (/usr/src/amneziawg-*). Nil = none.
SourceDirs func() []string
Exists func(path string) bool
// Probe asks the kernel for the genetlink family: version and maxattr, or an error when it is not loaded.
Probe func() (genlVersion uint32, maxAttr uint32, err error)
// AptBusy says whether another package manager holds the dpkg or apt lock. Nil = never.
AptBusy func() bool
// Sleep waits d or until ctx ends. Nil = the real clock.
Sleep func(ctx context.Context, d time.Duration)
// TryBuilderLock is the shared non-blocking lock for module builders. Nil = no lock (a test fake).
TryBuilderLock func() (release func(), acquired bool, err error)
// KernelRelease returns the running kernel. Nil = unavailable.
KernelRelease func() string
}
Sys is the part of the machine the run and the verification touch.
type Unsupported ¶
type Unsupported struct {
Code string // CodeContainer, CodeDistro, CodeUnknownKernel, CodeSecureBoot or CodeNoSystemd
Msg string
}
Unsupported says that the module cannot be put on this machine, and why. It is a fact about the host, not a failure.
func (*Unsupported) Error ¶
func (u *Unsupported) Error() string