Help us shape the future of Go! Take the 2026 Go Developer Survey

k3sengine

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package k3sengine runs single-node k3s clusters in containers for the EKS and GKE emulators.

Index

Constants

View Source
const (
	// ImageRepo is the image repository the engine runs.
	ImageRepo = "rancher/k3s"
	// DefaultToken is the static cluster-admin bearer token used when none is configured.
	DefaultToken = "gopherstack-eks-cluster-token" //nolint:gosec // documented default for a local emulator
	// APIPort is the k3s API server port inside the container.
	APIPort = 6443

	// DataDir is the k3s state directory a persistent volume is mounted on.
	DataDir = "/var/lib/rancher/k3s"
	// CACertFile is where the node keeps the serving CA certificate.
	CACertFile = tlsDir + "/server-ca.crt"
)
View Source
const VolumeLabel = "gopherstack.k3s-volume"

VolumeLabel marks the data volumes the engine creates.

Variables

View Source
var (
	// ErrInvalidConfig is returned when the engine host or token is unusable.
	ErrInvalidConfig = errors.New("invalid k3s cluster engine configuration")
	// ErrDefaultTokenExposed is returned when the public default token would be exposed off-host.
	ErrDefaultTokenExposed = errors.New("a cluster token must be set when the cluster host is not loopback")
	// ErrSuperseded is returned by Launch when the caller's record callback declined the new container.
	ErrSuperseded = errors.New("cluster was superseded while starting")
	// ErrNotAdoptable is returned when a leftover container cannot be taken over.
	ErrNotAdoptable = errors.New("container cannot be adopted")
	// ErrNodeExited is returned when the node container stops while the engine waits for its API server.
	ErrNodeExited = errors.New("node container exited")
	// ErrRotateFailed is returned when the node could not drop its certificates.
	ErrRotateFailed = errors.New("certificate rotation failed")
	// ErrStopUnsupported is returned by Stop and Start when the runtime cannot keep a stopped container.
	ErrStopUnsupported = errors.New("container runtime cannot stop and restart a container in place")
)
View Source
var ErrNotReady = errors.New("readyz not ok")

ErrNotReady is returned while the API server has not answered /readyz with 200.

Functions

func HTTPGet

func HTTPGet(ctx context.Context, addr, path, token string, tlsCfg *tls.Config) ([]byte, error)

HTTPGet GETs https://addr/path with an optional bearer token and requires a 200.

func Image

func Image(version, fallbackVersion string) (string, bool)

Image maps a Kubernetes version to its pinned k3s image; exact is false when it fell back to fallbackVersion.

func MinorKey

func MinorKey(version string) (string, bool)

MinorKey returns "1.N" for a "1.N[.x]" version.

func NormalizeAccess

func NormalizeAccess(host, token string) (string, string, error)

NormalizeAccess validates host and token and fills their defaults.

func Probe

func Probe(ctx context.Context, addr, token string, caPEM []byte) error

Probe requires /readyz to answer 200 for the bearer token over TLS verified against the pre-provisioned CA.

func Script

func Script(servicelb bool) string

Script builds the node command; servicelb stays on only when load-balancer ports are published.

func Tag

func Tag(version string) (string, bool)

Tag returns the pinned k3s tag for a Kubernetes version's minor, or false when the minor is unsupported.

func Tags

func Tags() [8]string

Tags are the newest published rancher/k3s tags for Kubernetes 1.29 through 1.36, in minor order.

Types

type CA

type CA struct {
	CertPEM []byte
	KeyPEM  []byte
}

CA is the server CA pre-provisioned into k3s so the readiness probe never has to trust-on-first-use.

func NewCA

func NewCA(commonName string) (*CA, error)

NewCA generates a fresh P-256 CA with the given common name.

type Config

type Config struct {
	Runtime      Runtime
	Ports        *portalloc.Allocator
	Logger       *slog.Logger
	Probe        func(ctx context.Context, addr, token string) ([]byte, error)
	Prefix       string
	Host         string
	Token        string
	StartTimeout time.Duration
}

Config configures an Engine. Prefix names containers and port labels ("eks", "gke").

type Engine

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

Engine starts and stops single-node k3s containers.

func New

func New(cfg Config) (*Engine, error)

New validates cfg and returns an Engine with defaults applied.

func (*Engine) AcquirePort

func (e *Engine) AcquirePort(name string) (int, error)

AcquirePort takes a host port labelled for name.

func (*Engine) Addr

func (e *Engine) Addr(port int) string

Addr is the host:port of an API server published on port.

func (*Engine) Adopt

func (e *Engine) Adopt(oc container.ManagedContainer) (*Instance, error)

Adopt takes over a running node container an earlier gopherstack left behind. The caller owns it afterwards.

func (*Engine) AwaitReady

func (e *Engine) AwaitReady(ctx context.Context, addr string, ca []byte) ([]byte, error)

AwaitReady polls the API server until it answers or the start timeout passes; it returns the serving CA.

func (*Engine) Close

func (e *Engine) Close()

Close closes the runtime when it supports it.

func (*Engine) Exec

func (e *Engine) Exec(ctx context.Context, containerID string, cmd, env []string) (container.ExecResult, error)

Exec runs cmd in a running node; env entries are set on the process, never in argv.

func (*Engine) Host

func (e *Engine) Host() string

Host is the host clients reach the API server on.

func (*Engine) Launch

func (e *Engine) Launch(ctx context.Context, n Node, record func(*Instance) bool) (*Instance, error)

Launch starts the container for n. record runs once the container exists and returns false when the caller no longer wants it, in which case the container is removed and ErrSuperseded returned.

func (*Engine) Log

func (e *Engine) Log(ctx context.Context) *slog.Logger

Log returns the configured logger, or the context's.

func (*Engine) ReleaseAll

func (e *Engine) ReleaseAll(port int, lbHost []int)

ReleaseAll returns an API port and its load-balancer host ports.

func (*Engine) ReleasePort

func (e *Engine) ReleasePort(port int)

ReleasePort returns a port taken by AcquirePort.

func (*Engine) Remove

func (e *Engine) Remove(containerID string, ports ...int)

Remove stops and removes a container, then releases ports.

func (*Engine) RemoveVolume

func (e *Engine) RemoveVolume(ctx context.Context, name string) error

RemoveVolume deletes a data volume; runtimes without volume support have nothing to delete.

func (*Engine) RotateCertificates

func (e *Engine) RotateCertificates(ctx context.Context, containerID, addr string) ([]byte, error)

RotateCertificates replaces the node's cluster CAs with freshly generated ones (k3s certificate rotate-ca) and restarts it, so k3s reissues every certificate under them. It returns the new serving CA.

func (*Engine) Runtime

func (e *Engine) Runtime() Runtime

Runtime is the container runtime the engine starts nodes on.

func (*Engine) ServingCA

func (e *Engine) ServingCA(ctx context.Context, containerID string) ([]byte, error)

ServingCA reads the node's serving CA certificate, which differs from the one generated for a launch when a reused data volume already held a CA. It waits for the node to write it.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context, containerID, addr string, ca []byte) ([]byte, error)

Start restarts a container kept by Stop and waits for its API server on addr; it returns the serving CA.

func (*Engine) Stop

func (e *Engine) Stop(ctx context.Context, containerID string) error

Stop stops the container but keeps it, so its filesystem (the cluster state) and published ports survive.

func (*Engine) Token

func (e *Engine) Token() string

Token is the static cluster-admin bearer token.

func (*Engine) UnusedVolumes

func (e *Engine) UnusedVolumes(ctx context.Context) ([]string, error)

UnusedVolumes lists the engine's data volumes no container references.

type Instance

type Instance struct {
	CA          *CA
	ContainerID string
	LBHost      []int
	Port        int
}

Instance is a started k3s container.

type Node

type Node struct {
	Name      string
	Image     string
	JoinToken string
	// Resource is the owning service's key for the cluster: a restarted gopherstack can adopt the container by it.
	Resource string
	// Volume names a data volume mounted on DataDir, so cluster state outlives the container.
	Volume string
	// NodeName pins the Kubernetes node name; empty keeps the container hostname.
	NodeName string
	Mounts   []string
	LBPorts  []int
}

Node describes one k3s server container.

type Runtime

type Runtime interface {
	CreateAndStart(ctx context.Context, spec container.Spec) (string, error)
	StopAndRemove(ctx context.Context, containerID string) error
}

Runtime is the slice of container.Runtime the engine needs.

type Stoppable

type Stoppable interface {
	StopContainer(ctx context.Context, containerID string) error
	StartContainer(ctx context.Context, containerID string) error
}

Stoppable is implemented by runtimes that can stop a container and start it again with its data and ports.

Jump to

Keyboard shortcuts

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