Documentation
¶
Overview ¶
Package core holds the endpoint and network logic: the per-container Tailscale lifecycle, its state directories and their garbage collection.
Index ¶
- Constants
- func CheckEndpointOptions(opts map[string]any) error
- func CheckTagScope(stack string, tags []string, strict bool) error
- func CollectGarbage(ctx context.Context, cfg *Config, claims *StateClaims, ...)
- func ContainerName(name string) string
- func DataDir() string
- func ParseMTU(s string) int
- func ParseTags(s string) []string
- func ReadyPath(dataDir, endpointID string) string
- func RemoveDownloadCache(dataDir string)
- func StatusPath(dataDir, endpointID string) string
- func TagScopeRelaxed(v string) bool
- func TagScopeStrict(v string) bool
- func ValidateLoginServer(s string) error
- func WarnUnusedCertificates(dataDir, sharedDir string)
- type Config
- type ContainerInfo
- type Endpoint
- func (e *Endpoint) ClaimStateDir(info *ContainerInfo) error
- func (e *Endpoint) DrainService()
- func (e *Endpoint) GetInfo() (string, string)
- func (e *Endpoint) IsTailscaleStarted() bool
- func (e *Endpoint) Join(sandboxKey string) (*network.JoinResponse, error)
- func (e *Endpoint) Leave()
- func (e *Endpoint) MarkStartRequested()
- func (e *Endpoint) Recover(sandboxKey string) error
- func (e *Endpoint) RunTailscale(ctx context.Context, info *ContainerInfo)
- func (e *Endpoint) SandboxKey() string
- func (e *Endpoint) SetSandboxKey(sandboxKey string)
- func (e *Endpoint) StartRequested() bool
- func (e *Endpoint) StartTailscale(info *ContainerInfo) error
- func (e *Endpoint) StateDir() string
- func (e *Endpoint) Stop()
- type EndpointOptions
- type EndpointStatusFile
- type Network
- type NetworkOptions
- type StateClaims
- type StatusWarning
Constants ¶
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.
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.
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.
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.
const GenericOptionsKey = "com.docker.network.generic"
GenericOptionsKey is the key Docker uses to pass driver options.
const HostEndpointsSetting = "TSLINK_HOST_ENDPOINTS"
HostEndpointsSetting is the plugin setting that selects HostEndpoints: auto, off, or up to netutil.MaxHostEndpoints IPv4 addresses.
const IsolateHostTailnetSetting = "TSLINK_ISOLATE_HOST_TAILNET"
IsolateHostTailnetSetting is the plugin setting that turns the host's tailnet isolation off.
const KeyPrefix = "tslink."
KeyPrefix starts the keys of tslink's options and labels.
const LogLevelSetting = "TSLINK_LOG_LEVEL"
LogLevelSetting is the plugin setting of the lowest level the plugin logs: debug, info, warn or error.
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.
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.
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
CheckEndpointOptions refuses endpoint options under tslink's prefix: a container's settings are its labels.
func CheckTagScope ¶
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
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 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 ¶
StatusPath returns the status file of an endpoint.
func TagScopeRelaxed ¶ added in v0.3.1
TagScopeRelaxed reports whether a TagScopeSetting value relaxes the scope: only "prefix" does.
func TagScopeStrict ¶
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 ¶
ValidateLoginServer checks a login server URL. An empty one selects Tailscale's control server.
func WarnUnusedCertificates ¶ added in v0.3.2
func WarnUnusedCertificates(dataDir, sharedDir string)
WarnUnusedCertificates warns once at startup of certificates and keys in the data directory's certs/ that tslink no longer reads: the shared directory moved away from the data directory, its default. tslink leaves them, private keys included, for the operator to remove or move back.
Types ¶
type Config ¶
type Config struct {
AuthKey string
DataDir string
// 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) IsTailscaleStarted ¶
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 ¶
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 ¶
SandboxKey returns the sandbox key (container netns path) safely.
func (*Endpoint) SetSandboxKey ¶ added in v0.3.0
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 ¶
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.
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 ¶
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 ¶
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 ¶
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.