awgprep

package
v0.2.0-dev.14 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: AGPL-3.0 Imports: 25 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 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

View Source
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).

View Source
const (
	StateRunning = "running"
	StateDone    = "done"
	StateFailed  = "failed"
)

Status states, as the job writes them.

View Source
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
)
View Source
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
)
View Source
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.

View Source
const BuilderLockPath = "/run/mistgate-awg-kmod.lock"
View Source
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 AptInstall

func AptInstall(ctx context.Context, out io.Writer, run Runner, sys Sys, lockWait time.Duration, what string, args []string) error

AptInstall runs `apt-get args...` (an install) the way the agent's host jobs do: it waits up to lockWait for another package manager to let go of the dpkg and apt locks, never cuts an apt-get that has started when ctx ends (dpkg killed in the middle of a transaction leaves the host half configured; only the unit's RuntimeMaxSec stops a hung one), and on a failure that is not the lock refreshes the package lists and tries once more (a fresh cloud image has none). what names the package for the failure's sentence.

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

func DKMSFailureKernel(out string) string

DKMSFailureKernel is the kernel release the dkms failure in the output is for, "" when it does not name one.

func ExecRunner

func ExecRunner(ctx context.Context, w io.Writer, dir string, cmd ...string) (string, error)

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

func FileLocked(path string) bool

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

func IsAptLockOutput(out string) bool

IsAptLockOutput reports whether apt or dpkg said that another package manager holds a lock.

func KmodDKMSInstalled

func KmodDKMSInstalled(ctx context.Context, run Runner) (bool, error)

KmodDKMSInstalled accepts held and half-configured installed packages by their dpkg state letter.

func KmodHookBody

func KmodHookBody(nodePath, stateDir string) (string, error)

func KmodSystemdArgs

func KmodSystemdArgs(exe, statusPath string, mode KmodMode) ([]string, error)

func KmodSystemdRun

func KmodSystemdRun(exe, statusPath string, mode KmodMode) func(context.Context) error

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

func OwnDKMSFailure(out string) bool

OwnDKMSFailure reports whether apt or dpkg output shows the AmneziaWG module's own DKMS build failing.

func ParseOSRelease

func ParseOSRelease(r io.Reader) map[string]string

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

func SafePath(p string) bool

SafePath is the existing systemd path rule shared by unit rendering and hook generation.

func Short

func Short(err error) (code, detail string)

Short returns the Failure behind err (a plain error is a step failure), for the status file.

func SystemdRun

func SystemdRun(exe, statusPath string) func(ctx context.Context) error

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

func TryBuilderLock() (func(), bool, error)

TryBuilderLock takes the one non-blocking lock shared by every AmneziaWG module builder.

func UnknownSourceNote

func UnknownSourceNote(sha12 string) string

UnknownSourceNote words the reason a build fails on a source Mistgate does not know.

func Verify

func Verify(w io.Writer, sys Sys) error

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

func WaitAptLock(ctx context.Context, w io.Writer, steps []Step, sys Sys, max time.Duration) error

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

func WriteStatus(path string, s Status) error

WriteStatus replaces the file atomically.

Types

type Answer

type Answer struct {
	State        string
	Code, Reason string
	Kernel       string
	Since        int64
}

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

func FixCompat(sys Sys, dirs []string, check bool, w io.Writer) []CompatResult

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.

func (*Controller) Watch

func (c *Controller) Watch(ctx context.Context, every time.Duration, onEnd func(Status))

Watch polls until ctx ends.

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.

func ReadEnv

func ReadEnv(ctx context.Context) Env

ReadEnv reads what the plan depends on from this machine. Everything is best effort: an unreadable fact makes the plan refuse (an unknown kernel, no recipe), never guess.

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.

func (*Failure) Error

func (f *Failure) Error() string

type FileOp added in v0.1.49

type FileOp struct {
	Path   string
	Body   string
	Remove bool
}

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.

func (Job) Do

func (j Job) Do(ctx context.Context) error

Do runs it. The error is a *Failure (Short gives its code); a status file is left behind for it either way.

func (Job) Steps

func (j Job) Steps() ([]Step, []string, error)

Steps is the plan this job would run (and the notes to read first), or why there is none.

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 NewKmodController(statusPath string, needBoot func() bool, launch func(context.Context) error) *KmodController

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)

func (*KmodController) StartBoot

func (c *KmodController) StartBoot(ctx context.Context) bool

type KmodMode

type KmodMode string
const (
	KmodPatchOnly KmodMode = "patch-only"
	KmodBoot      KmodMode = "boot"
	KmodAfterApt  KmodMode = "after-apt"
	KmodRepair    KmodMode = "repair"
)

type KmodRebuild

type KmodRebuild struct {
	Kernel    string `json:"kernel"`
	SourceSHA string `json:"source_sha"`
}

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

type Runner func(ctx context.Context, w io.Writer, dir string, cmd ...string) (string, error)

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.

func ReadStatus

func ReadStatus(path string) (s Status, ok bool, err error)

ReadStatus returns the status at path; ok is false when there is none (never ran, or unreadable garbage).

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

func Plan(e Env) (steps []Step, notes []string, err error)

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.

func PlanAuto

func PlanAuto(e Env) ([]Step, []string, error)

PlanAuto is Plan for the run the panel asks for: it also refuses what only a person can fix halfway through. Secure Boot makes modprobe refuse the unsigned module after hundreds of MB were installed, and the automatic run is started by systemd-run.

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.

func RealSys

func RealSys() Sys

RealSys is the real machine behind Run, Verify and WaitAptLock.

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

Jump to

Keyboard shortcuts

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