core

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 24 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 (
	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 EphemeralOption = "tslink.ephemeral"

EphemeralOption says whether a network's nodes are ephemeral, for keys that do not say so themselves.

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

GenericOptionsKey is the key Docker uses to pass driver options.

View Source
const HealthLabel = "tslink.health"

HealthLabel is the container label that 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.

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 LoginServerOption = "tslink.loginserver"

LoginServerOption is the network option for a control server other than Tailscale's, such as headscale.

View Source
const MTUOption = "com.docker.network.driver.mtu"

MTUOption is Docker's standard network option for the interface MTU.

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

func TagScopeStrict(v string) bool

TagScopeStrict parses TagScopeSetting. Only "prefix" relaxes the scope; any other value, 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
}

Config holds the plugin configuration.

func LoadConfig

func LoadConfig() (*Config, error)

LoadConfig loads configuration from environment variables.

type ContainerInfo

type ContainerInfo struct {
	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 {
	ID          string
	Network     *Network
	Hostname    string
	Tags        []string                  // ACL tags for tailscale up --advertise-tags
	Service     string                    // Service name (e.g., "svc:hello-world")
	Endpoints   []tailscale.ServeEndpoint // Parsed tslink.serve.<port> labels
	Direct      bool                      // Serve the endpoints on the task's own name too
	TailscaleIP string
	VethName    string
	StateDir    string
	SandboxKey  string // Container's network namespace path, stored during Join
	DataDir     string // Base data directory for state
	SharedDir   string // Directory shared between hosts; empty for none
	IPAMAddress string // Docker's IPAM address for the endpoint; set before Join, then fixed
	// 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, error)

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

func (e *Endpoint) GetSandboxKey() string

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

func (*Endpoint) GetStateDir

func (e *Endpoint) GetStateDir() string

GetStateDir returns the endpoint's state directory safely.

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() error

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 the routes Join installs, which an older version may not have.

func (*Endpoint) RunTailscale

func (e *Endpoint) RunTailscale(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.

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

func (e *Endpoint) Stop() error

Stop stops the endpoint and cleans up resources.

type EndpointOptions

type EndpointOptions struct {
	Hostname string
}

EndpointOptions holds options for endpoint creation.

func ParseEndpointOptions

func ParseEndpointOptions(opts map[string]any) EndpointOptions

ParseEndpointOptions parses endpoint creation options.

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

ParseNetworkOptions parses network creation options. Docker passes --opt values nested under "com.docker.network.generic".

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