Documentation
¶
Overview ¶
Package wireguard implements the WireGuard mesh bootstrap logic for the coolify init command (alpha, Coolify v5).
Index ¶
- Constants
- func FirewallServiceUnit(iface string, namespaces []string, containerSubnets []*net.IPNet, ...) string
- func InstallFirewallCommand(iface string, namespaces []string, containerSubnets []*net.IPNet, ...) string
- func MachineIP(subnet *net.IPNet) net.IP
- func PodmanNetworkFor(ns string) string
- func RenderConfig(mgmtIP net.IP, listenPort int, peers []PeerConfig) string
- func ValidateIntent(d *DesiredMesh) error
- func WriteConfigCommand(iface string, mgmtIP net.IP, listenPort int, peers []PeerConfig) string
- type ActionResult
- type ActionType
- type DesiredMesh
- type Intent
- type MeshState
- type NamespaceServerState
- type Peer
- type PeerConfig
- type Plan
- type PlannedAction
- type ServerState
- type SkippedAction
- type VerifyResult
- type Warning
- func Allocate(pool *net.IPNet, hostPrefix int, existing map[string]*net.IPNet, ...) (map[string]*net.IPNet, []Warning, error)
- func AllocateMgmtIPs(pool *net.IPNet, existing map[string]net.IP, hosts []string) (map[string]net.IP, []Warning, error)
- func AllocateNamespaced(pool *net.IPNet, hostPrefix int, existing map[string]map[string]*net.IPNet, ...) (map[string]map[string]*net.IPNet, []Warning, error)
Constants ¶
const AllowRulesPath = "/etc/coolify/allow.rules"
AllowRulesPath is the on-disk location where coold snapshots the COOLIFY-ALLOW chain as an iptables-restore fragment on every rule mutate. The firewall unit reads this file at boot/restart to repopulate the chain after the kernel tables are cleared.
const BridgeAllowRulesPath = "/etc/coolify/allow.nft"
BridgeAllowRulesPath is where coold writes the nft bridge-family allow fragment. The firewall unit replays it at start/restart.
const BridgeScaffoldPath = "/etc/coolify/bridge-fw.nft"
BridgeScaffoldPath is where the CLI writes the static bridge chain scaffold (forward + coolify_intra chains). Applied at unit start/restart.
const BridgeTableName = "coolify_bridge"
BridgeTableName is the nftables table name owned by the CLI scaffold.
const DefaultNamespace = "default"
DefaultNamespace is the namespace used when the user does not pass --namespaces. It is also always present even in a multi-namespace setup — coold's config assumes a `default` entry.
Variables ¶
This section is empty.
Functions ¶
func FirewallServiceUnit ¶
func FirewallServiceUnit(iface string, namespaces []string, containerSubnets []*net.IPNet, defaultDeny bool) string
FirewallServiceUnit returns the systemd unit text that installs the idempotent iptables rules required for cross-host container traffic over WG.
containerSubnets is the per-namespace list of subnets on this host (one /<prefix> per namespace). Rules are emitted once per subnet so every namespace is covered by the same host-global COOLIFY-INTRA / COOLIFY-ALLOW chain pair.
Two modes:
defaultDeny == false (mode A, blanket allow): installs FORWARD ACCEPT rules for every subnet. Tears down any default-deny scaffold left over from a prior --default-deny run.
defaultDeny == true (mode B, default deny): removes blanket ACCEPT, installs COOLIFY-INTRA + COOLIFY-ALLOW chains, and adds FORWARD jumps so any traffic with a container subnet as source OR destination traverses the deny chain. Conntrack ESTABLISHED/RELATED is accepted early so reply traffic for already-allowed flows bypasses the chain.
Note: default-deny only enforces CROSS-HOST container traffic. Same- namespace intra-host traffic stays at L2 and bypasses iptables; cross- namespace intra-host traffic is blocked at L2 anyway because each namespace has its own podman bridge.
Both modes preserve the POSTROUTING RETURN rule that prevents podman's MASQUERADE from rewriting container egress to wg0's IP.
func InstallFirewallCommand ¶
func InstallFirewallCommand(iface string, namespaces []string, containerSubnets []*net.IPNet, defaultDeny bool) string
InstallFirewallCommand returns a shell command that atomically writes the service unit, reloads systemd, and enables/starts (or restarts) it.
func MachineIP ¶
MachineIP returns the host address within a per-host subnet — the first usable IP (network address + 1). For example, 10.210.5.0/24 → 10.210.5.1.
Used for the Podman bridge gateway. WireGuard does NOT use this — wg0 gets a separate /32 from the management pool (see AllocateMgmtIPs).
func PodmanNetworkFor ¶
PodmanNetworkFor returns the podman bridge name backing namespace ns on every host. Derived as `coolify-<ns>-mesh` so the namespace is visible directly in `podman network ls`.
func RenderConfig ¶
func RenderConfig(mgmtIP net.IP, listenPort int, peers []PeerConfig) string
RenderConfig returns the content of wg0.conf for one host.
The host's own Address is the management IP /32 (e.g. 100.64.0.0/32). It lives in a separate pool from the container subnets, so the Podman bridges can own their per-host /24s without conflict.
The literal string __PRIVKEY__ is used as a placeholder; callers must substitute the actual key before (or during) writing to disk.
func ValidateIntent ¶
func ValidateIntent(d *DesiredMesh) error
ValidateIntent enforces pre-plan invariants the filter itself can't express.
func WriteConfigCommand ¶
WriteConfigCommand returns the shell command that atomically writes /etc/wireguard/<iface>.conf on the remote host.
The private key is read from /etc/wireguard/privatekey on the remote so it never traverses SSH. The config is written to a .tmp file first and then moved into place so a killed session cannot leave a torn config.
Types ¶
type ActionResult ¶
type ActionResult struct {
Action PlannedAction
Err error
}
ActionResult pairs a PlannedAction with its execution outcome.
func ApplyMesh ¶
func ApplyMesh( ctx context.Context, runner ssh.Runner, user string, port int, desired *DesiredMesh, current MeshState, concurrency int, ) ([]ActionResult, error)
ApplyMesh executes the mesh convergence in two phases:
- Phase 1 (per-server, parallel): install WG + Podman, generate keypair, enable podman socket + IP forwarding.
- Re-probe to collect fresh public keys.
- Phase 2 (per-server, parallel): write WG config, enable/reload service, create per-namespace Podman networks, install firewall service.
- Phase 3 (per-server, parallel, optional): download + enable corrosion/coold.
type ActionType ¶
type ActionType string
ActionType identifies the kind of change required.
const ( ActionInstallWG ActionType = "install-wg" ActionGenKeyPair ActionType = "gen-keypair" ActionAllocateMgmtIP ActionType = "allocate-mgmt-ip" ActionAllocateContainerSubnet ActionType = "allocate-container-subnet" ActionWriteConfig ActionType = "write-config" ActionEnableService ActionType = "enable-service" ActionReloadService ActionType = "reload-service" ActionAddPeer ActionType = "add-peer" ActionRemovePeer ActionType = "remove-peer" ActionInstallPodman ActionType = "install-podman" ActionEnablePodmanSocket ActionType = "enable-podman-socket" ActionEnableIPForward ActionType = "enable-ip-forward" ActionCreatePodmanNet ActionType = "create-podman-network" ActionRecreatePodmanNet ActionType = "recreate-podman-network" ActionInstallFirewall ActionType = "install-firewall" ActionInstallCorrosion ActionType = "install-corrosion" ActionInstallCoold ActionType = "install-coold" ActionWriteCorrosionConfig ActionType = "write-corrosion-config" ActionWriteCorrosionSchema ActionType = "write-corrosion-schema" ActionInstallCorrosionService ActionType = "install-corrosion-service" ActionInstallCooldService ActionType = "install-coold-service" ActionInstallScheduler ActionType = "install-scheduler" ActionGenerateJWTKeypair ActionType = "generate-jwt-keypair" ActionInstallSchedulerService ActionType = "install-scheduler-service" ActionWriteHostJWT ActionType = "write-host-jwt" ActionUpdateCooldSchedulerEnv ActionType = "update-coold-scheduler-env" ActionInstallBuilder ActionType = "install-builder" )
type DesiredMesh ¶
type DesiredMesh struct {
// Hosts lists the SSH addresses of all servers (also used as WG endpoints).
Hosts []string
// Interface is the WireGuard interface name (default "wg0").
Interface string
// MgmtPool is the address pool from which per-host /32 management IPs
// are carved and assigned to wg0 (default 100.64.0.0/16 — RFC 6598 CGNAT).
MgmtPool *net.IPNet
// ContainerPool is the address pool from which per-(namespace, host)
// container subnets are carved (default 10.210.0.0/16). One pool is
// shared across all namespaces so subnets cannot overlap.
ContainerPool *net.IPNet
// ContainerPrefix is the prefix length of each per-host, per-namespace
// container subnet (default 24, giving each host 254 usable container IPs
// per namespace).
ContainerPrefix int
// ListenPort is the WireGuard UDP listen port (default 51820).
ListenPort int
// InstallPodman, when true, installs Podman, enables its socket, creates
// the per-namespace bridge networks, installs firewall rules, and enables
// IP forwarding on each server.
InstallPodman bool
// Namespaces lists every namespace the mesh should carry. Ordered —
// deterministic iteration produces stable subnet assignments. At least
// one entry (typically "default") is always expected.
Namespaces []string
// DefaultDenyContainers, when true (and InstallPodman is true), installs
// default-deny iptables rules for ALL container traffic on the host's
// container subnets (intra-host AND cross-host via wg0). The v5 control
// plane manages the explicit allow-list in the COOLIFY-ALLOW chain.
DefaultDenyContainers bool
// InstallCoold, when true, downloads corrosion + coold from GitHub releases
// to each host, writes their configs/unit files, and enables both services.
// Requires InstallPodman (coold depends on podman.socket).
InstallCoold bool
// CooldVersion is the release tag to download (e.g. "nightly", "v1.2.3").
CooldVersion string
// CorrosionVersion is the release tag to download for corrosion.
CorrosionVersion string
// CorrosionGossipPort is the SWIM gossip UDP port (default 8787).
CorrosionGossipPort int
// CorrosionAPIPort is the corrosion HTTP API port bound to 127.0.0.1 (default 8080).
CorrosionAPIPort int
// CentralHost is the SSH address of the central VM that runs scheduler.
// Empty string disables phases 4+5 (scheduler setup).
// Must be an element of Hosts.
CentralHost string
// SchedulerVersion is the release tag for scheduler (e.g. "nightly").
SchedulerVersion string
// EnableBuilder, when true and BuilderHosts is empty, installs buildah/
// git and the builder binary on every host in Hosts and advertises
// "builder" in each host's JWT caps claim. When BuilderHosts is non-
// empty it wins and EnableBuilder is ignored. Requires a non-empty
// CentralHost (scheduler issues the JWT) and InstallPodman (buildah needs
// podman's containers-storage).
EnableBuilder bool
// BuilderHosts is the explicit list of hosts that should carry the
// builder capability. Empty slice means "fall back to EnableBuilder".
// Hosts not present in this set get `caps:["coold"]` only and the
// builder binary is not installed on them.
BuilderHosts []string
// BuilderCapacity caps concurrent builds per host. 0 falls back to 2 (the
// coold builder adapter's own default).
BuilderCapacity int
// BuilderCPUQuota is the systemd CPUQuota applied to each build subprocess
// (e.g. "200%" for two full cores). Empty string falls back to coold's
// own default ("200%").
BuilderCPUQuota string
// BuilderMemoryMax is the systemd MemoryMax applied to each build
// subprocess (e.g. "2G"). Empty string falls back to coold's own default
// ("2G").
BuilderMemoryMax string
// BuilderTimeoutSecs is the hard per-build wall-clock timeout in seconds.
// 0 falls back to coold's own default (1800).
BuilderTimeoutSecs int
// Intent selects the action filter applied after BuildPlan computes the
// raw action list. IntentBootstrap (default, zero value) emits every
// applicable action (today's behavior). IntentExtend limits destructive
// and version-bump actions to NewHosts only; existing hosts get just the
// peer-refresh actions required to route traffic to the new peer.
// IntentUpgrade emits only binary-fetch + service-restart actions
// cluster-wide.
Intent Intent
// NewHosts is the subset of Hosts that are brand-new to the mesh on this
// run. Only meaningful when Intent == IntentExtend. Empty = treat every
// host as existing (no-op safe mode).
NewHosts []string
// AllowReplace unlocks destructive-replace actions on existing hosts in
// extend mode (e.g. ActionRecreatePodmanNet). Never unlocks the wipe-DB
// branch of ActionWriteCorrosionSchema.
AllowReplace bool
// AllowNightly lets the upgrade intent accept version tag "nightly".
// Upgrade mode otherwise rejects nightly because it forces a re-install
// on every run instead of only when the pinned version changes.
AllowNightly bool
}
DesiredMesh describes the target WireGuard + Podman configuration.
func (*DesiredMesh) BuilderHostSet ¶
func (d *DesiredMesh) BuilderHostSet() map[string]bool
BuilderHostSet returns the set of hosts that should carry the builder capability given EnableBuilder + BuilderHosts. Hosts in the result are a subset of Hosts.
func (*DesiredMesh) HasBuilderCap ¶
func (d *DesiredMesh) HasBuilderCap(host string) bool
HasBuilderCap reports whether host should advertise the builder capability.
func (*DesiredMesh) SortedNamespaces ¶
func (d *DesiredMesh) SortedNamespaces() []string
SortedNamespaces returns the desired namespaces in deterministic order.
type Intent ¶
type Intent string
Intent selects the action filter applied by BuildPlan to match the caller's operation (first-time bootstrap vs. adding servers vs. bumping agent versions). See DesiredMesh.Intent.
const ( // IntentBootstrap allows every action. Matches pre-subcommand-split // behavior and is the default for DesiredMesh (zero value). IntentBootstrap Intent = "" // IntentExtend runs the full install on hosts in NewHosts and limits // existing hosts to peer-refresh actions (WG config rewrite + service // reload + corrosion config rewrite + firewall unit reinstall on drift). IntentExtend Intent = "extend" // IntentUpgrade only emits binary-fetch actions + the service-restart // actions that follow them. IntentUpgrade Intent = "upgrade" )
type MeshState ¶
type MeshState struct {
// Servers maps host → *ServerState.
Servers map[string]*ServerState
}
MeshState is the reconstructed state across all servers in the mesh.
func Reconstruct ¶
func Reconstruct( ctx context.Context, runner ssh.Runner, hosts []string, user string, port int, iface string, namespaces []string, concurrency int, ) (MeshState, error)
Reconstruct runs Probe on every host in parallel and assembles a MeshState.
func (*MeshState) AssignedContainerSubnets ¶
AssignedContainerSubnets returns the per-(namespace, host) subnets that are already assigned on remote podman networks. The result is nested: `out[namespace][host] = subnet`.
type NamespaceServerState ¶
type NamespaceServerState struct {
// Namespace is the logical namespace name (e.g. "default", "alpha").
Namespace string
// NetworkExists is true when the per-namespace podman bridge
// (coolify-<ns>-mesh) already exists on this host.
NetworkExists bool
// ContainerSubnet is the /<prefix> owned by the per-namespace bridge
// (read from `podman network inspect`). nil when not yet created.
ContainerSubnet *net.IPNet
// DNSEnabled is true when the per-namespace network has `dns_enabled=true`
// (netavark auto-starts aardvark-dns on the bridge gateway:53). coold owns
// that socket, so drift triggers ActionRecreatePodmanNet.
DNSEnabled bool
// Label is the `io.coolify.namespace` label on the network. Used only as
// an assertion that the network was created by us — label mismatch is
// treated like "the network exists but is not ours" and triggers recreate.
Label string
}
NamespaceServerState captures per-namespace podman state on one host. A ServerState carries one entry per namespace in the desired set.
type Peer ¶
type Peer struct {
PublicKey string
Endpoint string // "ip:port" or empty
AllowedIPs []string
LatestHandshake int64 // Unix timestamp; 0 means no handshake yet
PersistentKeepalive int // seconds; 0 means disabled
}
Peer represents a single WireGuard peer as seen in the config or from `wg show <iface> dump`.
type PeerConfig ¶
type PeerConfig struct {
// Endpoint is the SSH/public IP of the peer (used as WG endpoint).
Endpoint string
// PublicKey is the peer's WireGuard public key.
PublicKey string
// MgmtIP is the peer's /32 wg0 management IP.
MgmtIP net.IP
// ContainerSubnets is the peer's per-namespace container bridge subnets,
// sorted by namespace name for stable output. All of them — along with
// MgmtIP/32 — are listed in AllowedIPs so every namespace's cross-host
// traffic can route via the tunnel.
ContainerSubnets []*net.IPNet
}
PeerConfig holds the information needed to write a Peer block.
type Plan ¶
type Plan struct {
Actions []PlannedAction
// MgmtAssignments maps host → planned WG management /32 IP.
MgmtAssignments map[string]net.IP
// SubnetAssignments maps namespace → host → planned container subnet.
SubnetAssignments map[string]map[string]*net.IPNet
// Warnings contains non-fatal conflict messages from the IP allocator.
Warnings []Warning
// Skipped lists actions that were filtered out by the Intent gate
// (e.g. destructive-replace on an existing host in extend mode). Exposed
// so the plan preview can show operators what would have fired and why.
Skipped []SkippedAction
}
Plan is the list of actions needed to converge the mesh to the desired state.
type PlannedAction ¶
type PlannedAction struct {
Host string
Namespace string // empty for host-global actions
Type ActionType
Detail string
}
PlannedAction is one step that apply must execute on a host.
type ServerState ¶
type ServerState struct {
// Host is the SSH address used to reach this server.
// It also serves as the WireGuard Endpoint value for peer configs.
Host string
// Installed is true when the wireguard package is present.
Installed bool
// KeysExist is true when /etc/wireguard/privatekey exists.
KeysExist bool
// PublicKey is the content of /etc/wireguard/publickey (trimmed).
// Empty when KeysExist is false.
PublicKey string
// WireGuardMgmtIP is the /32 management IP assigned to wg0 (parsed from
// the [Interface] Address line). Lives outside the container pool so the
// Podman bridge can own the full per-host /24 without conflict.
// nil when not yet assigned.
WireGuardMgmtIP net.IP
// ListenPort is the WireGuard listen port from the config.
ListenPort int
// Interface is the WireGuard interface name (e.g., "wg0").
Interface string
// Active is true when `wg show <iface>` returns output (interface up).
Active bool
// Peers lists the peers currently present in the config file.
Peers []Peer
// PodmanInstalled is true when the podman package is present.
PodmanInstalled bool
// PodmanSocketActive is true when podman.socket systemd unit is active.
PodmanSocketActive bool
// Namespaces maps namespace name → per-namespace podman state on this
// host. Populated by Probe for every namespace in the desired set.
Namespaces map[string]*NamespaceServerState
// IPForwardEnabled is true when net.ipv4.ip_forward == 1.
IPForwardEnabled bool
// FirewallActive is true when coolify-mesh-fw.service is active.
FirewallActive bool
// DefaultDenyActive is true when the COOLIFY-INTRA chain exists and
// terminates in DROP (the default-deny scaffold is in place).
DefaultDenyActive bool
// FirewallUnitSha256 is the sha256 of /etc/systemd/system/coolify-mesh-fw.service
// (hex), or empty when absent. Used to detect unit drift when the desired
// set of namespace subnets changes.
FirewallUnitSha256 string
// BridgeTableExists is true when `nft list table bridge coolify_bridge`
// succeeds on this host (nft bridge-family deny scaffold is in place).
BridgeTableExists bool
// NftAvailable is true when `nft --version` exits 0 on this host.
NftAvailable bool
// CorrosionInstalled is true when /usr/local/bin/corrosion exists and is executable.
CorrosionInstalled bool
// CorrosionActive is true when the corrosion systemd service is active.
CorrosionActive bool
// CorrosionConfigHash is the sha256 of /etc/corrosion/config.toml, or empty
// when the file is absent. Used to detect drift when peer list changes.
CorrosionConfigHash string
// CorrosionSchemaExists is true when /etc/corrosion/schemas/coolify.sql exists.
CorrosionSchemaExists bool
// CorrosionSchemaSha256 is the sha256 of /etc/corrosion/schemas/coolify.sql
// (hex), or empty when absent. Used by BuildPlan to detect schema drift so
// a new schema revision triggers re-write + corrosion restart + DB reset.
CorrosionSchemaSha256 string
// CooldInstalled is true when /usr/local/bin/coold exists and is executable.
CooldInstalled bool
// CooldActive is true when the coold systemd service is active.
CooldActive bool
// CorrosionVersion is the content of /usr/local/bin/corrosion.version
// (trimmed), or empty when absent. Matches the version tag passed to
// CorrosionInstallCommand (e.g. "nightly", "v1.2.3").
CorrosionVersion string
// CooldVersion is the content of /usr/local/bin/coold.version (trimmed),
// or empty when absent.
CooldVersion string
// CooldUnitSha256 is the sha256 of /etc/systemd/system/coold.service (hex),
// or empty when absent. Used by BuildPlan to detect generator changes
// (e.g. Requires→Wants) that would otherwise be invisible.
CooldUnitSha256 string
}
ServerState holds the reconstructed WireGuard + Podman state for one server. It is built from live SSH probes and never cached to disk.
func Probe ¶
func Probe(ctx context.Context, runner ssh.Runner, host, user string, port int, iface string, namespaces []string) (*ServerState, error)
Probe SSHes into host and reads its current WireGuard + Podman state. All commands use `|| true` so a missing package or interface never causes a non-zero exit that would abort the probe.
func (*ServerState) FirewallSubnets ¶
func (s *ServerState) FirewallSubnets() []*net.IPNet
FirewallSubnets returns the sorted-by-namespace list of this host's container subnets across all namespaces (one /prefix per namespace). Used by the firewall service unit generator.
type SkippedAction ¶
type SkippedAction struct {
Action PlannedAction
Reason string
}
SkippedAction is a PlannedAction that BuildPlan would have emitted but the Intent filter suppressed. Reason is a short human-readable message.
type VerifyResult ¶
VerifyResult holds the post-apply verification for one server.
type Warning ¶
Warning describes a non-fatal conflict discovered during IP allocation.
func Allocate ¶
func Allocate( pool *net.IPNet, hostPrefix int, existing map[string]*net.IPNet, hosts []string, ) (map[string]*net.IPNet, []Warning, error)
Allocate assigns a per-host subnet (of size hostPrefix) to every host in hosts, carving them from pool.
Rules:
- Duplicate host names in hosts → error (user input bug).
- Existing subnet within pool with correct prefix → kept unchanged (stable).
- Existing subnet outside pool or wrong prefix → warning, reassign.
- Two existing hosts with the same subnet → first (alphabetical) kept, second gets a warning and is reassigned.
- New hosts receive the lowest free subnet in pool.
Returns (assignments, warnings, error).
func AllocateMgmtIPs ¶
func AllocateMgmtIPs( pool *net.IPNet, existing map[string]net.IP, hosts []string, ) (map[string]net.IP, []Warning, error)
AllocateMgmtIPs assigns a /32 management IP to every host in hosts from pool. Wraps Allocate by promoting/demoting between net.IP and *net.IPNet.
func AllocateNamespaced ¶
func AllocateNamespaced( pool *net.IPNet, hostPrefix int, existing map[string]map[string]*net.IPNet, namespaces []string, hosts []string, ) (map[string]map[string]*net.IPNet, []Warning, error)
AllocateNamespaced assigns a per-host /<hostPrefix> subnet for every (namespace, host) pair in `namespaces × hosts`, carving them from a single shared pool. Stable: existing valid assignments are preserved so re-runs reproduce the same subnets. Invalid or duplicate existing assignments produce a warning and get reassigned to the next free block.
Iteration order is deterministic (namespaces then hosts as passed in), which keeps warnings and subnet layout reproducible for tests.
Returns nested map[namespace][host] = *net.IPNet.