You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

328 lines
11 KiB
Go

package hypervisor
import (
"context"
"errors"
"fmt"
"strings"
"time"
)
// PowerAction is the deliberately small set of libvirt lifecycle operations
// exposed by the agent. The values are also the fixed virsh subcommands; no
// caller-provided command text is ever passed to the host.
type PowerAction string
const (
PowerActionStart PowerAction = "start"
PowerActionShutdown PowerAction = "shutdown"
PowerActionDestroy PowerAction = "destroy"
PowerActionReboot PowerAction = "reboot"
PowerActionSuspend PowerAction = "suspend"
PowerActionResume PowerAction = "resume"
)
var (
ErrInvalidPowerAction = errors.New("invalid power action")
ErrInvalidPowerState = errors.New("invalid domain power state")
ErrPowerActionRejected = errors.New("power action rejected for current domain state")
ErrPowerReadbackMismatch = errors.New("power state read-back mismatch")
)
// DomainPowerState is the canonical state vocabulary returned by virsh
// domstate. In particular, libvirt's "shut off" spelling is normalized to
// "shutoff" and "in shutdown" is retained as the transitional "shutdown"
// state used by the panel.
type DomainPowerState string
const (
StateNoState DomainPowerState = "nostate"
StateRunning DomainPowerState = "running"
StateBlocked DomainPowerState = "blocked"
StatePaused DomainPowerState = "paused"
StateShutdown DomainPowerState = "shutdown"
StateShutoff DomainPowerState = "shutoff"
StateCrashed DomainPowerState = "crashed"
StatePMSuspended DomainPowerState = "pmsuspended"
)
// PowerResult records the state observed after a lifecycle request. A failed
// or uncertain shutdown may carry StateShutdown while the guest is still
// converging; callers must wait for a later read-back before declaring it
// powered off. The normal success predicate only accepts StateShutoff.
type PowerResult struct {
UUID string `json:"uuid"`
Action PowerAction `json:"action"`
State DomainPowerState `json:"state"`
Active bool `json:"active"`
ObservedAt time.Time `json:"observed_at"`
}
// PowerRequest is the typed form used at the panel boundary. Backend methods
// still accept UUID and action separately so implementations cannot silently
// ignore either identity component.
type PowerRequest struct {
UUID string
Action PowerAction
}
// ParsePowerAction accepts only the canonical lower-case action names. It does
// not trim or otherwise normalize input: the HTTP contract is a strict
// allowlist, and accepting surrounding whitespace would make malformed
// payloads appear valid at one boundary but not another.
func ParsePowerAction(value string) (PowerAction, error) {
switch PowerAction(value) {
case PowerActionStart,
PowerActionShutdown,
PowerActionDestroy,
PowerActionReboot,
PowerActionSuspend,
PowerActionResume:
return PowerAction(value), nil
default:
return "", fmt.Errorf("%w: %q", ErrInvalidPowerAction, value)
}
}
// ParseDomainPowerState parses the one-line output of `virsh domstate`.
// Multiple non-empty lines are rejected so a future --reason output cannot be
// accidentally interpreted as a state.
func ParseDomainPowerState(data []byte) (DomainPowerState, error) {
trimmed := strings.TrimSpace(string(data))
if trimmed == "" || strings.ContainsAny(trimmed, "\r\n") {
return "", fmt.Errorf("%w: expected one state line", ErrInvalidPowerState)
}
normalized := strings.ToLower(strings.Join(strings.Fields(trimmed), " "))
switch normalized {
case "no state", "nostate":
return StateNoState, nil
case "running":
return StateRunning, nil
case "blocked":
return StateBlocked, nil
case "paused":
return StatePaused, nil
case "shutdown", "in shutdown":
// Libvirt reports this transitional state while the guest is still
// processing an ACPI request. It must not be collapsed into terminal
// shutoff, otherwise callers can publish a false powered-off result.
return StateShutdown, nil
case "shut off", "shutoff":
return StateShutoff, nil
case "crashed":
return StateCrashed, nil
case "pmsuspended", "pm suspended":
return StatePMSuspended, nil
default:
return "", fmt.Errorf("%w: %q", ErrInvalidPowerState, trimmed)
}
}
// IsActive follows libvirt's domain-active interpretation for the states the
// agent exposes. Transitional and paused states remain active; no-state and
// shutoff do not.
func (state DomainPowerState) IsActive() bool {
switch state {
case StateRunning, StateBlocked, StatePaused, StateShutdown, StateCrashed, StatePMSuspended:
return true
default:
return false
}
}
// PowerActionSatisfied reports whether an observed state proves that the
// requested lifecycle outcome has been reached. It is shared by the normal
// command path and the read-only reconcile path so they cannot drift.
func PowerActionSatisfied(action PowerAction, state DomainPowerState) bool {
return powerActionSatisfied(action, state)
}
// PowerActionReconcileSatisfied is the stricter predicate for an operation
// whose response was lost. A running read-back cannot prove that reboot was
// actually observed by the guest, so reboot remains uncertain even when the
// current state is running; reconciliation must not manufacture success from
// an indistinguishable pre-action state.
func PowerActionReconcileSatisfied(action PowerAction, state DomainPowerState) bool {
if action == PowerActionReboot {
return false
}
return powerActionSatisfied(action, state)
}
func powerActionSatisfied(action PowerAction, state DomainPowerState) bool {
switch action {
case PowerActionStart, PowerActionReboot, PowerActionResume:
return state == StateRunning
case PowerActionShutdown:
// `in shutdown` is a transitional libvirt state. It proves that an
// ACPI request was accepted, but not that the guest is powered off.
// Callers must keep the operation pending/uncertain until a later
// read-back observes the terminal `shutoff` state.
return state == StateShutoff
case PowerActionDestroy:
return state == StateShutoff
case PowerActionSuspend:
return state == StatePaused
default:
return false
}
}
// powerActionCanBeAlreadySatisfied identifies actions for which a command
// error is safe to treat as an idempotent success after an authoritative state
// read-back. Reboot is intentionally excluded: observing running does not
// prove that a reboot actually occurred.
func powerActionCanBeAlreadySatisfied(action PowerAction, state DomainPowerState) bool {
if action == PowerActionReboot {
return false
}
return powerActionSatisfied(action, state)
}
func fakePowerTransition(current DomainPowerState, action PowerAction) (DomainPowerState, error) {
switch action {
case PowerActionStart:
if current == StateRunning {
return current, nil
}
if current == StatePaused || current == StateBlocked || current == StatePMSuspended {
return "", fmt.Errorf("%w: cannot start from %s", ErrPowerActionRejected, current)
}
return StateRunning, nil
case PowerActionShutdown:
if current == StateShutoff || current == StateShutdown {
// The deterministic backend has no guest to converge asynchronously;
// model the terminal result so normal API tests exercise the same
// success predicate as a host that completed ACPI shutdown.
return StateShutoff, nil
}
if current == StateNoState {
return "", fmt.Errorf("%w: domain has no state", ErrPowerActionRejected)
}
return StateShutdown, nil
case PowerActionDestroy:
if current == StateShutoff {
return current, nil
}
if current == StateNoState {
return "", fmt.Errorf("%w: domain has no state", ErrPowerActionRejected)
}
return StateShutoff, nil
case PowerActionReboot:
if !current.IsActive() || current == StateShutdown || current == StateCrashed {
return "", fmt.Errorf("%w: cannot reboot from %s", ErrPowerActionRejected, current)
}
return StateRunning, nil
case PowerActionSuspend:
if current == StatePaused {
return current, nil
}
if current != StateRunning {
return "", fmt.Errorf("%w: cannot suspend from %s", ErrPowerActionRejected, current)
}
return StatePaused, nil
case PowerActionResume:
if current == StateRunning {
return current, nil
}
if current != StatePaused && current != StatePMSuspended {
return "", fmt.Errorf("%w: cannot resume from %s", ErrPowerActionRejected, current)
}
return StateRunning, nil
default:
return "", fmt.Errorf("%w: %q", ErrInvalidPowerAction, action)
}
}
func powerResult(uuid string, action PowerAction, state DomainPowerState) PowerResult {
return PowerResult{
UUID: uuid,
Action: action,
State: state,
Active: state.IsActive(),
ObservedAt: time.Now().UTC(),
}
}
// PowerDomain applies one lifecycle action to the in-memory backend and
// returns the state that was immediately observed. It mirrors the real
// adapter's read-back contract while keeping tests deterministic.
func (f *FakeBackend) PowerDomain(ctx context.Context, uuid string, action PowerAction) (PowerResult, error) {
if err := contextErr(ctx); err != nil {
return PowerResult{}, err
}
f.mutationMu.Lock()
defer f.mutationMu.Unlock()
if err := contextErr(ctx); err != nil {
return PowerResult{}, err
}
canonical, err := CanonicalUUID(uuid)
if err != nil {
return PowerResult{}, err
}
normalizedAction, err := ParsePowerAction(string(action))
if err != nil {
return PowerResult{}, err
}
f.mu.Lock()
defer f.mu.Unlock()
if _, exists := f.domains[canonical]; !exists {
return PowerResult{}, fmt.Errorf("%w: %s", ErrDomainNotFound, canonical)
}
current := f.states[canonical]
if current == "" {
// This should only be possible for a manually constructed FakeBackend;
// treating it as shutoff keeps the test backend fail-closed and
// deterministic rather than inventing a running guest.
current = StateShutoff
}
next, err := fakePowerTransition(current, normalizedAction)
if err != nil {
return PowerResult{}, err
}
if err := contextErr(ctx); err != nil {
return PowerResult{}, err
}
f.states[canonical] = next
result := powerResult(canonical, normalizedAction, next)
if !powerActionSatisfied(normalizedAction, next) {
return result, fmt.Errorf("%w: action=%s observed=%s", ErrPowerReadbackMismatch, normalizedAction, next)
}
return result, nil
}
// ReadDomainPowerState returns the current in-memory state without invoking a
// transition. Reconciliation uses this method after an ambiguous response;
// it is deliberately separate from PowerDomain to make accidental replay
// impossible at the interface boundary.
func (f *FakeBackend) ReadDomainPowerState(ctx context.Context, uuid string) (DomainPowerState, error) {
if err := contextErr(ctx); err != nil {
return "", err
}
canonical, err := CanonicalUUID(uuid)
if err != nil {
return "", err
}
f.mu.RLock()
_, exists := f.domains[canonical]
state := f.states[canonical]
f.mu.RUnlock()
if !exists {
return "", fmt.Errorf("%w: %s", ErrDomainNotFound, canonical)
}
if state == "" {
state = StateShutoff
}
if err := contextErr(ctx); err != nil {
return "", err
}
return state, nil
}
func powerOutputTooLarge(data []byte) error {
if len(data) > maxVirshOutput {
return ErrVirshOutputTooLarge
}
return nil
}