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.
virt/agent/operation/journal.go

1217 lines
37 KiB
Go

package operation
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
bolt "go.etcd.io/bbolt"
)
type State string
const (
StateReserved State = "reserved"
StateDispatching State = "dispatching"
StateSucceeded State = "succeeded"
StateFailed State = "failed"
StateUncertain State = "uncertain"
)
const (
ExpectedUpdateSettings = "update-settings"
ExpectedChangeNetwork = "change-network"
ExpectedNetworkState = "network-state"
ExpectedServiceState = "service-state"
ExpectedFirewall = "firewall"
operationDetailRetention = 90 * 24 * time.Hour
)
var (
ErrNotFound = errors.New("operation not found")
ErrFingerprint = errors.New("operation_id payload conflict")
ErrOperationUncertain = errors.New("operation result is uncertain")
ErrBusy = errors.New("operation execution capacity is exhausted")
operationIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{8,80}$`)
hexDigestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
networkSourcePattern = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
causeCodePattern = regexp.MustCompile(`^[a-z][a-z0-9]*(_[a-z0-9]+)*$`)
metadataBucket = []byte("metadata")
operationsBucket = []byte("operations")
inflightBucket = []byte("inflight")
operationExpiryBucket = []byte("operation_expiry")
noncesBucket = []byte("nonces")
nonceExpiryBucket = []byte("nonce_expiry")
schemaVersionKey = []byte("schema_version")
schemaVersion = []byte("2")
)
// ExpectedState is the non-secret, durable evidence contract used after a
// crash. It intentionally has no password, SSH key, token, file path, or raw
// request field. The exact request remains bound separately by Fingerprint.
type ExpectedState struct {
Kind string `json:"kind"`
TransitionID string `json:"transition_id"`
HostnameChanged bool `json:"hostname_changed,omitempty"`
Hostname string `json:"hostname,omitempty"`
RootPasswordChanged bool `json:"root_password_changed,omitempty"`
SSHKeyChanged bool `json:"ssh_key_changed,omitempty"`
NetworkSelector string `json:"network,omitempty"`
NetworkSourceType string `json:"network_source_type,omitempty"`
NetworkSourceName string `json:"network_source_name,omitempty"`
PublicPoolKey string `json:"public_pool_key,omitempty"`
PublicPoolCIDR string `json:"public_pool_cidr,omitempty"`
PublicIPCIDR string `json:"public_ip_cidr,omitempty"`
Gateway string `json:"gateway,omitempty"`
DNSServers []string `json:"dns_servers,omitempty"`
Enabled bool `json:"enabled,omitempty"`
StartIfSuspended bool `json:"start_if_suspended,omitempty"`
FirewallRevision uint64 `json:"firewall_revision,omitempty"`
FirewallDigest string `json:"firewall_digest,omitempty"`
}
type PublicError struct {
Code string `json:"code"`
Message string `json:"message"`
}
type Record struct {
OperationID string `json:"operation_id"`
ResourceID string `json:"resource_id,omitempty"`
Action string `json:"action"`
Fingerprint string `json:"fingerprint"`
Destructive bool `json:"destructive"`
State State `json:"status"`
Result json.RawMessage `json:"result,omitempty"`
Error *PublicError `json:"error,omitempty"`
CauseCode string `json:"cause_code,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Tombstone bool `json:"tombstone,omitempty"`
// ExpectedState is persisted in the private journal but deliberately never
// serialized on the HTTP API.
ExpectedState *ExpectedState `json:"-"`
}
type Spec struct {
OperationID string
ResourceID string
Action string
Fingerprint string
Destructive bool
ExpectedState *ExpectedState
}
type Result struct {
Value json.RawMessage
}
type Resolution struct {
Resolved bool
Succeeded bool
Result json.RawMessage
ErrorCode string
ErrorMessage string
}
type UncertainError struct {
Cause error
}
func (e *UncertainError) Error() string {
if e.Cause == nil {
return ErrOperationUncertain.Error()
}
return fmt.Sprintf("%s: %v", ErrOperationUncertain, e.Cause)
}
func (e *UncertainError) Unwrap() error { return e.Cause }
func MarkUncertain(err error) error { return &UncertainError{Cause: err} }
func IsUncertain(err error) bool {
var target *UncertainError
return errors.As(err, &target) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
type recordAlias Record
type storedRecord struct {
Record recordAlias `json:"record"`
ExpectedState *ExpectedState `json:"expected_state,omitempty"`
}
type resourceLock struct {
semaphore chan struct{}
references int
}
type Journal struct {
path string
db *bolt.DB
clockMu sync.RWMutex
now func() time.Time
resourceMu sync.Mutex
resources map[string]*resourceLock
executionSlots chan struct{}
workerWG sync.WaitGroup
}
const maxConcurrentExecutions = 32
func Open(path string) (*Journal, error) {
if strings.TrimSpace(path) == "" {
return nil, errors.New("journal path is required")
}
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
return nil, fmt.Errorf("create operation journal directory: %w", err)
}
db, err := bolt.Open(path, 0o600, &bolt.Options{Timeout: 2 * time.Second})
if err != nil {
return nil, fmt.Errorf("open operation journal database: %w", err)
}
j := &Journal{
path: path, db: db, now: time.Now, resources: make(map[string]*resourceLock),
executionSlots: make(chan struct{}, maxConcurrentExecutions),
}
if err := j.initialize(); err != nil {
_ = db.Close()
return nil, err
}
return j, nil
}
func (j *Journal) Close() error {
if j == nil || j.db == nil {
return nil
}
return j.db.Close()
}
// Wait blocks until every real mutation and late-result finalizer has stopped.
// Callers must stop API admission before invoking it so no new worker can be
// added concurrently with the wait.
func (j *Journal) Wait(ctx context.Context) error {
done := make(chan struct{})
go func() {
j.workerWG.Wait()
close(done)
}()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// UseNonce uses two Bolt buckets: direct lookup is O(1), while the ordered
// expiry index makes cleanup proportional only to expired entries. It never
// rewrites or decodes the operation history.
func (j *Journal) UseNonce(nonce string, now, expiresAt time.Time) (bool, error) {
if !noncePattern.MatchString(nonce) {
return false, errors.New("invalid nonce")
}
if !expiresAt.After(now) {
return false, errors.New("nonce expiry must be in the future")
}
accepted := false
err := j.db.Update(func(tx *bolt.Tx) error {
nonces := tx.Bucket(noncesBucket)
expiry := tx.Bucket(nonceExpiryBucket)
if nonces == nil || expiry == nil {
return errors.New("nonce buckets are unavailable")
}
if err := pruneExpiredOperationDetails(tx, now); err != nil {
return err
}
pruneExpiredNonces(nonces, expiry, now)
key := []byte(nonce)
if encoded := nonces.Get(key); encoded != nil {
current, err := decodeExpiry(encoded)
if err != nil {
return err
}
if !current.Before(now) {
return nil
}
if err := expiry.Delete(expiryIndexKey(current, nonce)); err != nil {
return err
}
}
encoded := encodeExpiry(expiresAt.UTC())
if err := nonces.Put(key, encoded); err != nil {
return err
}
if err := expiry.Put(expiryIndexKey(expiresAt.UTC(), nonce), nil); err != nil {
return err
}
accepted = true
return nil
})
return accepted, err
}
func Fingerprint(method, target string, body []byte) string {
sum := sha256.Sum256([]byte(strings.ToUpper(method) + "\n" + target + "\n" + string(body)))
return hex.EncodeToString(sum[:])
}
func (j *Journal) SetClockForTesting(now func() time.Time) {
j.clockMu.Lock()
defer j.clockMu.Unlock()
j.now = now
}
func (j *Journal) currentTime() time.Time {
j.clockMu.RLock()
defer j.clockMu.RUnlock()
return j.now().UTC()
}
func (j *Journal) Get(operationID string) (Record, error) {
var record Record
err := j.db.View(func(tx *bolt.Tx) error {
bucket := tx.Bucket(operationsBucket)
if bucket == nil {
return errors.New("operation bucket is unavailable")
}
value := bucket.Get([]byte(operationID))
if value == nil {
return ErrNotFound
}
decoded, err := decodeRecord(value)
if err != nil {
return err
}
record = decoded
return nil
})
return cloneRecord(record), err
}
// Reserve durably binds operation_id to one exact request fingerprint and its
// non-secret reconciliation descriptor. Records are never deleted, so an old
// destructive operation_id can never become valid again after housekeeping.
func (j *Journal) Reserve(spec Spec) (Record, bool, error) {
if err := validateSpec(spec); err != nil {
return Record{}, false, err
}
var record Record
existed := false
err := j.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(operationsBucket)
inflight := tx.Bucket(inflightBucket)
if bucket == nil || inflight == nil {
return errors.New("operation buckets are unavailable")
}
if err := pruneExpiredOperationDetails(tx, j.currentTime()); err != nil {
return err
}
if value := bucket.Get([]byte(spec.OperationID)); value != nil {
existing, err := decodeRecord(value)
if err != nil {
return err
}
existed = true
if existing.Fingerprint != spec.Fingerprint || existing.Action != spec.Action || existing.ResourceID != spec.ResourceID {
return ErrFingerprint
}
record = existing
return nil
}
now := j.currentTime()
record = Record{
OperationID: spec.OperationID, ResourceID: spec.ResourceID,
Action: spec.Action, Fingerprint: spec.Fingerprint,
Destructive: spec.Destructive, State: StateReserved,
CreatedAt: now, UpdatedAt: now, ExpectedState: cloneExpectedState(spec.ExpectedState),
}
if err := putRecord(bucket, record); err != nil {
return err
}
return inflight.Put([]byte(record.OperationID), nil)
})
return cloneRecord(record), existed, err
}
// Execute persists the dispatch boundary before invoking fn. A caller timeout
// after that boundary becomes durable uncertainty; the worker retains the
// per-resource lease and records a late definitive result when one arrives.
func (j *Journal) Execute(ctx context.Context, spec Spec, fn func(context.Context) (json.RawMessage, error)) (Record, bool, error) {
record, existed, err := j.Reserve(spec)
if err != nil {
return Record{}, existed, err
}
if existed && record.State != StateReserved {
if record.State == StateUncertain || record.State == StateDispatching {
return record, true, ErrOperationUncertain
}
return record, true, nil
}
release, err := j.acquire(ctx, lockKey(spec))
if err != nil {
failed, failErr := j.failNotDispatchedIfReserved(spec.OperationID)
if failErr != nil {
return failed, existed, failErr
}
return failed, existed, err
}
releaseExecution, err := j.acquireExecution(ctx)
if err != nil {
release()
failed, failErr := j.failNotDispatchedIfReserved(spec.OperationID)
if failErr != nil {
return failed, existed, failErr
}
return failed, existed, err
}
record, err = j.markDispatching(spec.OperationID)
if err != nil {
releaseExecution()
release()
return record, existed, err
}
if record.State != StateDispatching {
releaseExecution()
release()
if record.State == StateUncertain {
return record, true, ErrOperationUncertain
}
return record, true, nil
}
type outcome struct {
result json.RawMessage
err error
}
done := make(chan outcome, 1)
mutationContext := context.WithValue(ctx, expectedStateContextKey{}, cloneExpectedState(record.ExpectedState))
j.workerWG.Add(1)
go func() {
defer j.workerWG.Done()
result, callErr := fn(mutationContext)
done <- outcome{result: result, err: callErr}
}()
select {
case completed := <-done:
terminal, persistErr := j.finish(spec.OperationID, completed.result, completed.err)
release()
releaseExecution()
if persistErr != nil {
return terminal, existed, persistErr
}
return terminal, existed, completed.err
case <-ctx.Done():
uncertain, persistErr := j.markUncertain(spec.OperationID, ctx.Err())
j.workerWG.Add(1)
go func() {
defer j.workerWG.Done()
completed := <-done
_, _ = j.finishIfUncertain(spec.OperationID, completed.result, completed.err)
release()
releaseExecution()
}()
if persistErr != nil {
return uncertain, existed, persistErr
}
return uncertain, existed, MarkUncertain(ctx.Err())
}
}
// ExecuteBackground persists the dispatch boundary and starts one bounded,
// tracked worker before returning. A nil done channel means an existing
// non-reserved record was replayed and no new call was started.
func (j *Journal) ExecuteBackground(
dispatchCtx, workerCtx context.Context,
spec Spec,
fn func(context.Context) (json.RawMessage, error),
) (Record, bool, <-chan struct{}, error) {
record, existed, err := j.Reserve(spec)
if err != nil {
return Record{}, existed, nil, err
}
if existed && record.State != StateReserved {
return record, true, nil, nil
}
release, err := j.acquire(dispatchCtx, lockKey(spec))
if err != nil {
failed, failErr := j.failNotDispatchedIfReserved(spec.OperationID)
if failErr != nil {
return failed, existed, nil, failErr
}
return failed, existed, nil, err
}
releaseExecution, err := j.acquireExecution(dispatchCtx)
if err != nil {
release()
failed, failErr := j.failNotDispatchedIfReserved(spec.OperationID)
if failErr != nil {
return failed, existed, nil, failErr
}
return failed, existed, nil, err
}
record, err = j.markDispatching(spec.OperationID)
if err != nil {
releaseExecution()
release()
return record, existed, nil, err
}
if record.State != StateDispatching {
releaseExecution()
release()
return record, true, nil, nil
}
type outcome struct {
result json.RawMessage
err error
}
callDone := make(chan outcome, 1)
done := make(chan struct{})
mutationContext := context.WithValue(workerCtx, expectedStateContextKey{}, cloneExpectedState(record.ExpectedState))
j.workerWG.Add(2)
go func() {
defer j.workerWG.Done()
result, callErr := fn(mutationContext)
callDone <- outcome{result: result, err: callErr}
}()
go func() {
defer j.workerWG.Done()
defer close(done)
defer release()
defer releaseExecution()
select {
case completed := <-callDone:
_, _ = j.finishIfUncertain(spec.OperationID, completed.result, completed.err)
case <-workerCtx.Done():
_, _ = j.markUncertain(spec.OperationID, workerCtx.Err())
completed := <-callDone
_, _ = j.finishIfUncertain(spec.OperationID, completed.result, completed.err)
}
}()
return record, existed, done, nil
}
// ExpectedStateFromContext returns the descriptor atomically persisted with
// the dispatch record. Mutation implementations use it to write a matching
// host-side transition marker before reporting success.
func ExpectedStateFromContext(ctx context.Context) (ExpectedState, bool) {
expected, ok := ctx.Value(expectedStateContextKey{}).(*ExpectedState)
if !ok || expected == nil {
return ExpectedState{}, false
}
return *cloneExpectedState(expected), true
}
// Reconcile never resubmits the original API request. The hypervisor callback
// may inspect evidence and continue an idempotent target-state or cleanup tail
// whose targets are durably bound to this exact operation. Unresolved evidence
// leaves the operation uncertain.
func (j *Journal) Reconcile(ctx context.Context, operationID string, fn func(context.Context, Record) (Resolution, error)) (Record, error) {
record, err := j.Get(operationID)
if err != nil {
return Record{}, err
}
if !recordCanReconcile(record) {
return record, nil
}
release, err := j.acquire(ctx, lockKeyForRecord(record))
if err != nil {
return record, err
}
defer release()
record, err = j.Get(operationID)
if err != nil || !recordCanReconcile(record) {
return record, err
}
cleanupRetry := succeededCleanupCanReconcile(record)
resolution, inspectErr := fn(ctx, record)
if inspectErr != nil || !resolution.Resolved {
// The reinstall itself is already committed and publicly succeeded.
// A transient cleanup inspection failure must not erase that durable
// result or turn a completed reinstall into an uncertain mutation. By
// retaining cleanup_pending, a later reconcile call can safely retry the
// idempotent cleanup tail with this same operation ID.
if cleanupRetry {
if inspectErr != nil {
return record, inspectErr
}
return record, ErrOperationUncertain
}
if inspectErr != nil {
updated, persistErr := j.markUncertain(operationID, inspectErr)
if persistErr != nil {
return updated, persistErr
}
return updated, inspectErr
}
if record.Action == "create-vm" {
updated, persistErr := j.markUncertain(operationID, nil)
if persistErr != nil {
return updated, persistErr
}
return updated, ErrOperationUncertain
}
return record, ErrOperationUncertain
}
if resolution.Succeeded {
return j.finish(operationID, resolution.Result, nil)
}
if cleanupRetry {
return record, ErrOperationUncertain
}
code := resolution.ErrorCode
if code == "" {
code = "operation_failed"
}
message := resolution.ErrorMessage
if message == "" {
message = "host evidence confirms the operation failed"
}
if evidence, ok := safeFailureEvidence(record.Action, code, resolution.Result); ok {
return j.finishWithPublicErrorAndResult(operationID, code, message, evidence)
}
// A create failure is terminal only when read-only host evidence proves
// both the domain and every panel-managed artifact are absent. Any other
// failure resolution can describe a partial create and must stay uncertain;
// it never authorizes replaying the original create call.
if record.Action == "create-vm" {
updated, persistErr := j.markUncertain(operationID, nil)
if persistErr != nil {
return updated, persistErr
}
return updated, ErrOperationUncertain
}
return j.finishWithPublicError(operationID, code, message)
}
func recordCanReconcile(record Record) bool {
if record.State == StateUncertain || record.State == StateDispatching {
return true
}
if succeededCleanupCanReconcile(record) {
return true
}
if record.State != StateFailed || record.Action != "create-vm" {
return false
}
code := ""
if record.Error != nil {
code = record.Error.Code
}
_, confirmedAbsent := safeFailureEvidence(record.Action, code, record.Result)
return !confirmedAbsent
}
// Older Agents could finalize a committed reinstall while its deterministic
// old-root cleanup was still pending. Permit the same operation's reconcile
// endpoint to replace that result after the cleanup tail is confirmed.
func succeededCleanupCanReconcile(record Record) bool {
if record.State != StateSucceeded || record.Action != "reinstall-vm" || len(record.Result) == 0 {
return false
}
var result map[string]json.RawMessage
if json.Unmarshal(record.Result, &result) != nil {
return false
}
var pending bool
return json.Unmarshal(result["cleanup_pending"], &pending) == nil && pending
}
func safeFailureEvidence(action, code string, candidate json.RawMessage) (json.RawMessage, bool) {
if action != "create-vm" ||
(code != "creation_absent" && code != "operation_not_dispatched") ||
len(candidate) == 0 {
return nil, false
}
var object map[string]json.RawMessage
expectedFields := 2
if code == "operation_not_dispatched" {
expectedFields = 3
}
if err := json.Unmarshal(candidate, &object); err != nil || len(object) != expectedFields {
return nil, false
}
if code == "operation_not_dispatched" {
var notDispatched bool
if err := json.Unmarshal(object["not_dispatched"], &notDispatched); err != nil || !notDispatched {
return nil, false
}
}
var creationAbsent, artifactsAbsent bool
if err := json.Unmarshal(object["creation_absent"], &creationAbsent); err != nil || !creationAbsent {
return nil, false
}
if err := json.Unmarshal(object["managed_artifacts_absent"], &artifactsAbsent); err != nil || !artifactsAbsent {
return nil, false
}
if code == "operation_not_dispatched" {
return json.RawMessage(`{"not_dispatched":true,"creation_absent":true,"managed_artifacts_absent":true}`), true
}
return json.RawMessage(`{"creation_absent":true,"managed_artifacts_absent":true}`), true
}
func (j *Journal) initialize() error {
return j.db.Update(func(tx *bolt.Tx) error {
metadata, err := tx.CreateBucketIfNotExists(metadataBucket)
if err != nil {
return fmt.Errorf("create journal metadata bucket: %w", err)
}
if current := metadata.Get(schemaVersionKey); current == nil {
if err := metadata.Put(schemaVersionKey, schemaVersion); err != nil {
return err
}
} else if string(current) != string(schemaVersion) {
return fmt.Errorf("unsupported operation journal schema %q", current)
}
operations, err := tx.CreateBucketIfNotExists(operationsBucket)
if err != nil {
return fmt.Errorf("create operation bucket: %w", err)
}
if _, err := tx.CreateBucketIfNotExists(noncesBucket); err != nil {
return fmt.Errorf("create nonce bucket: %w", err)
}
if _, err := tx.CreateBucketIfNotExists(nonceExpiryBucket); err != nil {
return fmt.Errorf("create nonce expiry bucket: %w", err)
}
operationExpiry, err := tx.CreateBucketIfNotExists(operationExpiryBucket)
if err != nil {
return fmt.Errorf("create operation expiry bucket: %w", err)
}
inflight, err := tx.CreateBucketIfNotExists(inflightBucket)
if err != nil {
return fmt.Errorf("create inflight operation bucket: %w", err)
}
now := j.currentTime()
var recovered []Record
var stale [][]byte
if err := inflight.ForEach(func(key, _ []byte) error {
value := operations.Get(key)
if value == nil {
stale = append(stale, append([]byte(nil), key...))
return nil
}
record, err := decodeRecord(value)
if err != nil {
return fmt.Errorf("decode operation %q: %w", key, err)
}
switch record.State {
case StateReserved:
record.State = StateFailed
record.Result = notDispatchedEvidence(record.Action)
record.Error = &PublicError{Code: "operation_not_dispatched", Message: "agent restarted before the dispatch boundary"}
case StateDispatching:
record.State = StateUncertain
record.Result = nil
record.Error = &PublicError{Code: "result_uncertain", Message: "agent restarted after dispatch; reconciliation is required"}
default:
stale = append(stale, append([]byte(nil), key...))
return nil
}
record.UpdatedAt = now
recovered = append(recovered, record)
return nil
}); err != nil {
return err
}
for _, record := range recovered {
if err := putRecord(operations, record); err != nil {
return err
}
if terminalState(record.State) {
if err := operationExpiry.Put(operationExpiryKey(record.UpdatedAt, record.OperationID), nil); err != nil {
return err
}
}
if err := inflight.Delete([]byte(record.OperationID)); err != nil {
return err
}
}
for _, key := range stale {
if err := inflight.Delete(key); err != nil {
return err
}
}
return pruneExpiredOperationDetails(tx, now)
})
}
func (j *Journal) markDispatching(operationID string) (Record, error) {
return j.updateRecord(operationID, func(record *Record) {
if record.State == StateReserved {
record.State = StateDispatching
record.UpdatedAt = j.currentTime()
}
})
}
func (j *Journal) finish(operationID string, result json.RawMessage, callErr error) (Record, error) {
if IsUncertain(callErr) {
return j.markUncertain(operationID, callErr)
}
if callErr != nil {
code := "backend_error"
message := callErr.Error()
var public interface {
PublicCode() string
PublicMessage() string
}
if errors.As(callErr, &public) {
if public.PublicCode() != "" {
code = public.PublicCode()
}
if public.PublicMessage() != "" {
message = public.PublicMessage()
}
}
return j.finishWithCause(operationID, code, message, nil, code)
}
return j.updateRecord(operationID, func(record *Record) {
record.State = StateSucceeded
record.Result = append(json.RawMessage(nil), result...)
record.Error = nil
record.CauseCode = ""
record.UpdatedAt = j.currentTime()
})
}
func (j *Journal) finishIfUncertain(operationID string, result json.RawMessage, callErr error) (Record, error) {
record, err := j.Get(operationID)
if err != nil {
return Record{}, err
}
if record.State != StateUncertain && record.State != StateDispatching {
return record, nil
}
return j.finish(operationID, result, callErr)
}
func (j *Journal) finishWithPublicError(operationID, code, message string) (Record, error) {
return j.finishWithPublicErrorAndResult(operationID, code, message, nil)
}
func (j *Journal) finishWithPublicErrorAndResult(operationID, code, message string, result json.RawMessage) (Record, error) {
return j.finishWithCause(operationID, code, message, result, "")
}
func (j *Journal) finishWithCause(operationID, code, message string, result json.RawMessage, causeCode string) (Record, error) {
return j.updateRecord(operationID, func(record *Record) {
record.State = StateFailed
record.Result = append(json.RawMessage(nil), result...)
record.Error = &PublicError{Code: code, Message: message}
preserveCauseCode(record, causeCode)
record.UpdatedAt = j.currentTime()
})
}
func (j *Journal) failNotDispatchedIfReserved(operationID string) (Record, error) {
return j.updateRecord(operationID, func(record *Record) {
if record.State != StateReserved {
return
}
record.State = StateFailed
record.Result = notDispatchedEvidence(record.Action)
record.Error = &PublicError{Code: "operation_not_dispatched", Message: "operation did not cross the dispatch boundary"}
record.UpdatedAt = j.currentTime()
})
}
// FailNotDispatched terminally records that a reserved operation never
// crossed the dispatch boundary. It is safe for admission failures only.
func (j *Journal) FailNotDispatched(operationID string) (Record, error) {
return j.failNotDispatchedIfReserved(operationID)
}
func notDispatchedEvidence(action string) json.RawMessage {
if action == "create-vm" {
return json.RawMessage(`{"not_dispatched":true,"creation_absent":true,"managed_artifacts_absent":true}`)
}
return json.RawMessage(`{"not_dispatched":true}`)
}
func (j *Journal) markUncertain(operationID string, cause error) (Record, error) {
return j.updateRecord(operationID, func(record *Record) {
message := "operation crossed the dispatch boundary and requires reconciliation"
if summary := publicMessageFromError(cause); summary != "" {
message += ": " + summary
}
record.State = StateUncertain
record.Result = nil
record.Error = &PublicError{Code: "result_uncertain", Message: message}
preserveCauseCode(record, publicCodeFromError(cause))
record.UpdatedAt = j.currentTime()
})
}
func preserveCauseCode(record *Record, code string) {
if record.CauseCode == "" && validCauseCode(code) {
record.CauseCode = code
}
}
func validCauseCode(code string) bool {
return len(code) <= 64 && causeCodePattern.MatchString(code)
}
func publicCodeFromError(err error) string {
if err == nil {
return ""
}
var public interface{ PublicCode() string }
if !errors.As(err, &public) {
return ""
}
code := public.PublicCode()
if !validCauseCode(code) {
return ""
}
return code
}
func publicMessageFromError(err error) string {
if err == nil {
return ""
}
var public interface{ PublicMessage() string }
if !errors.As(err, &public) {
return ""
}
return public.PublicMessage()
}
func (j *Journal) updateRecord(operationID string, mutate func(*Record)) (Record, error) {
var result Record
err := j.db.Update(func(tx *bolt.Tx) error {
bucket := tx.Bucket(operationsBucket)
inflight := tx.Bucket(inflightBucket)
if bucket == nil || inflight == nil {
return errors.New("operation buckets are unavailable")
}
value := bucket.Get([]byte(operationID))
if value == nil {
return ErrNotFound
}
record, err := decodeRecord(value)
if err != nil {
return err
}
mutate(&record)
if err := putRecord(bucket, record); err != nil {
return err
}
switch record.State {
case StateReserved, StateDispatching:
if err := inflight.Put([]byte(record.OperationID), nil); err != nil {
return err
}
default:
if err := inflight.Delete([]byte(record.OperationID)); err != nil {
return err
}
}
if terminalState(record.State) && !record.Tombstone {
expiry := tx.Bucket(operationExpiryBucket)
if expiry == nil {
return errors.New("operation expiry bucket is unavailable")
}
if err := expiry.Put(operationExpiryKey(record.UpdatedAt, record.OperationID), nil); err != nil {
return err
}
}
result = record
return nil
})
return cloneRecord(result), err
}
func (j *Journal) acquire(ctx context.Context, key string) (func(), error) {
j.resourceMu.Lock()
lock, ok := j.resources[key]
if !ok {
lock = &resourceLock{semaphore: make(chan struct{}, 1)}
j.resources[key] = lock
}
lock.references++
j.resourceMu.Unlock()
select {
case lock.semaphore <- struct{}{}:
var once sync.Once
return func() {
once.Do(func() {
<-lock.semaphore
j.releaseResourceReference(key, lock)
})
}, nil
case <-ctx.Done():
j.releaseResourceReference(key, lock)
return nil, ctx.Err()
}
}
func (j *Journal) acquireExecution(_ context.Context) (func(), error) {
select {
case j.executionSlots <- struct{}{}:
var once sync.Once
return func() {
once.Do(func() { <-j.executionSlots })
}, nil
default:
return nil, ErrBusy
}
}
func (j *Journal) releaseResourceReference(key string, lock *resourceLock) {
j.resourceMu.Lock()
defer j.resourceMu.Unlock()
lock.references--
if lock.references == 0 && len(lock.semaphore) == 0 && j.resources[key] == lock {
delete(j.resources, key)
}
}
func lockKey(spec Spec) string {
if spec.ResourceID != "" {
return spec.ResourceID
}
return "operation:" + spec.OperationID
}
func lockKeyForRecord(record Record) string {
return lockKey(Spec{OperationID: record.OperationID, ResourceID: record.ResourceID})
}
func validateSpec(spec Spec) error {
if !operationIDPattern.MatchString(spec.OperationID) {
return errors.New("operation_id must be 8-80 URL-safe characters")
}
if strings.TrimSpace(spec.Action) == "" || len(spec.Action) > 128 {
return errors.New("action must contain 1-128 characters")
}
if len(spec.ResourceID) > 255 {
return errors.New("resource_id is too long")
}
if !hexDigestPattern.MatchString(spec.Fingerprint) {
return errors.New("fingerprint must be lowercase SHA-256 hex")
}
if spec.ExpectedState != nil {
if err := validateExpectedState(spec.Action, spec.OperationID, *spec.ExpectedState); err != nil {
return err
}
}
return nil
}
func validateExpectedState(action, operationID string, expected ExpectedState) error {
if expected.TransitionID != operationID {
return errors.New("expected state transition_id must match operation_id")
}
if len(expected.Hostname) > 253 || len(expected.NetworkSelector) > 128 || len(expected.NetworkSourceType) > 16 || len(expected.NetworkSourceName) > 128 || len(expected.PublicPoolKey) > 128 ||
len(expected.PublicPoolCIDR) > 64 || len(expected.PublicIPCIDR) > 64 || len(expected.Gateway) > 64 || len(expected.DNSServers) > 4 {
return errors.New("expected state contains an oversized value")
}
values := []string{expected.Hostname, expected.NetworkSelector, expected.NetworkSourceType, expected.NetworkSourceName, expected.PublicPoolKey, expected.PublicPoolCIDR, expected.PublicIPCIDR, expected.Gateway}
values = append(values, expected.DNSServers...)
for _, value := range values {
if strings.ContainsRune(value, 0) {
return errors.New("expected state contains NUL")
}
}
switch expected.Kind {
case ExpectedUpdateSettings:
if action != "update-settings" || (!expected.HostnameChanged && !expected.RootPasswordChanged && !expected.SSHKeyChanged) {
return errors.New("invalid update-settings expected state")
}
case ExpectedChangeNetwork:
if action != "change-network" || expected.NetworkSelector == "" || expected.PublicPoolKey == "" || expected.PublicPoolCIDR == "" ||
expected.PublicIPCIDR == "" || expected.Gateway == "" || len(expected.DNSServers) == 0 ||
(expected.NetworkSourceType != "bridge" && expected.NetworkSourceType != "network") || !networkSourcePattern.MatchString(expected.NetworkSourceName) {
return errors.New("invalid change-network expected state")
}
case ExpectedNetworkState:
if (action != "network-suspend" && action != "network-resume") || expected.Enabled != (action == "network-resume") {
return errors.New("invalid network-state expected state")
}
case ExpectedServiceState:
if (action != "service-suspend" && action != "service-resume") || expected.Enabled != (action == "service-resume") || (!expected.Enabled && expected.StartIfSuspended) {
return errors.New("invalid service-state expected state")
}
case ExpectedFirewall:
if action != "apply-firewall" || expected.FirewallRevision == 0 || !hexDigestPattern.MatchString(expected.FirewallDigest) {
return errors.New("invalid firewall expected state")
}
default:
return errors.New("unsupported expected state kind")
}
return nil
}
func validateRecord(record Record) error {
if err := validateSpec(Spec{
OperationID: record.OperationID, ResourceID: record.ResourceID,
Action: record.Action, Fingerprint: record.Fingerprint, ExpectedState: record.ExpectedState,
}); err != nil {
return err
}
switch record.State {
case StateReserved, StateDispatching, StateSucceeded, StateFailed, StateUncertain:
default:
return fmt.Errorf("invalid state %q", record.State)
}
if record.CauseCode != "" && !validCauseCode(record.CauseCode) {
return errors.New("invalid operation cause_code")
}
return nil
}
func putRecord(bucket *bolt.Bucket, record Record) error {
if err := validateRecord(record); err != nil {
return err
}
encoded, err := json.Marshal(storedRecord{Record: recordAlias(record), ExpectedState: cloneExpectedState(record.ExpectedState)})
if err != nil {
return fmt.Errorf("encode operation record: %w", err)
}
return bucket.Put([]byte(record.OperationID), encoded)
}
func decodeRecord(encoded []byte) (Record, error) {
var stored storedRecord
if err := json.Unmarshal(encoded, &stored); err != nil {
return Record{}, fmt.Errorf("decode operation record: %w", err)
}
record := Record(stored.Record)
record.ExpectedState = cloneExpectedState(stored.ExpectedState)
if err := validateRecord(record); err != nil {
return Record{}, err
}
return record, nil
}
func cloneRecord(record Record) Record {
copyRecord := record
copyRecord.Result = append(json.RawMessage(nil), record.Result...)
copyRecord.ExpectedState = cloneExpectedState(record.ExpectedState)
if record.Error != nil {
copyError := *record.Error
copyRecord.Error = &copyError
}
return copyRecord
}
func cloneExpectedState(expected *ExpectedState) *ExpectedState {
if expected == nil {
return nil
}
copyExpected := *expected
copyExpected.DNSServers = append([]string(nil), expected.DNSServers...)
return &copyExpected
}
func encodeExpiry(value time.Time) []byte {
encoded := make([]byte, 8)
binary.BigEndian.PutUint64(encoded, uint64(value.UnixNano()))
return encoded
}
func decodeExpiry(encoded []byte) (time.Time, error) {
if len(encoded) != 8 {
return time.Time{}, errors.New("invalid nonce expiry record")
}
return time.Unix(0, int64(binary.BigEndian.Uint64(encoded))).UTC(), nil
}
func expiryIndexKey(expiresAt time.Time, nonce string) []byte {
result := make([]byte, 8+len(nonce))
copy(result, encodeExpiry(expiresAt))
copy(result[8:], nonce)
return result
}
func operationExpiryKey(terminalAt time.Time, operationID string) []byte {
return expiryIndexKey(terminalAt, operationID)
}
func terminalState(state State) bool {
return state == StateSucceeded || state == StateFailed
}
func pruneExpiredOperationDetails(tx *bolt.Tx, now time.Time) error {
operations := tx.Bucket(operationsBucket)
expiry := tx.Bucket(operationExpiryBucket)
if operations == nil || expiry == nil {
return errors.New("operation retention buckets are unavailable")
}
cutoff := now.Add(-operationDetailRetention).UnixNano()
cursor := expiry.Cursor()
for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() {
if len(key) < 9 || int64(binary.BigEndian.Uint64(key[:8])) > cutoff {
break
}
operationID := string(key[8:])
encoded := operations.Get([]byte(operationID))
if encoded != nil {
record, err := decodeRecord(encoded)
if err != nil {
return err
}
indexedAt := int64(binary.BigEndian.Uint64(key[:8]))
if terminalState(record.State) && !record.Tombstone && record.UpdatedAt.UnixNano() == indexedAt {
record.Tombstone = true
record.Result = nil
record.ExpectedState = nil
if record.Error != nil {
record.Error = &PublicError{Code: record.Error.Code, Message: "operation details expired; operation_id remains permanently reserved"}
}
if err := putRecord(operations, record); err != nil {
return err
}
}
}
if err := cursor.Delete(); err != nil {
return err
}
}
return nil
}
func pruneExpiredNonces(nonces, expiry *bolt.Bucket, now time.Time) {
cursor := expiry.Cursor()
for key, _ := cursor.First(); key != nil; key, _ = cursor.Next() {
if len(key) < 9 || int64(binary.BigEndian.Uint64(key[:8])) >= now.UnixNano() {
break
}
nonce := key[8:]
if encoded := nonces.Get(nonce); encoded != nil && len(encoded) == 8 && string(encoded) == string(key[:8]) {
_ = nonces.Delete(nonce)
}
_ = cursor.Delete()
}
}
type expectedStateContextKey struct{}