331 lines
12 KiB
Go
331 lines
12 KiB
Go
// Package config reads the labd configuration from the environment.
|
|
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Defaults of the labd settings. The management plane values match
|
|
// deploy/labs/lxd-preseed.yaml.
|
|
const (
|
|
DefaultListenAddress = "127.0.0.1:8445"
|
|
DefaultAllowedClients = "127.0.0.0/8,::1/128"
|
|
DefaultLXDSocket = "/var/snap/lxd/common/lxd/unix.socket"
|
|
DefaultLXDProject = "default"
|
|
DefaultStateFile = "/var/lib/lincodex-labd/labs.json"
|
|
DefaultMemoryBudgetMiB = 3072
|
|
DefaultMaxLabs = 0
|
|
DefaultMaxLifetime = 2 * time.Hour
|
|
DefaultProvisionTimeout = 5 * time.Minute
|
|
DefaultProbeInterval = 2 * time.Second
|
|
DefaultProbeTimeout = 2 * time.Second
|
|
DefaultRetryAfter = 30 * time.Second
|
|
DefaultSweepInterval = 15 * time.Second
|
|
DefaultReconcileInterval = 5 * time.Minute
|
|
DefaultDeletedRetention = time.Hour
|
|
DefaultConsoleTokenTTL = time.Minute
|
|
DefaultCheckTimeout = time.Minute
|
|
DefaultShutdownTimeout = 30 * time.Second
|
|
DefaultMaxRequestBytes = 64 << 10
|
|
DefaultManagementNetwork = "lxdbr-labmgmt"
|
|
DefaultManagementSubnet = "10.81.0.0/24"
|
|
DefaultManagementHost = "10.81.0.1"
|
|
DefaultManagementFirst = "10.81.0.16"
|
|
// MinTokenLength is the shortest accepted service token.
|
|
MinTokenLength = 32
|
|
// MaxConsoleTokenTTL is the contract bound of a console token.
|
|
MaxConsoleTokenTTL = 120 * time.Second
|
|
bytesPerMiB = 1 << 20
|
|
)
|
|
|
|
// Config is the validated labd configuration.
|
|
type Config struct {
|
|
ListenAddress string
|
|
TLSCertFile string
|
|
TLSKeyFile string
|
|
// AllowPlaintextHTTP serves HTTP without TLS, for local development only.
|
|
AllowPlaintextHTTP bool
|
|
APIToken string
|
|
// AllowedClients are the networks a request may come from. The token
|
|
// authorizes the caller; the list keeps every other network out even
|
|
// when the listener is reachable.
|
|
AllowedClients []netip.Prefix
|
|
|
|
LXDSocket string
|
|
LXDProject string
|
|
StateFile string
|
|
|
|
MemoryBudgetBytes int64
|
|
MaxLabs int
|
|
MaxLifetime time.Duration
|
|
ProvisionTimeout time.Duration
|
|
ProbeInterval time.Duration
|
|
ProbeTimeout time.Duration
|
|
RetryAfter time.Duration
|
|
SweepInterval time.Duration
|
|
ReconcileInterval time.Duration
|
|
DeletedRetention time.Duration
|
|
ConsoleTokenTTL time.Duration
|
|
CheckTimeout time.Duration
|
|
ShutdownTimeout time.Duration
|
|
MaxRequestBytes int64
|
|
|
|
ManagementNetwork string
|
|
ManagementSubnet netip.Prefix
|
|
ManagementHost netip.Addr
|
|
ManagementFirst netip.Addr
|
|
|
|
LogLevel slog.Level
|
|
}
|
|
|
|
// Load reads the configuration from the process environment.
|
|
func Load() (Config, error) {
|
|
return parse(os.LookupEnv, os.ReadFile)
|
|
}
|
|
|
|
type (
|
|
lookupFunc func(string) (string, bool)
|
|
readFileFunc func(string) ([]byte, error)
|
|
)
|
|
|
|
func parse(lookup lookupFunc, readFile readFileFunc) (Config, error) {
|
|
r := reader{lookup: lookup}
|
|
cfg := Config{
|
|
ListenAddress: r.text("LABD_LISTEN_ADDRESS", DefaultListenAddress),
|
|
TLSCertFile: r.text("LABD_TLS_CERT_FILE", ""),
|
|
TLSKeyFile: r.text("LABD_TLS_KEY_FILE", ""),
|
|
AllowPlaintextHTTP: r.boolean("LABD_DEV_ALLOW_PLAINTEXT_HTTP"),
|
|
AllowedClients: r.prefixes("LABD_ALLOWED_CLIENTS", DefaultAllowedClients),
|
|
LXDSocket: r.text("LABD_LXD_SOCKET", DefaultLXDSocket),
|
|
LXDProject: r.text("LABD_LXD_PROJECT", DefaultLXDProject),
|
|
StateFile: r.text("LABD_STATE_FILE", DefaultStateFile),
|
|
MemoryBudgetBytes: r.int64("LABD_MEMORY_BUDGET_MIB", DefaultMemoryBudgetMiB) * bytesPerMiB,
|
|
MaxLabs: r.integer("LABD_MAX_LABS", DefaultMaxLabs),
|
|
MaxLifetime: r.duration("LABD_MAX_LIFETIME", DefaultMaxLifetime),
|
|
ProvisionTimeout: r.duration("LABD_PROVISION_TIMEOUT", DefaultProvisionTimeout),
|
|
ProbeInterval: r.duration("LABD_PROBE_INTERVAL", DefaultProbeInterval),
|
|
ProbeTimeout: r.duration("LABD_PROBE_TIMEOUT", DefaultProbeTimeout),
|
|
RetryAfter: r.duration("LABD_RETRY_AFTER", DefaultRetryAfter),
|
|
SweepInterval: r.duration("LABD_SWEEP_INTERVAL", DefaultSweepInterval),
|
|
ReconcileInterval: r.duration("LABD_RECONCILE_INTERVAL", DefaultReconcileInterval),
|
|
DeletedRetention: r.duration("LABD_DELETED_RETENTION", DefaultDeletedRetention),
|
|
ConsoleTokenTTL: r.duration("LABD_CONSOLE_TOKEN_TTL", DefaultConsoleTokenTTL),
|
|
CheckTimeout: r.duration("LABD_CHECK_TIMEOUT", DefaultCheckTimeout),
|
|
ShutdownTimeout: r.duration("LABD_SHUTDOWN_TIMEOUT", DefaultShutdownTimeout),
|
|
MaxRequestBytes: r.int64("LABD_MAX_REQUEST_BYTES", DefaultMaxRequestBytes),
|
|
ManagementNetwork: r.text("LABD_MGMT_NETWORK", DefaultManagementNetwork),
|
|
ManagementSubnet: r.prefix("LABD_MGMT_SUBNET", DefaultManagementSubnet),
|
|
ManagementHost: r.address("LABD_MGMT_HOST_ADDRESS", DefaultManagementHost),
|
|
ManagementFirst: r.address("LABD_MGMT_FIRST_ADDRESS", DefaultManagementFirst),
|
|
LogLevel: r.logLevel("LABD_LOG_LEVEL"),
|
|
}
|
|
cfg.APIToken = r.token(readFile)
|
|
// Report parse and validation errors together, so one start names every
|
|
// setting to fix.
|
|
if err := errors.Join(append(r.errs, cfg.validate())...); err != nil {
|
|
return Config{}, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func (c Config) validate() error {
|
|
return errors.Join(c.validateTransport(), c.validateLimits(), c.validatePlacement())
|
|
}
|
|
|
|
func (c Config) validateTransport() error {
|
|
tlsSet := c.TLSCertFile != "" || c.TLSKeyFile != ""
|
|
switch {
|
|
case tlsSet && (c.TLSCertFile == "" || c.TLSKeyFile == ""):
|
|
return errors.New("config.validate - LABD_TLS_CERT_FILE and LABD_TLS_KEY_FILE must be set together")
|
|
case tlsSet && c.AllowPlaintextHTTP:
|
|
return errors.New("config.validate - LABD_DEV_ALLOW_PLAINTEXT_HTTP conflicts with TLS settings")
|
|
case !tlsSet && !c.AllowPlaintextHTTP:
|
|
return errors.New("config.validate - TLS is required: set LABD_TLS_CERT_FILE and LABD_TLS_KEY_FILE")
|
|
case len(c.AllowedClients) == 0:
|
|
return errors.New("config.validate - LABD_ALLOWED_CLIENTS must name at least one network")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c Config) validateLimits() error {
|
|
var errs []error
|
|
positive := map[string]int64{
|
|
"LABD_MEMORY_BUDGET_MIB": c.MemoryBudgetBytes,
|
|
"LABD_MAX_LIFETIME": int64(c.MaxLifetime),
|
|
"LABD_PROVISION_TIMEOUT": int64(c.ProvisionTimeout),
|
|
"LABD_PROBE_INTERVAL": int64(c.ProbeInterval),
|
|
"LABD_PROBE_TIMEOUT": int64(c.ProbeTimeout),
|
|
"LABD_RETRY_AFTER": int64(c.RetryAfter),
|
|
"LABD_SWEEP_INTERVAL": int64(c.SweepInterval),
|
|
"LABD_RECONCILE_INTERVAL": int64(c.ReconcileInterval),
|
|
"LABD_DELETED_RETENTION": int64(c.DeletedRetention),
|
|
"LABD_CONSOLE_TOKEN_TTL": int64(c.ConsoleTokenTTL),
|
|
"LABD_CHECK_TIMEOUT": int64(c.CheckTimeout),
|
|
"LABD_SHUTDOWN_TIMEOUT": int64(c.ShutdownTimeout),
|
|
"LABD_MAX_REQUEST_BYTES": c.MaxRequestBytes,
|
|
}
|
|
for name, value := range positive {
|
|
if value <= 0 {
|
|
errs = append(errs, fmt.Errorf("config.validate - %s must be positive", name))
|
|
}
|
|
}
|
|
if c.MaxLabs < 0 {
|
|
errs = append(errs, errors.New("config.validate - LABD_MAX_LABS must not be negative"))
|
|
}
|
|
if c.ConsoleTokenTTL > MaxConsoleTokenTTL {
|
|
errs = append(errs, errors.New("config.validate - LABD_CONSOLE_TOKEN_TTL must not exceed 120s"))
|
|
}
|
|
// The contract bounds a lifetime by 4 hours.
|
|
if c.MaxLifetime > 4*time.Hour {
|
|
errs = append(errs, errors.New("config.validate - LABD_MAX_LIFETIME must not exceed 4h"))
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
func (c Config) validatePlacement() error {
|
|
var errs []error
|
|
for name, path := range map[string]string{"LABD_LXD_SOCKET": c.LXDSocket, "LABD_STATE_FILE": c.StateFile} {
|
|
if !filepath.IsAbs(path) {
|
|
errs = append(errs, fmt.Errorf("config.validate - %s must be an absolute path", name))
|
|
}
|
|
}
|
|
if c.ManagementNetwork == "" || c.LXDProject == "" {
|
|
errs = append(errs, errors.New("config.validate - LABD_MGMT_NETWORK and LABD_LXD_PROJECT must not be empty"))
|
|
}
|
|
if !c.ManagementSubnet.IsValid() || !c.ManagementSubnet.Addr().Is4() ||
|
|
!c.ManagementSubnet.Contains(c.ManagementHost) || !c.ManagementSubnet.Contains(c.ManagementFirst) {
|
|
errs = append(errs, errors.New("config.validate - LABD_MGMT_HOST_ADDRESS and LABD_MGMT_FIRST_ADDRESS must be in the IPv4 LABD_MGMT_SUBNET"))
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|
|
|
|
// reader collects parse errors so that one start reports every bad value.
|
|
type reader struct {
|
|
lookup lookupFunc
|
|
errs []error
|
|
}
|
|
|
|
func (r *reader) text(name, fallback string) string {
|
|
value, ok := r.lookup(name)
|
|
if !ok || value == "" {
|
|
return fallback
|
|
}
|
|
return value
|
|
}
|
|
|
|
func (r *reader) boolean(name string) bool {
|
|
value, ok := r.lookup(name)
|
|
if !ok || value == "" {
|
|
return false
|
|
}
|
|
parsed, err := strconv.ParseBool(value)
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.boolean - %s is not a boolean", name))
|
|
}
|
|
return parsed
|
|
}
|
|
|
|
func (r *reader) integer(name string, fallback int) int {
|
|
return int(r.int64(name, int64(fallback)))
|
|
}
|
|
|
|
func (r *reader) int64(name string, fallback int64) int64 {
|
|
value, ok := r.lookup(name)
|
|
if !ok || value == "" {
|
|
return fallback
|
|
}
|
|
parsed, err := strconv.ParseInt(value, 10, 64)
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.int64 - %s is not an integer", name))
|
|
}
|
|
return parsed
|
|
}
|
|
|
|
func (r *reader) duration(name string, fallback time.Duration) time.Duration {
|
|
value, ok := r.lookup(name)
|
|
if !ok || value == "" {
|
|
return fallback
|
|
}
|
|
parsed, err := time.ParseDuration(value)
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.duration - %s is not a duration", name))
|
|
}
|
|
return parsed
|
|
}
|
|
|
|
func (r *reader) prefix(name, fallback string) netip.Prefix {
|
|
parsed, err := netip.ParsePrefix(r.text(name, fallback))
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.prefix - %s is not a network", name))
|
|
}
|
|
return parsed.Masked()
|
|
}
|
|
|
|
func (r *reader) prefixes(name, fallback string) []netip.Prefix {
|
|
var result []netip.Prefix
|
|
for _, part := range strings.Split(r.text(name, fallback), ",") {
|
|
parsed, err := netip.ParsePrefix(strings.TrimSpace(part))
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.prefixes - %s holds a value that is not a network", name))
|
|
continue
|
|
}
|
|
result = append(result, parsed.Masked())
|
|
}
|
|
return result
|
|
}
|
|
|
|
func (r *reader) address(name, fallback string) netip.Addr {
|
|
parsed, err := netip.ParseAddr(r.text(name, fallback))
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.address - %s is not an address", name))
|
|
}
|
|
return parsed
|
|
}
|
|
|
|
func (r *reader) logLevel(name string) slog.Level {
|
|
value, ok := r.lookup(name)
|
|
if !ok || value == "" {
|
|
return slog.LevelInfo
|
|
}
|
|
var level slog.Level
|
|
if err := level.UnmarshalText([]byte(value)); err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.logLevel - %s is not a log level", name))
|
|
}
|
|
return level
|
|
}
|
|
|
|
// token reads the service token from LABD_API_TOKEN_FILE or, failing that,
|
|
// LABD_API_TOKEN. The value never appears in an error.
|
|
func (r *reader) token(readFile readFileFunc) string {
|
|
file := r.text("LABD_API_TOKEN_FILE", "")
|
|
direct := r.text("LABD_API_TOKEN", "")
|
|
var token string
|
|
switch {
|
|
case file != "" && direct != "":
|
|
r.errs = append(r.errs, errors.New("config.reader.token - set LABD_API_TOKEN_FILE or LABD_API_TOKEN, not both"))
|
|
return ""
|
|
case file != "":
|
|
content, err := readFile(file)
|
|
if err != nil {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.token - read LABD_API_TOKEN_FILE: %w", err))
|
|
return ""
|
|
}
|
|
token = strings.TrimSpace(string(content))
|
|
default:
|
|
token = direct
|
|
}
|
|
if len(token) < MinTokenLength {
|
|
r.errs = append(r.errs, fmt.Errorf("config.reader.token - the service token must have at least %d characters", MinTokenLength))
|
|
return ""
|
|
}
|
|
return token
|
|
}
|