281 lines
9.0 KiB
Go
281 lines
9.0 KiB
Go
package pool
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/netip"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"lincodex/labd/internal/lab"
|
|
"lincodex/labd/internal/lxd"
|
|
"lincodex/labd/internal/template"
|
|
)
|
|
|
|
// startWorkerLocked runs the provisioning and deletion of one lab in its own
|
|
// goroutine. At most one worker exists per lab, so the provisioning and the
|
|
// deletion of a lab never race.
|
|
func (m *Manager) startWorkerLocked(id uuid.UUID) {
|
|
if _, running := m.workers[id]; running || !m.started || m.base.Err() != nil {
|
|
return
|
|
}
|
|
provisionCtx, cancel := context.WithCancel(m.base)
|
|
m.workers[id] = cancel
|
|
m.wg.Add(1)
|
|
go m.run(provisionCtx, id)
|
|
}
|
|
|
|
func (m *Manager) run(provisionCtx context.Context, id uuid.UUID) {
|
|
defer m.wg.Done()
|
|
tornDown := false
|
|
defer func() {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if cancel, ok := m.workers[id]; ok {
|
|
cancel()
|
|
delete(m.workers, id)
|
|
}
|
|
// A deletion requested while this worker finished provisioning
|
|
// starts at once instead of at the next sweep.
|
|
if record, ok := m.labs[id]; ok && !tornDown && record.NeedsTeardown() {
|
|
m.startWorkerLocked(id)
|
|
}
|
|
}()
|
|
if record, ok := m.snapshot(id); ok && record.State == lab.Provisioning {
|
|
m.provision(provisionCtx, record)
|
|
}
|
|
if m.base.Err() != nil {
|
|
return
|
|
}
|
|
if record, ok := m.snapshot(id); ok && record.NeedsTeardown() {
|
|
tornDown = true
|
|
m.teardown(m.base, record)
|
|
}
|
|
}
|
|
|
|
func (m *Manager) snapshot(id uuid.UUID) (lab.Lab, bool) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
record, ok := m.labs[id]
|
|
if !ok {
|
|
return lab.Lab{}, false
|
|
}
|
|
return record.Clone(), true
|
|
}
|
|
|
|
// provision builds the lab and records the outcome. A cancelled
|
|
// provisioning (deletion, expiry) records nothing: the lab is already
|
|
// deleting. A stopped process records nothing either: the next start fails
|
|
// the lab as interrupted.
|
|
func (m *Manager) provision(provisionCtx context.Context, record lab.Lab) {
|
|
ctx, cancel := context.WithTimeout(provisionCtx, m.cfg.ProvisionTimeout)
|
|
defer cancel()
|
|
started := time.Now()
|
|
err := m.build(ctx, record)
|
|
switch {
|
|
case err == nil:
|
|
m.finishProvisioning(record.ID, "", nil)
|
|
m.logger.Info("lab ready", slog.String("lab_id", record.ID.String()),
|
|
slog.Int64("provision_ms", time.Since(started).Milliseconds()))
|
|
case provisionCtx.Err() != nil:
|
|
return
|
|
case errors.Is(err, context.DeadlineExceeded):
|
|
m.finishProvisioning(record.ID, lab.FailureTimedOut, err)
|
|
default:
|
|
m.finishProvisioning(record.ID, lab.FailureProvisioning, err)
|
|
}
|
|
}
|
|
|
|
func (m *Manager) finishProvisioning(id uuid.UUID, reason lab.FailureReason, cause error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
record, ok := m.labs[id]
|
|
if !ok || record.State != lab.Provisioning {
|
|
return
|
|
}
|
|
if reason == "" {
|
|
record.State = lab.Ready
|
|
record.ReadyAt = m.now().UTC()
|
|
} else {
|
|
record.State = lab.Failed
|
|
record.FailureReason = reason
|
|
// The LXD text may name host paths; it stays in the labd log.
|
|
m.logger.Warn("lab provisioning failed", slog.String("lab_id", id.String()),
|
|
slog.String("reason", string(reason)), slog.String("error", cause.Error()))
|
|
}
|
|
if err := m.persistLocked(); err != nil {
|
|
m.logger.Error("lab state not saved", slog.String("lab_id", id.String()), slog.String("error", err.Error()))
|
|
}
|
|
}
|
|
|
|
// build creates the bridges and instances of a lab, starts the instances,
|
|
// and waits until every node answers on its management port.
|
|
func (m *Manager) build(ctx context.Context, record lab.Lab) error {
|
|
chosen, ok := m.templates.Lookup(record.TemplateID, record.TemplateVersion)
|
|
if !ok {
|
|
return errors.New("Manager.build - the template of the lab is not in this build")
|
|
}
|
|
variant, err := m.plan(record, chosen)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
bootstraps, err := chosen.Render(variant)
|
|
if err != nil {
|
|
return fmt.Errorf("Manager.build - render: %w", err)
|
|
}
|
|
for index, link := range chosen.Links {
|
|
spec := lxd.NetworkSpec{
|
|
Name: record.Bridges[index],
|
|
Description: "Lincodex lab link " + link.Name,
|
|
// No address on the host side: the bridge is L2 only, so lab
|
|
// traffic is neither routed nor answered by the host.
|
|
Config: map[string]string{"ipv4.address": "none", "ipv6.address": "none", lab.ConfigLab: record.ID.String()},
|
|
}
|
|
if err := m.lxd.CreateNetwork(ctx, spec); err != nil {
|
|
return fmt.Errorf("Manager.build - create bridge: %w", err)
|
|
}
|
|
}
|
|
for index, node := range chosen.Nodes {
|
|
bootstrap := bootstraps[node.Name]
|
|
if err := template.ValidateBootstrap(bootstrap); err != nil {
|
|
return err
|
|
}
|
|
spec := m.instanceSpec(record, chosen, node, variant.Nodes[index], bootstrap)
|
|
if err := m.lxd.CreateInstance(ctx, spec); err != nil {
|
|
return fmt.Errorf("Manager.build - create instance: %w", err)
|
|
}
|
|
}
|
|
for _, node := range record.Nodes {
|
|
if err := m.lxd.StartInstance(ctx, node.Instance); err != nil {
|
|
return fmt.Errorf("Manager.build - start instance: %w", err)
|
|
}
|
|
}
|
|
return m.waitReachable(ctx, record)
|
|
}
|
|
|
|
func (m *Manager) instanceSpec(record lab.Lab, chosen template.Template, node template.Node, planned template.PlannedNode, bootstrap template.Bootstrap) lxd.InstanceSpec {
|
|
config := map[string]string{
|
|
lab.ConfigLab: record.ID.String(),
|
|
lab.ConfigNode: node.Name,
|
|
lab.ConfigExpiresAt: record.ExpiresAt.Format(time.RFC3339),
|
|
// The guest gets no LXD guest API.
|
|
"security.devlxd": "false",
|
|
}
|
|
devices := map[string]map[string]string{
|
|
// The management NIC overrides the profile NIC: a fixed MAC that
|
|
// cloud-init matches, no MAC spoofing, and no traffic to other
|
|
// isolated ports of the bridge, that is, to other nodes.
|
|
"eth0": {
|
|
"type": "nic", "network": m.cfg.ManagementNetwork, "hwaddr": planned.ManagementMAC,
|
|
"security.mac_filtering": "true", "security.port_isolation": "true",
|
|
},
|
|
}
|
|
bridges := make(map[string]string, len(chosen.Links))
|
|
for index, link := range chosen.Links {
|
|
bridges[link.Name] = record.Bridges[index]
|
|
}
|
|
for _, nic := range planned.Interfaces {
|
|
devices[nic.Device] = map[string]string{"type": "nic", "network": bridges[nic.Link], "hwaddr": nic.MAC}
|
|
}
|
|
if bootstrap.UserData != "" || bootstrap.NetworkConfig != "" {
|
|
if bootstrap.UserData != "" {
|
|
config["cloud-init.user-data"] = bootstrap.UserData
|
|
}
|
|
if bootstrap.NetworkConfig != "" {
|
|
config["cloud-init.network-config"] = bootstrap.NetworkConfig
|
|
}
|
|
// A VM reads its cloud-init data from this config drive.
|
|
devices["cloud-init"] = map[string]string{"type": "disk", "source": "cloud-init:config"}
|
|
}
|
|
return lxd.InstanceSpec{
|
|
Name: lab.InstanceName(record.ID, node.Name),
|
|
Description: "Lincodex lab node " + node.Name,
|
|
Source: node.Source,
|
|
Profiles: []string{node.Profile},
|
|
Config: config,
|
|
Devices: devices,
|
|
}
|
|
}
|
|
|
|
func (m *Manager) waitReachable(ctx context.Context, record lab.Lab) error {
|
|
for _, node := range record.Nodes {
|
|
address := netip.AddrPortFrom(node.ManagementAddress, node.ManagementPort)
|
|
for {
|
|
err := m.prober.Probe(ctx, address)
|
|
if err == nil {
|
|
break
|
|
}
|
|
timer := time.NewTimer(m.cfg.ProbeInterval)
|
|
select {
|
|
case <-ctx.Done():
|
|
timer.Stop()
|
|
return fmt.Errorf("Manager.waitReachable - node %s: %w", node.Name, ctx.Err())
|
|
case <-timer.C:
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// teardown deletes every instance and bridge of a lab. LXD answers not found
|
|
// for an object that never existed or is already gone, which counts as
|
|
// deleted. On any other failure the lab stays deleting and the next sweep
|
|
// tries again.
|
|
func (m *Manager) teardown(ctx context.Context, record lab.Lab) {
|
|
var errs []error
|
|
for _, node := range record.Nodes {
|
|
if err := m.deleteInstance(ctx, node.Instance); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
if len(errs) == 0 {
|
|
for _, bridge := range record.Bridges {
|
|
if err := m.deleteNetwork(ctx, bridge); err != nil {
|
|
errs = append(errs, err)
|
|
}
|
|
}
|
|
}
|
|
if err := errors.Join(errs...); err != nil {
|
|
m.logger.Warn("lab deletion incomplete; retrying on the next sweep",
|
|
slog.String("lab_id", record.ID.String()), slog.String("error", err.Error()))
|
|
return
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
current, ok := m.labs[record.ID]
|
|
if !ok || !current.NeedsTeardown() {
|
|
return
|
|
}
|
|
current.DeletedAt = m.now().UTC()
|
|
if current.State == lab.Deleting {
|
|
current.State = lab.Deleted
|
|
}
|
|
if err := m.persistLocked(); err != nil {
|
|
m.logger.Error("lab state not saved", slog.String("lab_id", record.ID.String()), slog.String("error", err.Error()))
|
|
}
|
|
m.logger.Info("lab deleted", slog.String("lab_id", record.ID.String()), slog.String("state", string(current.State)))
|
|
}
|
|
|
|
func (m *Manager) deleteInstance(ctx context.Context, name string) error {
|
|
if err := m.lxd.StopInstance(ctx, name); err != nil {
|
|
if errors.Is(err, lxd.ErrNotFound) {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("Manager.deleteInstance - stop %s: %w", name, err)
|
|
}
|
|
if err := m.lxd.DeleteInstance(ctx, name); err != nil && !errors.Is(err, lxd.ErrNotFound) {
|
|
return fmt.Errorf("Manager.deleteInstance - delete %s: %w", name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (m *Manager) deleteNetwork(ctx context.Context, name string) error {
|
|
if err := m.lxd.DeleteNetwork(ctx, name); err != nil && !errors.Is(err, lxd.ErrNotFound) {
|
|
return fmt.Errorf("Manager.deleteNetwork - delete %s: %w", name, err)
|
|
}
|
|
return nil
|
|
}
|