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

355 lines
13 KiB
Go

// Package store is the control plane's memory: who owns which cluster, which
// addresses are in use, and when a lease runs out.
//
// The interesting part is allocation. A cluster id is one byte of a MAC and
// one octet of a subnet, so it is bounded at 254 and has to be recycled, and
// recycling is safe only while no two live clusters share one. That is not a
// rule application code can keep on its own: two requests arriving together
// would both read the same free id and both believe they had it. So the
// choosing and the claiming happen in one statement, and the database refuses
// the loser.
package store
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
// ErrNoFreeID means every address between 1 and 254 belongs to a cluster that
// still exists. It is a capacity limit on concurrent clusters, not on tenants.
var ErrNoFreeID = errors.New("no free cluster id: all 254 are held by live clusters")
type Store struct{ pool *pgxpool.Pool }
// Cluster is one provisioned installation.
type Cluster struct {
SerialID int64 `json:"serial_id"`
ClusterID int16 `json:"cluster_id"`
TenantID int64 `json:"tenant_id"`
// TenantName is joined in rather than looked up by the caller: every
// place a cluster is shown, it is shown to someone who wants to know
// whose it is, and an id alone does not answer that.
TenantName string `json:"tenant_name"`
Site string `json:"site"`
AccountingName string `json:"accounting_name"`
State string `json:"state"`
LeaseExpiresAt *time.Time `json:"lease_expires_at"`
CreatedAt time.Time `json:"created_at"`
// DestroyedAt is nil while the cluster is live. It is what a released
// cluster is ordered and dated by: the record outlives the machines,
// which is the point of keeping it.
DestroyedAt *time.Time `json:"destroyed_at,omitempty"`
}
// LeaseLeft reports how long is left, and whether there is a lease at all.
func (c Cluster) LeaseLeft() (time.Duration, bool) {
if c.LeaseExpiresAt == nil {
return 0, false
}
return time.Until(*c.LeaseExpiresAt), true
}
func Open(ctx context.Context, dsn string) (*Store, error) {
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
return nil, err
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("database unreachable: %w", err)
}
return &Store{pool: pool}, nil
}
func (s *Store) Close() { s.pool.Close() }
// EnsureTenant returns the id of a tenant, creating it if this is the first
// time it has asked for anything.
func (s *Store) EnsureTenant(ctx context.Context, name, owner string) (int64, error) {
var id int64
err := s.pool.QueryRow(ctx, `
INSERT INTO tenant (name, owner) VALUES ($1, $2)
ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name
RETURNING id`, name, owner).Scan(&id)
return id, err
}
// allocateSQL claims the lowest free address in one statement.
//
// generate_series produces the candidates, NOT EXISTS filters out the ones
// held by a live cluster, and the INSERT takes the first. Choosing and
// claiming are one statement rather than a SELECT then an INSERT, because
// two callers running the second form would both pass the check.
const allocateSQL = `
INSERT INTO cluster (cluster_id, tenant_id, site, lease_expires_at, state)
SELECT gs, $1, $2, $3, 'requested'
FROM generate_series(1, 254) AS gs
WHERE NOT EXISTS (
SELECT 1 FROM cluster c
WHERE c.cluster_id = gs AND c.destroyed_at IS NULL)
ORDER BY gs
LIMIT 1
RETURNING serial_id, cluster_id, tenant_id, site, accounting_name, state,
lease_expires_at, created_at`
// allocLockKey serialises allocators against each other. The database is
// dedicated to hpcod, so the key cannot collide with another application's.
const allocLockKey int64 = 0x68706364_616c6c6f // "hpcd" "allo"
// AllocateCluster reserves an address for a new cluster and records who it is
// for.
//
// Two mechanisms, doing different jobs. The advisory lock makes concurrent
// allocators take turns, so the common case does no wasted work. The partial
// unique index is what actually guarantees the invariant, and covers a writer
// that never took the lock - an operator inserting a row by hand, say. The
// retry exists only for that second case.
// The placement is written in the same transaction as the address. The two
// cannot be separated: a cluster holding an address but no record of where
// it runs is one nothing will ever come back to release.
//
// The applications are written there too, and for the same reason. They are
// already resolved against the catalogue by the time they arrive here; a
// cluster that holds an address but no record of what it is for provisions
// as an empty scheduler and looks healthy doing it, which is how they were
// all built before this argument existed.
//
// A lease of zero or less means no expiry: the cluster stands until someone
// removes it. Use SetLease to attach or change an expiry afterwards.
func (s *Store) AllocateCluster(ctx context.Context, tenantID int64, p Placement, lease time.Duration, apps []ClusterApp, projectID *int64) (*Cluster, error) {
if err := p.validate(); err != nil {
return nil, err
}
var expires *time.Time
if lease > 0 {
t := time.Now().Add(lease)
expires = &t
}
for attempt := 0; attempt < 3; attempt++ {
c, err := s.allocateOnce(ctx, tenantID, p, expires, apps, projectID)
switch {
case err == nil:
return c, nil
case errors.Is(err, pgx.ErrNoRows):
// The SELECT produced nothing: every address is held.
return nil, ErrNoFreeID
case isUniqueViolationOn(err, "cluster_live_id_unique"):
continue // someone claimed the address without the lock; take the next
default:
return nil, err
}
}
return nil, errors.New("cluster id allocation kept losing races; try again")
}
func (s *Store) allocateOnce(ctx context.Context, tenantID int64, p Placement, expires *time.Time, apps []ClusterApp, projectID *int64) (*Cluster, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed
// Held until the transaction ends, so the scan below cannot see a free
// address that another allocator is in the middle of taking.
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock($1)`, allocLockKey); err != nil {
return nil, err
}
var c Cluster
if err := tx.QueryRow(ctx, allocateSQL, tenantID, p.Site, expires).Scan(
&c.SerialID, &c.ClusterID, &c.TenantID, &c.Site,
&c.AccountingName, &c.State, &c.LeaseExpiresAt, &c.CreatedAt); err != nil {
return nil, err
}
if err := recordPlacement(ctx, tx, c.SerialID, p); err != nil {
return nil, err
}
if err := recordApps(ctx, tx, c.SerialID, apps); err != nil {
return nil, err
}
// In the allocating transaction, for the same reason the placement and
// the applications are: a cluster holding an address with no record of
// what it was for is one nobody can account for afterwards, and
// afterwards is when the question gets asked.
//
// The project has to belong to the same tenant. Checked here rather
// than at the caller because this is the only place that has both in
// one transaction, and a cluster filed against somebody else's project
// is a leak of what they are working on.
if projectID != nil {
var ok bool
if err := tx.QueryRow(ctx, `
SELECT EXISTS (SELECT 1 FROM project
WHERE id = $1 AND tenant_id = $2 AND closed_at IS NULL)`,
*projectID, tenantID).Scan(&ok); err != nil {
return nil, err
}
if !ok {
return nil, fmt.Errorf("project %d is not an open project of this tenant", *projectID)
}
if _, err := tx.Exec(ctx,
`UPDATE cluster SET project_id = $2 WHERE serial_id = $1`,
c.SerialID, *projectID); 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
}
// isUniqueViolationOn names the constraint, because the two that can fire
// here mean opposite things. A clash on the address is a race worth
// retrying; a clash on a device means the plan was made against a stale
// inventory and retrying would only lose again.
func isUniqueViolationOn(err error, constraint string) bool {
var pge *pgconn.PgError
return errors.As(err, &pge) && pge.Code == "23505" && pge.ConstraintName == constraint
}
// SetState records a lifecycle transition. Written before the side effect it
// describes, so a provisioner that dies halfway leaves a cluster that is
// recognisably mid-flight rather than ambiguous.
func (s *Store) SetState(ctx context.Context, serialID int64, state string) error {
tag, err := s.pool.Exec(ctx,
`UPDATE cluster SET state = $2 WHERE serial_id = $1 AND destroyed_at IS NULL`,
serialID, state)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("cluster %d: not found, or already destroyed", serialID)
}
return nil
}
// SetLease moves a cluster's expiry, or removes it when expires is nil. This
// is how a lease is extended, and it is deliberately separate from
// allocation: granting time later is a different decision from granting it
// up front, and usually a different caller.
func (s *Store) SetLease(ctx context.Context, serialID int64, expires *time.Time) error {
tag, err := s.pool.Exec(ctx,
`UPDATE cluster SET lease_expires_at = $2 WHERE serial_id = $1 AND destroyed_at IS NULL`,
serialID, expires)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("cluster %d: not found, or already destroyed", serialID)
}
return nil
}
// Release frees the address. The row stays: it is what says this cluster
// existed, who it belonged to, and what its accounting name was, all of which
// outlive the cluster itself.
func (s *Store) Release(ctx context.Context, serialID int64) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed
tag, err := tx.Exec(ctx, `
UPDATE cluster
SET destroyed_at = now(), state = 'deleted'
WHERE serial_id = $1 AND destroyed_at IS NULL`, serialID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("cluster %d: not found, or already released", serialID)
}
// The hardware goes back at the same moment the address does. Releasing
// one without the other would leave a GPU nobody holds and nobody can be
// given.
if _, err := tx.Exec(ctx, `
UPDATE cluster_device SET released_at = now()
WHERE cluster_serial_id = $1 AND released_at IS NULL`, serialID); err != nil {
return err
}
if _, err := tx.Exec(ctx, `
UPDATE cluster_machine SET released_at = now()
WHERE cluster_serial_id = $1 AND released_at IS NULL`, serialID); err != nil {
return err
}
return tx.Commit(ctx)
}
// Live lists the clusters that still exist.
func (s *Store) Live(ctx context.Context) ([]Cluster, error) {
return s.query(ctx, `
SELECT c.serial_id, c.cluster_id, c.tenant_id, t.name, c.site,
c.accounting_name, c.state, c.lease_expires_at, c.created_at,
c.destroyed_at
FROM cluster c JOIN tenant t ON t.id = c.tenant_id
WHERE c.destroyed_at IS NULL ORDER BY c.cluster_id`)
}
// Expired lists live clusters whose lease has run out. A cluster with no
// lease never appears: an unbounded lease is a deliberate choice, not an
// oversight for the reaper to correct.
func (s *Store) Expired(ctx context.Context) ([]Cluster, error) {
return s.query(ctx, `
SELECT c.serial_id, c.cluster_id, c.tenant_id, t.name, c.site,
c.accounting_name, c.state, c.lease_expires_at, c.created_at,
c.destroyed_at
FROM cluster c JOIN tenant t ON t.id = c.tenant_id
WHERE c.destroyed_at IS NULL
AND c.lease_expires_at IS NOT NULL
AND c.lease_expires_at < now()
ORDER BY c.lease_expires_at`)
}
// Released lists clusters that are gone, newest first.
//
// The record outlives the machines on purpose: it is what a bill is
// computed from, and now also what says whose archive is whose. Bounded,
// because this is a page and not an export - an operator who wants the
// whole history has the database.
func (s *Store) Released(ctx context.Context, limit int) ([]Cluster, error) {
if limit <= 0 || limit > 500 {
limit = 100
}
return s.query(ctx, `
SELECT c.serial_id, c.cluster_id, c.tenant_id, t.name, c.site,
c.accounting_name, c.state, c.lease_expires_at, c.created_at,
c.destroyed_at
FROM cluster c JOIN tenant t ON t.id = c.tenant_id
WHERE c.destroyed_at IS NOT NULL
ORDER BY c.destroyed_at DESC
LIMIT $1`, limit)
}
func (s *Store) query(ctx context.Context, sql string, args ...any) ([]Cluster, error) {
rows, err := s.pool.Query(ctx, sql, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Cluster
for rows.Next() {
var c Cluster
if err := rows.Scan(&c.SerialID, &c.ClusterID, &c.TenantID, &c.TenantName,
&c.Site, &c.AccountingName, &c.State, &c.LeaseExpiresAt, &c.CreatedAt,
&c.DestroyedAt); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}