Files

375 lines
14 KiB
Go

package outbound
import (
"context"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"regexp"
"time"
"github.com/google/uuid"
)
// Bounds of the lab provisioner contract (api/labd). They are checked before
// a request leaves the process, so a task family that breaks one fails in the
// caller's tests instead of as a provisioner rejection in production.
const (
// MaxLabNodes and MaxLabCriteria also bound a response.
MaxLabNodes = 8
MaxLabCriteria = 50
// MinLabLifetime and MaxLabLifetime bound LabRequest.Lifetime. The
// provisioner may configure a lower maximum.
MinLabLifetime = 5 * time.Minute
MaxLabLifetime = 4 * time.Hour
// LabSeedBytes is the size of a variant seed.
LabSeedBytes = 32
maxLabTemplateVersion = 10000
redactedLabRequest = "[redacted lab request]"
redactedLabSeed = "[redacted lab seed]"
redactedConsoleAccess = "[redacted lab console token]"
redactedLabCheckResult = "[lab check result]"
)
var (
// ErrLabProvisionerUnavailable is the umbrella of every failure that
// leaves a lab operation without an answer although the candidate did
// nothing wrong: the provisioner is disabled, unreachable, too slow,
// refuses the service token, fails with a server error, answers outside
// the contract, or reports that LXD or a node could not be reached. A
// check that ends with it evaluated nothing: the caller must never score
// it as a failed check, and it reports the service as unavailable. Check
// it with errors.Is before the specific errors below.
//
// A busy lab pool is not this error: Create reports it as LabBusy.
ErrLabProvisionerUnavailable = errors.New("lab provisioner unavailable")
// ErrLabProvisionerDisabled means LAB_PROVISIONER_URL is not set, so no
// request was made.
ErrLabProvisionerDisabled = fmt.Errorf("lab provisioner is disabled: %w", ErrLabProvisionerUnavailable)
// ErrLabProvisionerUnauthorized means the provisioner refused the
// service token (401). It points at deployment configuration and needs an
// operator, not a retry.
ErrLabProvisionerUnauthorized = fmt.Errorf("lab provisioner refused the service token: %w", ErrLabProvisionerUnavailable)
// ErrLabProvisionerBadResponse means the provisioner answered, but not as
// the contract says: a malformed body, an unexpected status, or a status
// that contradicts the request or itself.
ErrLabProvisionerBadResponse = fmt.Errorf("lab provisioner answered outside its contract: %w", ErrLabProvisionerUnavailable)
// ErrInvalidLabRequest reports a request that fails LabRequest.Validate,
// or that the provisioner rejected as invalid (400), for example an
// unknown template version. It is a caller or task content bug; nothing
// was created.
ErrInvalidLabRequest = errors.New("invalid lab request")
// ErrLabNotFound means the provisioner does not hold the lab: it was
// never created, or its deleted record outlived the retention time.
ErrLabNotFound = errors.New("lab not found")
// ErrLabKeyReused means the provisioner already holds a lab under this
// key with a different payload (422). The caller bumps LabKey.Generation
// for a new lab.
ErrLabKeyReused = errors.New("lab key reused with another payload")
// ErrLabNotReady means the lab is not ready for a console token or a
// check (409): it is still provisioning, or it is being deleted, deleted,
// or failed. Read its status.
ErrLabNotReady = errors.New("lab is not ready")
)
var (
labTemplateIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,47}$`)
labNodeNamePattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,14}$`)
)
// LabKey identifies one lab of an attempt item. The adapter turns it into
// the opaque lab ID that the provisioner stores, so the provisioner never sees
// these values and every retry of the same key reaches the same lab.
type LabKey struct {
// AttemptItemID is the attempt item whose lab this is.
AttemptItemID uuid.UUID
// Generation is 0 for the first lab of the item. After a failed lab the
// caller increments it; the provisioner would return the failed lab for
// the old key.
Generation uint32
}
func (key LabKey) validate() error {
if key.AttemptItemID == uuid.Nil {
return invalidLabRequest("key must name the attempt item")
}
return nil
}
// LabTemplateRef names a template of the provisioner build.
type LabTemplateRef struct {
ID string
Version int32
}
// LabSeed is the variant seed of an item instance. The template renders the
// node configuration and the checker criteria of the variant from it, so it
// is as secret as an answer key: String, GoString, Format, and LogValue
// redact it. Hex returns the wire form.
type LabSeed [LabSeedBytes]byte
func (seed LabSeed) Hex() string { return hex.EncodeToString(seed[:]) }
func (seed LabSeed) String() string { return redactedLabSeed }
func (seed LabSeed) GoString() string { return redactedLabSeed }
// Format redacts every verb; without it %x would print the bytes.
func (seed LabSeed) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedLabSeed))
}
func (seed LabSeed) LogValue() slog.Value { return slog.StringValue(redactedLabSeed) }
// LabRequest asks for one lab of a template variant. It carries nothing about
// the candidate: the provisioner receives only a template reference, a seed,
// and a lifetime. The whole request is redacted when printed or logged
// because it holds the seed.
type LabRequest struct {
Key LabKey
Template LabTemplateRef
Seed LabSeed
// Lifetime counts from the creation of the lab. The provisioner deletes
// the lab when it ends, also across its own restarts.
Lifetime time.Duration
}
func (request LabRequest) String() string { return redactedLabRequest }
func (request LabRequest) GoString() string { return redactedLabRequest }
// Format redacts every verb; without it %+v would print the fields.
func (request LabRequest) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedLabRequest))
}
func (request LabRequest) LogValue() slog.Value { return slog.StringValue(redactedLabRequest) }
// Validate reports a request that the provisioner would reject by its
// contract. Errors wrap ErrInvalidLabRequest and never include the seed.
func (request LabRequest) Validate() error {
if err := request.Key.validate(); err != nil {
return err
}
switch {
case !labTemplateIDPattern.MatchString(request.Template.ID):
return invalidLabRequest("template ID must match [a-z0-9][a-z0-9-]{0,47}")
case request.Template.Version < 1 || request.Template.Version > maxLabTemplateVersion:
return invalidLabRequest("template version must be 1 to 10000")
case request.Seed == (LabSeed{}):
return invalidLabRequest("seed must not be zero")
case request.Lifetime < MinLabLifetime || request.Lifetime > MaxLabLifetime:
return invalidLabRequest("lifetime must be 5 minutes to 4 hours")
case request.Lifetime%time.Second != 0:
return invalidLabRequest("lifetime must be whole seconds")
}
return nil
}
// ValidateLabNodeName reports a node name that the contract does not allow.
func ValidateLabNodeName(name string) error {
if !labNodeNamePattern.MatchString(name) {
return fmt.Errorf("outbound.ValidateLabNodeName - node name must match [a-z][a-z0-9-]{0,14}: %w", ErrInvalidLabRequest)
}
return nil
}
func invalidLabRequest(reason string) error {
return fmt.Errorf("LabRequest.Validate - %s: %w", reason, ErrInvalidLabRequest)
}
// LabState is what a provisioner call established about a lab. The zero
// value is not a state and must never be read as readiness.
type LabState string
const (
// LabProvisioning means capacity is reserved and the nodes are being
// prepared. Poll Status later.
LabProvisioning LabState = "provisioning"
// LabReady means every node answers; console tokens and checks work.
LabReady LabState = "ready"
// LabDeleting means the lab ended and its resources are being removed.
LabDeleting LabState = "deleting"
// LabDeleted means every resource of the lab is gone.
LabDeleted LabState = "deleted"
// LabFailed means the provisioning failed for an infrastructure reason;
// FailureReason says which. It never depends on the candidate. Its
// resources are removed; the caller starts a new lab with the next
// LabKey.Generation.
LabFailed LabState = "failed"
// LabBusy means the lab does not fit the capacity of the provisioner, or
// the provisioner is draining. Nothing was stored and nothing of the
// attempt is consumed; create again with the same key after RetryAfter.
// Only Create reports it, and it is a capacity signal, never an
// infrastructure failure.
LabBusy LabState = "busy"
)
// LabFailureReason says why a lab failed.
type LabFailureReason string
const (
LabFailureProvisioning LabFailureReason = "provisioning_failed"
LabFailureTimedOut LabFailureReason = "provisioning_timed_out"
LabFailureInterrupted LabFailureReason = "interrupted"
)
// LabNodeKind is the guest system of a node.
type LabNodeKind string
const (
LabNodeMikroTik LabNodeKind = "mikrotik"
LabNodeUbuntu LabNodeKind = "ubuntu"
)
// LabNode is a node of a lab by its template name. It never carries an
// address or a credential: the backend reaches a node only through a console
// token, and the provisioner checks it itself.
type LabNode struct {
Name string
Kind LabNodeKind
}
// LabStatus is the state of a lab after one provisioner call.
type LabStatus struct {
State LabState
// LabID is the opaque ID the provisioner holds the lab under. It
// identifies no user, attempt, or task; it is safe to log and matches the
// provisioner's logs.
LabID string
// RetryAfter is the provisioner's wait hint for LabBusy only.
RetryAfter time.Duration
// The fields below are set for every state except LabBusy. ReadyAt,
// DeletedAt, and FailureReason are zero until they apply.
Template LabTemplateRef
CreatedAt time.Time
ReadyAt time.Time
ExpiresAt time.Time
DeletedAt time.Time
FailureReason LabFailureReason
Nodes []LabNode
}
// Active reports whether the lab holds or is about to hold resources that a
// candidate can use.
func (status LabStatus) Active() bool {
return status.State == LabProvisioning || status.State == LabReady
}
// LabConsoleToken lets the console gateway attach to the serial console of
// one node once. The token is a secret of the gateway: String, GoString,
// Format, and LogValue redact it, and it must never reach a browser or a log.
type LabConsoleToken struct {
Token string
Node string
ExpiresAt time.Time
AttachPath string
}
func (token LabConsoleToken) String() string { return redactedConsoleAccess }
func (token LabConsoleToken) GoString() string { return redactedConsoleAccess }
// Format redacts every verb; without it %+v would print the token.
func (token LabConsoleToken) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedConsoleAccess))
}
func (token LabConsoleToken) LogValue() slog.Value { return slog.StringValue(redactedConsoleAccess) }
// LabCriterionResult says whether one criterion of the variant holds.
type LabCriterionResult struct {
ID string
Passed bool
}
// LabCheckResult is a validated check of a ready lab. It is checker state for
// scoring only and must never reach the candidate.
type LabCheckResult struct {
CheckedAt time.Time
Score int
MaxScore int
Criteria []LabCriterionResult
}
// Validate reports a result that contradicts itself, so a malformed answer
// of the provisioner can never become a score.
func (result LabCheckResult) Validate() error {
if len(result.Criteria) < 1 || len(result.Criteria) > MaxLabCriteria {
return errors.New("LabCheckResult.Validate - criteria must have 1 to 50 entries")
}
passed := 0
seen := make(map[string]struct{}, len(result.Criteria))
for _, criterion := range result.Criteria {
if _, duplicate := seen[criterion.ID]; duplicate || criterion.ID == "" {
return errors.New("LabCheckResult.Validate - criterion IDs must be unique and not empty")
}
seen[criterion.ID] = struct{}{}
if criterion.Passed {
passed++
}
}
if result.MaxScore != len(result.Criteria) || result.Score != passed {
return errors.New("LabCheckResult.Validate - score must count the passed criteria")
}
if result.CheckedAt.IsZero() {
return errors.New("LabCheckResult.Validate - check time must be set")
}
return nil
}
// LogValue summarizes the result without criterion IDs, which describe the
// variant.
func (result LabCheckResult) LogValue() slog.Value {
return slog.GroupValue(slog.Int("score", result.Score), slog.Int("max_score", result.MaxScore))
}
func (result LabCheckResult) String() string { return redactedLabCheckResult }
// LabProvisioner creates, inspects, checks, and deletes practical labs
// through the lab provisioner service (api/labd). Only that service talks to
// LXD; the backend never holds the LXD socket or a node address.
//
// Every method makes exactly one provisioner call and never retries or
// sleeps; polling and backoff belong to the caller. Create is idempotent by
// request.Key: the same key with the same payload returns the current state
// of one lab and never creates a second one.
//
// A nil error from Create comes with provisioning, ready, deleting, deleted,
// failed, or busy. Busy holds RetryAfter, stores nothing, and is the only
// capacity outcome; it is never an error. An error means that nothing
// happened that the caller may rely on:
// - ErrInvalidLabRequest: the request is invalid or unknown to the
// provisioner; nothing was created.
// - ErrLabProvisionerUnavailable (including the disabled, unauthorized,
// and bad-response forms): no answer could be obtained. For Check it is
// never a failed check and never a reason to fail the candidate.
// - ErrLabNotFound: the provisioner does not hold the lab.
// - ErrLabKeyReused (Create): the key was used with another payload.
// - ErrLabNotReady (ConsoleToken, Check): the lab is not ready.
// - the context error when ctx ended.
//
// The returned values are zero when err is not nil. Errors and logs never
// include the seed, a console token, or the service token.
type LabProvisioner interface {
Create(ctx context.Context, request LabRequest) (LabStatus, error)
Status(ctx context.Context, key LabKey) (LabStatus, error)
Delete(ctx context.Context, key LabKey) (LabStatus, error)
ConsoleToken(ctx context.Context, key LabKey, node string) (LabConsoleToken, error)
Check(ctx context.Context, key LabKey) (LabCheckResult, error)
}