core

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package core holds the endpoint and network logic: the per-container Tailscale lifecycle, its state directories and their garbage collection.

Index

Constants

View Source
const (
	AuthKeyOption     = "tslink.authkey"
	TagsOption        = "tslink.tags"
	EphemeralOption   = "tslink.ephemeral"   // for keys that do not say so themselves
	LoginServerOption = "tslink.loginserver" // a control server other than Tailscale's
	MTUOption         = "com.docker.network.driver.mtu"
)

The options of a tslink network, as docker network create --opt passes them.

View Source
const (
	HostnameLabel = "tslink.hostname"
	TagsLabel     = "tslink.tags"
	ServiceLabel  = "tslink.service"
	DirectLabel   = "tslink.direct"
	// HealthLabel turns on the readiness endpoint on a loopback port of the
	// container's own, for a Docker healthcheck such as
	// wget -q -O- http://127.0.0.1:<port>/ready.
	HealthLabel = "tslink.health"
	// ServeLabelPrefix starts the labels tslink.serve.<port>.
	ServeLabelPrefix = "tslink.serve."
)

The container labels tslink reads.

View Source
const (
	StatusRetrying = "retrying" // starting failed, will retry
	StatusFailed   = "failed"   // starting failed in a way retrying cannot fix
	StatusRunning  = "running"
)

States of an endpoint's Tailscale, as written to its status file.

View Source
const ClusterCredentialFile = "oauth-client.secret" //nolint:gosec // a file name, not a credential

ClusterCredentialFile holds the cluster's OAuth client secret, in the plugin's data directory. Networks without tslink.authkey register their nodes with it, so stacks need no secret of their own.

View Source
const GenericOptionsKey = "com.docker.network.generic"

GenericOptionsKey is the key Docker uses to pass driver options.

View Source
const HostEndpointsSetting = "TSLINK_HOST_ENDPOINTS"

HostEndpointsSetting is the plugin setting that selects HostEndpoints: auto, off, or up to netutil.MaxHostEndpoints IPv4 addresses.

View Source
const IsolateHostTailnetSetting = "TSLINK_ISOLATE_HOST_TAILNET"

IsolateHostTailnetSetting is the plugin setting that turns the host's tailnet isolation off.

View Source
const KeyPrefix = "tslink."

KeyPrefix starts the keys of tslink's options and labels.

View Source
const LogLevelSetting = "TSLINK_LOG_LEVEL"

LogLevelSetting is the plugin setting of the lowest level the plugin logs: debug, info, warn or error.

View Source
const StackLabel = "com.docker.stack.namespace"

StackLabel is the label docker stack deploy puts on a stack's services, containers and networks. It overrides any value from the compose file.

View Source
const TagScopeSetting = "TSLINK_TAG_SCOPE"

TagScopeSetting selects how strictly a stack using the cluster credential is confined to its tags: "exact" (the default) allows only tag:<stack>, "prefix" also allows tag:<stack>-*, the old behaviour, which lets a stack claim a longer-named stack's base tag.

View Source
const WireGuardPortsSetting = "TSLINK_WIREGUARD_PORTS"

WireGuardPortsSetting is the plugin setting that sets the range of WireGuardPorts.

Variables

This section is empty.

Functions

func CheckEndpointOptions added in v0.3.0

func CheckEndpointOptions(opts map[string]any) error

CheckEndpointOptions refuses endpoint options under tslink's prefix: a container's settings are its labels.

func CheckTagScope

func CheckTagScope(stack string, tags []string, strict bool) error

CheckTagScope reports whether a stack may register nodes with tags using the cluster credential: the cluster client owns every stack's tags, so each stack is confined to tag:<stack>, or with strict false (TSLINK_TAG_SCOPE= prefix) also tag:<stack>-*.

func CollectGarbage

func CollectGarbage(
	ctx context.Context,
	cfg *Config,
	claims *StateClaims,
	stateInUse, socketsInUse map[string]bool,
	minAge time.Duration,
)

CollectGarbage removes what endpoints leave behind when Leave never runs, as when the host loses power: the state of ephemeral nodes no endpoint uses, and sockets and status files of unknown endpoints. It runs after recovery and then periodically. Non-ephemeral state is kept, since a container with the same hostname reuses its identity. Anything modified within minAge is kept too, as it may belong to an endpoint still starting, and so is state claimed in claims. Collection claims the state it removes. In the shared certificate directory, it removes certificates and files of names no task uses any more.

func ContainerName added in v0.3.1

func ContainerName(name string) string

ContainerName returns a container's name as Docker's API gives it, without the leading "/".

func DataDir

func DataDir() string

DataDir returns the plugin's data directory: TS_DATA_DIR, or /data.

func ParseMTU

func ParseMTU(s string) int

ParseMTU returns the MTU an option value sets, or 0 if it is not a valid one.

func ParseTags

func ParseTags(s string) []string

ParseTags splits a comma-separated tag list (e.g. "tag:web, tag:prod").

func ReadyPath

func ReadyPath(dataDir, endpointID string) string

ReadyPath returns the file that records that an endpoint has been ready.

func RemoveDownloadCache

func RemoveDownloadCache(dataDir string)

RemoveDownloadCache removes tailscale-bin, where versions before the bundled binaries cached the Tailscale releases they downloaded. Hosts upgraded from them keep it otherwise. It runs once at startup.

func StatusPath

func StatusPath(dataDir, endpointID string) string

StatusPath returns the status file of an endpoint.

func TagScopeRelaxed added in v0.3.1

func TagScopeRelaxed(v string) bool

TagScopeRelaxed reports whether a TagScopeSetting value relaxes the scope: only "prefix" does.

func TagScopeStrict

func TagScopeStrict(v string) bool

TagScopeStrict parses TagScopeSetting, as TagScopeRelaxed does, and warns of a relaxed scope or a value it does not know. Any value but "prefix", a typo included, keeps the exact match.

func ValidateLoginServer

func ValidateLoginServer(s string) error

ValidateLoginServer checks a login server URL. An empty one selects Tailscale's control server.

Types

type Config

type Config struct {
	AuthKey   string
	DataDir   string
	SharedDir string // Directory shared between hosts, for certificates; empty for none

	// IsolateHostTailnet keeps every container on the host from reaching the
	// tailnet through the host's own tailscaled (see netutil.SetupHostIsolation)
	IsolateHostTailnet bool

	// StrictTagScope confines a cluster-credential stack to tag:<stack>
	// exactly. TSLINK_TAG_SCOPE=prefix turns it off.
	StrictTagScope bool

	// WireGuardPorts are the host ports containers' tailscaled leave the host
	// on, one for each container (see netutil.SetupNAT)
	WireGuardPorts netutil.PortRange

	// HostEndpoints are the addresses of the host tslink nodes advertise, with
	// their external port, so nodes on hosts that share a network go direct
	// over it (see netutil.HostEndpointAddrs)
	HostEndpoints netutil.HostEndpointsConfig

	// LogLevel is the lowest level the plugin logs (see LogLevelSetting)
	LogLevel slog.Level
}

Config holds the plugin configuration.

func LoadConfig

func LoadConfig() *Config

LoadConfig loads configuration from environment variables.

type ContainerInfo

type ContainerInfo struct {
	ID         string                    // Container ID
	StopSignal string                    // Signal docker stop sends; "" for SIGTERM
	Name       string                    // Container name (without leading /)
	Labels     map[string]string         // All container labels
	Hostname   string                    // Parsed tslink.hostname label or container name
	Tags       []string                  // Parsed tslink.tags label (comma-separated)
	Service    string                    // Parsed tslink.service label (e.g., "svc:hello-world")
	Endpoints  []tailscale.ServeEndpoint // Parsed tslink.serve.<port> labels
	Direct     bool                      // tslink.direct; defaults to true without a Service

	Stack        string // Container's com.docker.stack.namespace label
	NetworkStack string // Network's com.docker.stack.namespace label

	DNS []netip.Addr // DNS servers the container was given, as with docker run --dns

	HealthPort int // tslink.health: loopback port of the readiness endpoint; 0 for none
}

ContainerInfo holds information extracted from Docker container inspection.

type Endpoint

type Endpoint struct {

	// Fixed when the endpoint is created: read without the lock
	ID          string
	Network     *Network
	IPAMAddress netip.Addr // Docker's IPAM address for the endpoint, if any
	// contains filtered or unexported fields
}

Endpoint represents a container endpoint with Tailscale connectivity.

func NewEndpoint

func NewEndpoint(
	id string,
	net *Network,
	opts EndpointOptions,
	cfg *Config,
	claims *StateClaims,
) *Endpoint

NewEndpoint creates a new endpoint with the given configuration. It claims state directories in claims.

func (*Endpoint) ClaimStateDir

func (e *Endpoint) ClaimStateDir(info *ContainerInfo) error

ClaimStateDir records the state directory the container's tailscaled uses, so garbage collection leaves it alone. A directory serves one endpoint at a time: two replicas with the same tslink.hostname on a node would otherwise share one node key. An invalid name claims nothing; starting fails on it.

func (*Endpoint) DrainService

func (e *Endpoint) DrainService()

DrainService stops new connections to the endpoint's Tailscale Service backend, if it has one; existing connections continue.

func (*Endpoint) GetInfo

func (e *Endpoint) GetInfo() (string, string)

GetInfo returns TailscaleIP and Hostname safely for status queries.

func (*Endpoint) IsTailscaleStarted

func (e *Endpoint) IsTailscaleStarted() bool

IsTailscaleStarted returns whether Tailscale has been started for this endpoint.

func (*Endpoint) Join

func (e *Endpoint) Join(sandboxKey string) (*network.JoinResponse, error)

Join is called when a container joins the network. It sets up basic networking (veth, IPs, routing, NAT) and stores the sandbox key. Tailscale setup is deferred until container info is available via Docker events. This allows Join() to return quickly while Tailscale is configured asynchronously.

func (*Endpoint) Leave

func (e *Endpoint) Leave()

Leave is called when a container leaves the network. It stops the Tailscale supervisor and cleans up networking resources.

func (*Endpoint) MarkStartRequested

func (e *Endpoint) MarkStartRequested()

MarkStartRequested records that the driver asked to start Tailscale for the endpoint, so recovery leaves it to that start.

func (*Endpoint) Recover

func (e *Endpoint) Recover(sandboxKey string) error

Recover adopts an endpoint whose Join ran in an earlier plugin instance: it records the namespace and the veth Join created, so Leave cleans them up, and reapplies Join's setup of the container's veth, which an older version may not have done in full.

func (*Endpoint) RunTailscale

func (e *Endpoint) RunTailscale(ctx context.Context, info *ContainerInfo)

RunTailscale starts Tailscale for the endpoint, retrying with backoff until it succeeds, fails in a way retrying cannot fix, or the endpoint leaves. A transient failure, such as the control plane being unreachable when the task starts, must not leave the task without its identity for good. Only one run is active per endpoint, however often it is triggered, and none once the endpoint has begun to leave. The run also ends with ctx, cancelled when the plugin stops: the container keeps running, and recovery adopts its node.

func (*Endpoint) SandboxKey

func (e *Endpoint) SandboxKey() string

SandboxKey returns the sandbox key (container netns path) safely.

func (*Endpoint) SetSandboxKey added in v0.3.0

func (e *Endpoint) SetSandboxKey(sandboxKey string)

SetSandboxKey records the container's network namespace path, as Join and Recover do, for a driver whose join is replaced in tests.

func (*Endpoint) StartRequested

func (e *Endpoint) StartRequested() bool

StartRequested reports whether the driver asked to start Tailscale for the endpoint. One that joined and was never asked missed its connect event.

func (*Endpoint) StartTailscale

func (e *Endpoint) StartTailscale(info *ContainerInfo) error

StartTailscale starts the Tailscale daemon with the provided container info. This is called by the event handler when container info becomes available. It uses the correct hostname and state directory for identity reuse.

func (*Endpoint) StateDir

func (e *Endpoint) StateDir() string

StateDir returns the endpoint's state directory safely.

func (*Endpoint) Stop

func (e *Endpoint) Stop()

Stop stops the endpoint and cleans up resources.

type EndpointOptions

type EndpointOptions struct {
	Hostname string
	// IPAMAddress is the address Docker's IPAM assigned to the endpoint, if any
	IPAMAddress netip.Addr
}

EndpointOptions holds options for endpoint creation.

type EndpointStatusFile

type EndpointStatusFile struct {
	Endpoint string          `json:"endpoint"`
	Hostname string          `json:"hostname"`
	Stack    string          `json:"stack,omitempty"`
	State    string          `json:"state"`
	Error    string          `json:"error,omitempty"`
	Attempts int             `json:"attempts"`
	Updated  time.Time       `json:"updated"`
	Warnings []StatusWarning `json:"warnings,omitempty"`
}

EndpointStatusFile is written to <data>/status/<endpoint>.json while the endpoint exists. A task without its identity looks healthy to Swarm, so this is how diagnostics and monitoring on the node find it.

type Network

type Network struct {
	ID      string
	AuthKey string   // Empty if nodes register with the cluster credential
	Tags    []string // If set, overrides the tslink.tags container label
	MTU     int      // veth MTU; 0 for the default

	LoginServer string // control server URL; empty for Tailscale's

	StrictTagScope bool // confine a cluster-credential stack to tag:<stack> exactly
	// contains filtered or unexported fields
}

Network represents a Docker network using Tailscale.

func NewNetwork

func NewNetwork(id string, opts NetworkOptions, cfg *Config) (*Network, error)

NewNetwork builds a network from its options and resolves its credential: its tslink.authkey option, else the cluster credential, else the plugin's TS_AUTHKEY.

func (*Network) Credential

func (n *Network) Credential(dataDir string) (string, error)

Credential returns the key a node registers with. The cluster credential is read on every call, so replacing the file takes effect at the next registration. An OAuth client secret without an ephemeral parameter gets one from the tslink.ephemeral option, so its nodes are what the option says.

func (*Network) Ephemeral

func (n *Network) Ephemeral() bool

Ephemeral reports whether the network's nodes are ephemeral: always with the cluster credential, which registers ephemeral nodes only, else as the tslink.ephemeral option says, else as far as the key says. Unknown counts as not ephemeral, so a persistent node is never logged out by guess.

func (*Network) UsesClusterCredential

func (n *Network) UsesClusterCredential() bool

UsesClusterCredential reports whether the network's nodes register with the cluster credential.

type NetworkOptions

type NetworkOptions struct {
	AuthKey string
	Tags    []string
	MTU     int // 0 if unset or invalid

	LoginServer string // control server URL; empty for Tailscale's
	Ephemeral   string // tslink.ephemeral as given; NewNetwork validates it
}

NetworkOptions holds options for network creation.

func ParseNetworkOptions

func ParseNetworkOptions(opts map[string]any) (NetworkOptions, error)

ParseNetworkOptions parses network creation options. Docker passes --opt values nested under "com.docker.network.generic". An option tslink does not know under its prefix, a value that is not a string or an invalid MTU is an error: a misspelt option would otherwise leave the network with another credential or other tags than meant. Docker's other options pass.

type StateClaims

type StateClaims struct {
	// contains filtered or unexported fields
}

StateClaims records which endpoint uses each state directory. A directory serves one endpoint at a time, and garbage collection leaves claimed ones alone. The driver creates one and passes it to its endpoints and to garbage collection.

func NewStateClaims

func NewStateClaims() *StateClaims

NewStateClaims returns a registry without claims.

type StatusWarning

type StatusWarning struct {
	Key     string    `json:"key"`
	Message string    `json:"message"`
	Since   time.Time `json:"since"`
}

StatusWarning is a condition of a running endpoint that needs attention, as a certificate whose renewal is blocked. Key identifies it, such as "renewal-blocked/<domain>"; Since is when it was first seen.

Jump to

Keyboard shortcuts

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