Files
Reims-Go/internal/driver/state_table.go

162 lines
4.2 KiB
Go

package driver
import (
"fmt"
"strings"
"sync"
"time"
)
// reportableStates are the states a driver may report for a VM it hosts.
var reportableStates = map[string]bool{
"stopped": true, "starting": true, "running": true,
"stopping": true, "suspended": true, "broken": true,
}
// ReportedState is a VM state a driver pushed to the host.
type ReportedState struct {
Ref VMRef
State string
Ready *bool
Phase string
Endpoints []VMEndpoint
GuestOS *GuestOSInfo
UpdatedAt time.Time
}
// StateTable keeps the latest state each driver reported per VM reference.
// Two drivers can own VMs with the same name; the key includes the driver.
type StateTable struct {
mu sync.RWMutex
entries map[string]ReportedState
now func() time.Time
}
// NewStateTable creates an empty table.
func NewStateTable() *StateTable {
return &StateTable{entries: map[string]ReportedState{}, now: time.Now}
}
// Report validates and stores a driver-reported state.
func (t *StateTable) Report(rep ReportedState) error {
if t == nil {
return fmt.Errorf("state table unavailable")
}
rep.Ref = NewVMRef(rep.Ref.DriverID, rep.Ref.Name)
if rep.Ref.Name == "" {
return fmt.Errorf("reported state needs a VM name")
}
if !reportableStates[strings.ToLower(strings.TrimSpace(rep.State))] {
return fmt.Errorf("reported state %q is not allowed", rep.State)
}
rep.State = strings.ToLower(strings.TrimSpace(rep.State))
if err := ValidateEndpoints(rep.Endpoints); err != nil {
return err
}
if rep.Phase != "" && rep.Phase != PhaseNormal && rep.Phase != PhaseInstaller && rep.Phase != PhaseRecovery {
return fmt.Errorf("reported phase %q is not allowed", rep.Phase)
}
rep.Endpoints = append([]VMEndpoint(nil), rep.Endpoints...)
rep.UpdatedAt = t.now()
t.mu.Lock()
t.entries[foldedRefKey(rep.Ref.DriverID, rep.Ref.Name)] = rep
t.mu.Unlock()
return nil
}
// Get returns the stored report for ref.
func (t *StateTable) Get(ref VMRef) (ReportedState, bool) {
if t == nil {
return ReportedState{}, false
}
t.mu.RLock()
defer t.mu.RUnlock()
rep, ok := t.entries[foldedRefKey(ref.DriverID, ref.Name)]
return rep, ok
}
// Delete drops the report for ref.
func (t *StateTable) Delete(ref VMRef) {
if t == nil {
return
}
t.mu.Lock()
delete(t.entries, foldedRefKey(ref.DriverID, ref.Name))
t.mu.Unlock()
}
// DeleteDriver drops every report of a driver.
func (t *StateTable) DeleteDriver(driverID string) {
if t == nil {
return
}
prefix := strings.ToLower(NewVMRef(driverID, "x").DriverID) + ":"
t.mu.Lock()
for k := range t.entries {
if strings.HasPrefix(k, prefix) {
delete(t.entries, k)
}
}
t.mu.Unlock()
}
// PruneDrivers drops the reports of every driver not in active.
func (t *StateTable) PruneDrivers(active map[string]bool) {
if t == nil {
return
}
t.mu.Lock()
for k, rep := range t.entries {
if !active[rep.Ref.DriverID] {
delete(t.entries, k)
}
}
t.mu.Unlock()
}
// Merge overlays a fresh driver report on vm. A report newer than fetchedAt
// wins over the state the driver returned; an older one only fills fields the
// driver left empty while the states agree. It always keeps the ssh endpoint
// and SSHPort consistent, and is safe on a nil table.
func (t *StateTable) Merge(vm *VMInfo, fetchedAt time.Time) {
if vm == nil {
return
}
if rep, ok := t.Get(vm.Ref()); ok {
if fetchedAt.IsZero() || rep.UpdatedAt.After(fetchedAt) {
vm.State = rep.State
vm.Ready = rep.Ready
if rep.Phase != "" {
vm.Phase = rep.Phase
}
if rep.Endpoints != nil {
vm.Endpoints = append([]VMEndpoint(nil), rep.Endpoints...)
}
if rep.GuestOS != nil {
vm.GuestOS = rep.GuestOS
}
} else if vm.State == rep.State {
if vm.Ready == nil {
vm.Ready = rep.Ready
}
if vm.Phase == "" {
vm.Phase = rep.Phase
}
if len(vm.Endpoints) == 0 && len(rep.Endpoints) > 0 {
vm.Endpoints = append([]VMEndpoint(nil), rep.Endpoints...)
}
if vm.GuestOS == nil {
vm.GuestOS = rep.GuestOS
}
}
}
SyncSSHEndpoint(vm)
}
// NeedsFallback reports whether the driver has not reported ref within
// maxAge, so the host should ask the driver with `driver/show`.
func (t *StateTable) NeedsFallback(ref VMRef, maxAge time.Duration, now time.Time) bool {
rep, ok := t.Get(ref)
return !ok || now.Sub(rep.UpdatedAt) > maxAge
}