Files

339 lines
11 KiB
Go

// Package template describes lab templates: their nodes, their L2 links,
// and the hooks that render the variant configuration of every node from a
// seed and check a variant on running nodes.
//
// A template is code in the labd build, never request data. The prepared
// base images and snapshots it names, and its real renderers and checkers,
// belong to the template itself; this package fixes the model and the
// rendering helpers.
package template
import (
"context"
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"math/rand/v2"
"net/netip"
"regexp"
"strings"
)
// Kind is the guest system of a node.
type Kind string
const (
MikroTik Kind = "mikrotik"
Ubuntu Kind = "ubuntu"
)
// Bounds of a template.
const (
MaxNodes = 8
// MaxInterfaces bounds the NICs of a node, management included, so that
// device names eth0..eth7 keep their PCI order in a VM.
MaxInterfaces = 8
MaxLinks = 16
MaxCriteria = 50
// MaxBootstrapBytes bounds each rendered cloud-init document.
MaxBootstrapBytes = 64 << 10
// SeedBytes is the size of a variant seed.
SeedBytes = 32
ubuntuManagementPort = 22
mikroTikManagementPort = 8728
)
var (
idPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,47}$`)
nodeNamePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,14}$`)
criterionPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`)
// sourcePattern is an LXD snapshot reference: instance/snapshot.
sourcePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}/[A-Za-z0-9][A-Za-z0-9._-]{0,62}$`)
profilePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
)
// Node is a node of a template.
type Node struct {
// Name is the name the task statement uses, such as r1.
Name string
Kind Kind
// Profile is the LXD profile with the CPU, memory, and disk limits, such
// as lincodex-lab-small.
Profile string
// Source is the prepared snapshot the node is copied from, as
// instance/snapshot. On the btrfs pool a copy is a subvolume snapshot
// and takes seconds.
Source string
// MemoryBytes is the guest memory of the profile. labd admits a lab only
// when the memory of all its nodes fits the host budget.
MemoryBytes int64
// ManagementPort is the TCP port labd probes for readiness and the
// checker uses; zero selects 22 for ubuntu and 8728 for mikrotik.
ManagementPort uint16
}
// Port returns the management port of the node.
func (n Node) Port() uint16 {
switch {
case n.ManagementPort != 0:
return n.ManagementPort
case n.Kind == MikroTik:
return mikroTikManagementPort
default:
return ubuntuManagementPort
}
}
// Link is an L2 segment between nodes. Every link becomes its own bridge
// without an address on the host, so lab traffic never reaches the host,
// another lab, or the internet.
type Link struct {
Name string
Nodes []string
}
// Interface is a data NIC of a planned node.
type Interface struct {
// Device is the LXD device and the guest interface name, eth1 and up.
Device string
// Link is the name of the template link.
Link string
MAC string
}
// PlannedNode is a node with its management address and data NICs.
type PlannedNode struct {
Name string
Kind Kind
Management netip.Prefix
ManagementHost netip.Addr
ManagementMAC string
Interfaces []Interface
}
// Variant is one lab of a template: the seed and the plan of every node.
type Variant struct {
Seed [SeedBytes]byte
Nodes []PlannedNode
}
// Node returns the planned node with the given name.
func (v Variant) Node(name string) (PlannedNode, bool) {
for _, node := range v.Nodes {
if node.Name == name {
return node, true
}
}
return PlannedNode{}, false
}
// Rand returns a deterministic random stream for one purpose of the variant,
// such as "addresses" or "faults". The same seed and label always give the
// same stream, so the renderer and the checker agree on the variant.
func (v Variant) Rand(label string) *rand.Rand {
mac := hmac.New(sha256.New, v.Seed[:])
_, _ = mac.Write([]byte(label)) // A hash never fails to write.
var key [32]byte
copy(key[:], mac.Sum(nil))
return rand.New(rand.NewChaCha8(key)) //nolint:gosec // Deterministic variant choice, not a secret.
}
// Bootstrap is the first-boot configuration of a node. LXD passes it to the
// guest as cloud-init data; for a MikroTik node UserData holds the RouterOS
// script that the image applies on first boot.
type Bootstrap struct {
UserData string
NetworkConfig string
}
// NodeAccess is how the checker reaches a node: its management address on
// the lab management bridge. It never leaves labd.
type NodeAccess struct {
Name string
Kind Kind
Address netip.AddrPort
}
// Criterion is the result of one checker criterion.
type Criterion struct {
ID string
Passed bool
}
// RenderFunc renders the bootstrap of every node of a variant by node name.
type RenderFunc func(variant Variant) (map[string]Bootstrap, error)
// CheckFunc evaluates the criteria of a variant on running nodes. It reads
// node state only. An error means that nothing was evaluated, never a failed
// criterion.
type CheckFunc func(ctx context.Context, variant Variant, nodes []NodeAccess) ([]Criterion, error)
// Template is a lab template of one version.
type Template struct {
ID string
Version int
Nodes []Node
Links []Link
Render RenderFunc
Check CheckFunc
}
// MemoryBytes returns the memory of all nodes.
func (t Template) MemoryBytes() int64 {
var total int64
for _, node := range t.Nodes {
total += node.MemoryBytes
}
return total
}
// Node returns the node with the given name.
func (t Template) Node(name string) (Node, bool) {
for _, node := range t.Nodes {
if node.Name == name {
return node, true
}
}
return Node{}, false
}
// Validate reports a template that labd cannot provision.
func (t Template) Validate() error {
if !idPattern.MatchString(t.ID) || t.Version < 1 || t.Version > 10000 {
return errors.New("template.Validate - ID or version is outside the contract")
}
if t.Render == nil || t.Check == nil {
return fmt.Errorf("template.Validate - %s needs a renderer and a checker", t.ID)
}
if len(t.Nodes) < 1 || len(t.Nodes) > MaxNodes || len(t.Links) > MaxLinks {
return fmt.Errorf("template.Validate - %s must have 1 to %d nodes and at most %d links", t.ID, MaxNodes, MaxLinks)
}
if err := t.validateGraph(); err != nil {
return fmt.Errorf("template.Validate - %s: %w", t.ID, err)
}
return nil
}
// validateGraph checks the nodes and the links between them.
func (t Template) validateGraph() error {
nics := make(map[string]int, len(t.Nodes))
for _, node := range t.Nodes {
if err := node.validate(); err != nil {
return err
}
if _, duplicate := nics[node.Name]; duplicate {
return fmt.Errorf("Template.validateGraph - duplicate node %s", node.Name)
}
// Every node starts with its management NIC.
nics[node.Name] = 1
}
links := make(map[string]struct{}, len(t.Links))
for _, link := range t.Links {
if _, duplicate := links[link.Name]; duplicate || !nodeNamePattern.MatchString(link.Name) {
return fmt.Errorf("Template.validateGraph - link names must be unique and match %s", nodeNamePattern)
}
links[link.Name] = struct{}{}
if len(link.Nodes) < 1 {
return fmt.Errorf("Template.validateGraph - link %s has no node", link.Name)
}
for _, name := range link.Nodes {
count, known := nics[name]
if !known {
return fmt.Errorf("Template.validateGraph - link %s names unknown node %s", link.Name, name)
}
if count+1 > MaxInterfaces {
return fmt.Errorf("Template.validateGraph - node %s has more than %d interfaces", name, MaxInterfaces)
}
nics[name] = count + 1
}
}
return nil
}
func (n Node) validate() error {
switch {
case !nodeNamePattern.MatchString(n.Name):
return fmt.Errorf("Node.validate - node name %q must match %s", n.Name, nodeNamePattern)
case n.Kind != MikroTik && n.Kind != Ubuntu:
return fmt.Errorf("Node.validate - node %s has unknown kind %q", n.Name, n.Kind)
case !profilePattern.MatchString(n.Profile):
return fmt.Errorf("Node.validate - node %s needs an LXD profile", n.Name)
case !sourcePattern.MatchString(n.Source):
return fmt.Errorf("Node.validate - node %s needs a source snapshot as instance/snapshot", n.Name)
case n.MemoryBytes <= 0:
return fmt.Errorf("Node.validate - node %s needs its guest memory", n.Name)
}
return nil
}
// Plan returns the variant of a lab: management addresses in node order and
// one data NIC per link membership, numbered from eth1 in link order. MAC
// addresses are locally administered: a management MAC encodes the unique
// management address, and a data MAC needs to be unique only inside its
// own lab bridge.
func (t Template) Plan(seed [SeedBytes]byte, addresses []netip.Addr, prefixBits int, host netip.Addr) (Variant, error) {
if len(addresses) != len(t.Nodes) {
return Variant{}, errors.New("template.Plan - one management address per node is required")
}
variant := Variant{Seed: seed, Nodes: make([]PlannedNode, 0, len(t.Nodes))}
for index, node := range t.Nodes {
address := addresses[index]
if !address.Is4() {
return Variant{}, errors.New("template.Plan - management addresses must be IPv4")
}
octets := address.As4()
variant.Nodes = append(variant.Nodes, PlannedNode{
Name: node.Name,
Kind: node.Kind,
Management: netip.PrefixFrom(address, prefixBits),
ManagementHost: host,
ManagementMAC: fmt.Sprintf("02:4c:00:%02x:%02x:%02x", octets[1], octets[2], octets[3]),
})
}
for _, link := range t.Links {
for _, name := range link.Nodes {
for index := range variant.Nodes {
planned := &variant.Nodes[index]
if planned.Name != name {
continue
}
nic := len(planned.Interfaces) + 1
planned.Interfaces = append(planned.Interfaces, Interface{
Device: fmt.Sprintf("eth%d", nic),
Link: link.Name,
MAC: fmt.Sprintf("02:4c:01:%02x:%02x:00", index, nic),
})
}
}
}
return variant, nil
}
// ValidateCriteria reports checker output that cannot be a result.
func ValidateCriteria(criteria []Criterion) error {
if len(criteria) < 1 || len(criteria) > MaxCriteria {
return fmt.Errorf("template.ValidateCriteria - a check must have 1 to %d criteria", MaxCriteria)
}
seen := make(map[string]struct{}, len(criteria))
for _, criterion := range criteria {
if _, duplicate := seen[criterion.ID]; duplicate || !criterionPattern.MatchString(criterion.ID) {
return errors.New("template.ValidateCriteria - criterion IDs must be unique and match the contract")
}
seen[criterion.ID] = struct{}{}
}
return nil
}
// ValidateBootstrap reports a rendered bootstrap that LXD would not take.
func ValidateBootstrap(bootstrap Bootstrap) error {
if len(bootstrap.UserData) > MaxBootstrapBytes || len(bootstrap.NetworkConfig) > MaxBootstrapBytes {
return fmt.Errorf("template.ValidateBootstrap - cloud-init documents must have at most %d bytes", MaxBootstrapBytes)
}
if strings.ContainsRune(bootstrap.UserData, 0) || strings.ContainsRune(bootstrap.NetworkConfig, 0) {
return errors.New("template.ValidateBootstrap - cloud-init documents must not contain NUL")
}
return nil
}