awgprep

package
v0.1.81-dev.6 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: AGPL-3.0 Imports: 18 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 (
	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"
)

Codes of Unsupported.Code and Failure.Code: a stable vocabulary (agent.proto "AWG AND WARP"), the UI words them.

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 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 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 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 ParseOSRelease

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

ParseOSRelease reads KEY=value lines (values may be quoted).

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 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 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 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 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
	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 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
	// 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
}

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
	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)
}

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