Files
ilkerandClaude Opus 5.5 e7b3d30105 placement: whole machines, held one cluster at a time
A compute node on a bare-metal site is given a whole machine: Node.Machine
marks one, HeadOnly marks the hypervisor beside them that runs heads, and
AllocatedTo says who has a machine. Placement takes a machine whole, never
puts a head on one or compute on a head-only host. The database holds each
machine for one live cluster (cluster_machine, migration 010), from the
moment it is recorded, and Reservations reports it with no device id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:34:12 +01:00

262 lines
8.5 KiB
Go

package store
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/ilkermanap/hpcod/internal/model"
)
// ErrDeviceHeld means a device the placement asked for already belongs to
// another live cluster. It is not a race to retry: the plan was made against
// an inventory that has since moved on, and the caller has to re-plan.
var ErrDeviceHeld = errors.New("device already held by another cluster")
// Placement is where a cluster is to run. It is the planner's decision in
// the shape the database stores it, deliberately without importing the
// planner: persistence should not depend on how the choice was made.
type Placement struct {
Site string
VMs []VM
}
// VM is one guest pinned to one hypervisor.
type VM struct {
Role string `json:"role"` // "head" or "compute"
NodeIndex int `json:"node_index"` // 0 for the head, 1..n for compute
HostNode string `json:"host_node"`
Cores int `json:"cores"`
MemoryGB int `json:"memory_gb"`
Devices []Device `json:"devices,omitempty"`
// Machine: HostNode is a physical server held whole for this node.
Machine bool `json:"machine,omitempty"`
}
// Device is one piece of hardware handed to a VM.
type Device struct {
NativeID string `json:"native_id"`
Capability string `json:"capability"`
}
func (p Placement) validate() error {
if p.Site == "" {
return errors.New("placement has no site")
}
if len(p.VMs) == 0 {
return errors.New("placement has no VMs")
}
heads := 0
for _, v := range p.VMs {
switch v.Role {
case "head":
heads++
case "compute":
default:
return fmt.Errorf("unknown VM role %q", v.Role)
}
if v.HostNode == "" {
return fmt.Errorf("%s%d: no host node - placement must say which hypervisor", v.Role, v.NodeIndex)
}
if v.Machine && v.Role != "compute" {
return fmt.Errorf("%s%d: only a compute node can be given a machine", v.Role, v.NodeIndex)
}
if v.Cores < 1 || v.MemoryGB < 1 {
return fmt.Errorf("%s%d: cores and memory must be positive", v.Role, v.NodeIndex)
}
}
if heads != 1 {
return fmt.Errorf("placement has %d head nodes, want exactly 1", heads)
}
return nil
}
// recordPlacement writes the VMs and their devices inside the caller's
// transaction, so a device that turns out to be taken rolls back the cluster
// row and its address with it. A half-allocated cluster - an address held by
// a cluster that was never placed - is worse than a failed request, because
// nothing would ever come along to release it.
func recordPlacement(ctx context.Context, tx pgx.Tx, serialID int64, p Placement) error {
for _, v := range p.VMs {
if _, err := tx.Exec(ctx, `
INSERT INTO cluster_vm (cluster_serial_id, role, node_index, host_node, cores, memory_gb)
VALUES ($1, $2, $3, $4, $5, $6)`,
serialID, v.Role, v.NodeIndex, v.HostNode, v.Cores, v.MemoryGB); err != nil {
return err
}
if v.Machine {
_, err := tx.Exec(ctx, `
INSERT INTO cluster_machine (cluster_serial_id, role, node_index, site, machine)
VALUES ($1, $2, $3, $4, $5)`,
serialID, v.Role, v.NodeIndex, p.Site, v.HostNode)
if isUniqueViolationOn(err, "cluster_machine_live_unique") {
return fmt.Errorf("%w: machine %s on %s", ErrDeviceHeld, v.HostNode, p.Site)
}
if err != nil {
return err
}
}
for _, d := range v.Devices {
_, err := tx.Exec(ctx, `
INSERT INTO cluster_device
(cluster_serial_id, role, node_index, site, host_node, native_id, capability)
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
serialID, v.Role, v.NodeIndex, p.Site, v.HostNode, d.NativeID, d.Capability)
if isUniqueViolationOn(err, "cluster_device_live_unique") {
return fmt.Errorf("%w: %s on %s/%s", ErrDeviceHeld, d.NativeID, p.Site, v.HostNode)
}
if err != nil {
return err
}
}
}
return nil
}
// Adopt records a cluster that already exists, at the address it is already
// using.
//
// A control plane that can only account for what it built itself is not
// accounting for the estate. Worse, it is dangerous: c002 was provisioned by
// hand and holds subnet and MAC octet 2, so an allocator that does not know
// about it will eventually hand 2 to someone else and put two live clusters
// on the same addresses.
//
// Unlike AllocateCluster this takes the id rather than choosing one, and
// fails if it is in use - which is the same partial unique index doing the
// same job from the other direction.
func (s *Store) Adopt(ctx context.Context, tenantID int64, clusterID int16, p Placement, state string, lease *time.Time) (*Cluster, error) {
if err := p.validate(); err != nil {
return nil, err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, allocLockKey); err != nil {
return nil, err
}
var c Cluster
err = tx.QueryRow(ctx, `
INSERT INTO cluster (cluster_id, tenant_id, site, lease_expires_at, state)
VALUES ($1, $2, $3, $4, $5)
RETURNING serial_id, cluster_id, tenant_id, site, accounting_name, state,
lease_expires_at, created_at`,
clusterID, tenantID, p.Site, lease, state).Scan(
&c.SerialID, &c.ClusterID, &c.TenantID, &c.Site,
&c.AccountingName, &c.State, &c.LeaseExpiresAt, &c.CreatedAt)
if isUniqueViolationOn(err, "cluster_live_id_unique") {
return nil, fmt.Errorf("cluster id %d is already held by a live cluster", clusterID)
}
if err != nil {
return nil, err
}
if err := recordPlacement(ctx, tx, c.SerialID, p); err != nil {
return nil, err
}
if err := fillTenantName(ctx, tx, &c); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &c, nil
}
// fillTenantName completes a Cluster built from an INSERT ... RETURNING,
// which cannot join. Without it the field would be populated on a listing
// and empty on a create - the kind of difference nothing notices until
// something renders a blank where a name should be.
func fillTenantName(ctx context.Context, tx pgx.Tx, c *Cluster) error {
return tx.QueryRow(ctx, `SELECT name FROM tenant WHERE id = $1`, c.TenantID).Scan(&c.TenantName)
}
// Reservations lists every device, and every whole machine, promised to a
// cluster that still exists. A machine's has no NativeID.
// Feed it through model.ApplyReservations before planning, or the planner
// will offer hardware it has already given away to a cluster whose VMs are
// not built yet.
func (s *Store) Reservations(ctx context.Context) ([]model.Reservation, error) {
rows, err := s.pool.Query(ctx, `
SELECT d.site, d.host_node, d.native_id, c.accounting_name
FROM cluster_device d
JOIN cluster c ON c.serial_id = d.cluster_serial_id
WHERE d.released_at IS NULL AND c.destroyed_at IS NULL
UNION ALL
SELECT m.site, m.machine, '', c.accounting_name
FROM cluster_machine m
JOIN cluster c ON c.serial_id = m.cluster_serial_id
WHERE m.released_at IS NULL AND c.destroyed_at IS NULL
ORDER BY 1, 2, 3`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []model.Reservation
for rows.Next() {
var r model.Reservation
if err := rows.Scan(&r.Site, &r.HostNode, &r.NativeID, &r.HeldBy); err != nil {
return nil, err
}
out = append(out, r)
}
return out, rows.Err()
}
// VMs returns where one cluster's guests were placed, which is what the
// provisioner needs in order to build it.
func (s *Store) VMs(ctx context.Context, serialID int64) ([]VM, error) {
rows, err := s.pool.Query(ctx, `
SELECT role, node_index, host_node, cores, memory_gb
FROM cluster_vm WHERE cluster_serial_id = $1
ORDER BY role DESC, node_index`, serialID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []VM
idx := map[string]int{}
for rows.Next() {
var v VM
if err := rows.Scan(&v.Role, &v.NodeIndex, &v.HostNode, &v.Cores, &v.MemoryGB); err != nil {
return nil, err
}
idx[fmt.Sprintf("%s/%d", v.Role, v.NodeIndex)] = len(out)
out = append(out, v)
}
if err := rows.Err(); err != nil {
return nil, err
}
drows, err := s.pool.Query(ctx, `
SELECT role, node_index, native_id, capability
FROM cluster_device
WHERE cluster_serial_id = $1 AND released_at IS NULL
ORDER BY native_id`, serialID)
if err != nil {
return nil, err
}
defer drows.Close()
for drows.Next() {
var role, nativeID, capability string
var nodeIndex int
if err := drows.Scan(&role, &nodeIndex, &nativeID, &capability); err != nil {
return nil, err
}
if i, ok := idx[fmt.Sprintf("%s/%d", role, nodeIndex)]; ok {
out[i].Devices = append(out[i].Devices, Device{NativeID: nativeID, Capability: capability})
}
}
return out, drows.Err()
}