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.
419 lines
12 KiB
Go
419 lines
12 KiB
Go
package update
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type Job struct {
|
|
ID string `json:"id"`
|
|
Status string `json:"status"`
|
|
Checkpoint string `json:"checkpoint"`
|
|
ExpectedCurrentCommit string `json:"expected_current_commit"`
|
|
ExpectedRemoteCommit string `json:"expected_remote_commit"`
|
|
PreviousCommit string `json:"previous_commit,omitempty"`
|
|
AppliedCommit string `json:"applied_commit,omitempty"`
|
|
ErrorCode string `json:"error_code,omitempty"`
|
|
Resolution string `json:"resolution,omitempty"`
|
|
ResolutionEvidence string `json:"resolution_evidence,omitempty"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
type diskState struct {
|
|
Version int `json:"version"`
|
|
AccessToken string `json:"access_token,omitempty"`
|
|
Maintenance bool `json:"maintenance_lock"`
|
|
Jobs map[string]Job `json:"jobs"`
|
|
Nonces map[string]time.Time `json:"nonces"`
|
|
}
|
|
|
|
type StateStore struct {
|
|
path string
|
|
now func() time.Time
|
|
mu sync.Mutex
|
|
data diskState
|
|
}
|
|
|
|
const maxStateBytes = 8 << 20
|
|
|
|
var (
|
|
stateNoncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
|
|
stateCheckpointPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,63}$`)
|
|
)
|
|
|
|
func OpenState(path string) (*StateStore, error) {
|
|
store := &StateStore{path: path, now: time.Now, data: diskState{Version: 1, Jobs: map[string]Job{}, Nonces: map[string]time.Time{}}}
|
|
if err := store.load(); err != nil {
|
|
return nil, err
|
|
}
|
|
return store, nil
|
|
}
|
|
|
|
// OpenConfiguredState verifies that the fixed runtime directories do not
|
|
// escape the checkout through symlinks before creating or opening state.
|
|
func OpenConfiguredState(config Config) (*StateStore, error) {
|
|
if err := config.Validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
repository, err := filepath.EvalSymlinks(config.RepositoryDir)
|
|
if err != nil {
|
|
return nil, errors.New("repository directory is unavailable")
|
|
}
|
|
runtimePath := filepath.Join(config.RepositoryDir, "runtime")
|
|
if err := os.Mkdir(runtimePath, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
|
|
return nil, fmt.Errorf("create runtime directory: %w", err)
|
|
}
|
|
runtimeResolved, err := filepath.EvalSymlinks(runtimePath)
|
|
if err != nil || !pathWithin(repository, runtimeResolved) {
|
|
return nil, errors.New("runtime directory escapes the repository")
|
|
}
|
|
updatePath := filepath.Join(runtimePath, "update")
|
|
if err := os.Mkdir(updatePath, 0o700); err != nil && !errors.Is(err, os.ErrExist) {
|
|
return nil, fmt.Errorf("create update state directory: %w", err)
|
|
}
|
|
updateResolved, err := filepath.EvalSymlinks(updatePath)
|
|
if err != nil || !pathWithin(runtimeResolved, updateResolved) {
|
|
return nil, errors.New("update state directory escapes runtime")
|
|
}
|
|
if info, err := os.Lstat(config.StatePath); err == nil {
|
|
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() {
|
|
return nil, errors.New("update state path must be a regular file")
|
|
}
|
|
} else if !errors.Is(err, os.ErrNotExist) {
|
|
return nil, fmt.Errorf("inspect update state path: %w", err)
|
|
}
|
|
return OpenState(config.StatePath)
|
|
}
|
|
|
|
func (s *StateStore) SetClockForTesting(now func() time.Time) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.now = now
|
|
}
|
|
|
|
func (s *StateStore) load() error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
file, err := os.Open(s.path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return s.persistLocked()
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("open update state: %w", err)
|
|
}
|
|
defer file.Close()
|
|
raw, err := io.ReadAll(io.LimitReader(file, maxStateBytes+1))
|
|
if err != nil {
|
|
return fmt.Errorf("read update state: %w", err)
|
|
}
|
|
if len(raw) > maxStateBytes {
|
|
return errors.New("update state exceeds 8388608 bytes")
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewReader(raw))
|
|
decoder.DisallowUnknownFields()
|
|
var loaded diskState
|
|
if err := decoder.Decode(&loaded); err != nil {
|
|
return fmt.Errorf("decode update state: %w", err)
|
|
}
|
|
if err := requireEOF(decoder); err != nil {
|
|
return fmt.Errorf("decode update state: %w", err)
|
|
}
|
|
if err := validateDiskState(loaded); err != nil {
|
|
return err
|
|
}
|
|
now := s.now().UTC()
|
|
changed := false
|
|
for id, job := range loaded.Jobs {
|
|
if job.Status == "queued" || job.Status == "running" {
|
|
job.Status = "manual_intervention"
|
|
job.ErrorCode = "interrupted_update_requires_reconciliation"
|
|
job.UpdatedAt = now
|
|
loaded.Jobs[id] = job
|
|
loaded.Maintenance = true
|
|
changed = true
|
|
}
|
|
}
|
|
s.data = loaded
|
|
if changed {
|
|
return s.persistLocked()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validateDiskState(state diskState) error {
|
|
if state.Version != 1 || state.Jobs == nil || state.Nonces == nil {
|
|
return errors.New("update state has an unsupported or incomplete format")
|
|
}
|
|
if state.AccessToken != "" && !validAccessToken(state.AccessToken) {
|
|
return errors.New("update state contains an invalid access token")
|
|
}
|
|
if len(state.Jobs) > 10_000 || len(state.Nonces) > 100_000 {
|
|
return errors.New("update state exceeds its safe entry limit")
|
|
}
|
|
hasManual := false
|
|
for id, job := range state.Jobs {
|
|
if id != job.ID || !jobIDPattern.MatchString(id) || !commitPattern.MatchString(job.ExpectedCurrentCommit) ||
|
|
!commitPattern.MatchString(job.ExpectedRemoteCommit) || !stateCheckpointPattern.MatchString(job.Checkpoint) ||
|
|
job.CreatedAt.IsZero() || job.UpdatedAt.IsZero() {
|
|
return errors.New("update state contains an invalid job")
|
|
}
|
|
switch job.Status {
|
|
case "queued", "running", "succeeded", "failed":
|
|
case "manual_intervention":
|
|
hasManual = true
|
|
case "resolved":
|
|
if (job.Resolution != "completed" && job.Resolution != "rolled_back") || !validEvidence(job.ResolutionEvidence) {
|
|
return errors.New("update state contains an invalid resolution")
|
|
}
|
|
default:
|
|
return errors.New("update state contains an unknown job status")
|
|
}
|
|
}
|
|
if state.Maintenance != hasManual {
|
|
return errors.New("update state maintenance lock is inconsistent")
|
|
}
|
|
for nonce, expiry := range state.Nonces {
|
|
if !stateNoncePattern.MatchString(nonce) || expiry.IsZero() {
|
|
return errors.New("update state contains an invalid nonce")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *StateStore) UseNonce(nonce string, now, expiresAt time.Time) (bool, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
for value, expiry := range s.data.Nonces {
|
|
if !expiry.After(now) {
|
|
delete(s.data.Nonces, value)
|
|
}
|
|
}
|
|
if expiry, exists := s.data.Nonces[nonce]; exists && expiry.After(now) {
|
|
return false, nil
|
|
}
|
|
s.data.Nonces[nonce] = expiresAt
|
|
if err := s.persistLocked(); err != nil {
|
|
delete(s.data.Nonces, nonce)
|
|
return false, err
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
func (s *StateStore) TokenConfigured() bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.data.AccessToken != ""
|
|
}
|
|
|
|
func (s *StateStore) AccessToken() string {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.data.AccessToken
|
|
}
|
|
|
|
func (s *StateStore) SetAccessToken(token string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
old := s.data.AccessToken
|
|
s.data.AccessToken = token
|
|
if err := s.persistLocked(); err != nil {
|
|
s.data.AccessToken = old
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *StateStore) CreateJob(job Job) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if s.data.Maintenance {
|
|
return errors.New("maintenance lock is active")
|
|
}
|
|
if _, exists := s.data.Jobs[job.ID]; exists {
|
|
return errors.New("update job ID already exists")
|
|
}
|
|
for _, existing := range s.data.Jobs {
|
|
if existing.Status == "queued" || existing.Status == "running" {
|
|
return errors.New("an update job is already active")
|
|
}
|
|
}
|
|
now := s.now().UTC()
|
|
job.Status = "queued"
|
|
job.Checkpoint = "accepted"
|
|
job.CreatedAt = now
|
|
job.UpdatedAt = now
|
|
s.data.Jobs[job.ID] = job
|
|
if err := s.persistLocked(); err != nil {
|
|
delete(s.data.Jobs, job.ID)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *StateStore) UpdateJob(id string, mutate func(*Job)) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
job, ok := s.data.Jobs[id]
|
|
if !ok {
|
|
return os.ErrNotExist
|
|
}
|
|
old := job
|
|
oldMaintenance := s.data.Maintenance
|
|
mutate(&job)
|
|
job.UpdatedAt = s.now().UTC()
|
|
s.data.Jobs[id] = job
|
|
if job.Status == "manual_intervention" {
|
|
s.data.Maintenance = true
|
|
}
|
|
if err := s.persistLocked(); err != nil {
|
|
s.data.Jobs[id] = old
|
|
s.data.Maintenance = oldMaintenance
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ForceManual updates only process memory when durable state cannot be
|
|
// written. The previously persisted queued/running record will also be
|
|
// converted to manual_intervention on restart, so both the live process and a
|
|
// replacement fail closed.
|
|
func (s *StateStore) ForceManual(id, code string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
job, ok := s.data.Jobs[id]
|
|
if !ok {
|
|
return
|
|
}
|
|
job.Status = "manual_intervention"
|
|
job.ErrorCode = code
|
|
job.UpdatedAt = s.now().UTC()
|
|
s.data.Jobs[id] = job
|
|
s.data.Maintenance = true
|
|
}
|
|
|
|
func (s *StateStore) ResolveJob(id, resolution, evidence string) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
job, ok := s.data.Jobs[id]
|
|
if !ok {
|
|
return os.ErrNotExist
|
|
}
|
|
if job.Status != "manual_intervention" {
|
|
return errors.New("only a manual-intervention job can be resolved")
|
|
}
|
|
oldJob := job
|
|
oldMaintenance := s.data.Maintenance
|
|
job.Status = "resolved"
|
|
job.Checkpoint = "operator_reconciled"
|
|
job.Resolution = resolution
|
|
job.ResolutionEvidence = evidence
|
|
job.UpdatedAt = s.now().UTC()
|
|
s.data.Jobs[id] = job
|
|
s.data.Maintenance = false
|
|
for otherID, other := range s.data.Jobs {
|
|
if otherID != id && other.Status == "manual_intervention" {
|
|
s.data.Maintenance = true
|
|
}
|
|
}
|
|
if err := s.persistLocked(); err != nil {
|
|
s.data.Jobs[id] = oldJob
|
|
s.data.Maintenance = oldMaintenance
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *StateStore) Job(id string) (Job, bool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
job, ok := s.data.Jobs[id]
|
|
return job, ok
|
|
}
|
|
|
|
func (s *StateStore) Jobs() []Job {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
jobs := make([]Job, 0, len(s.data.Jobs))
|
|
for _, job := range s.data.Jobs {
|
|
jobs = append(jobs, job)
|
|
}
|
|
sort.Slice(jobs, func(i, j int) bool { return jobs[i].CreatedAt.After(jobs[j].CreatedAt) })
|
|
return jobs
|
|
}
|
|
|
|
func (s *StateStore) JobPointers() (active, last string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
var activeAt, lastAt time.Time
|
|
for _, job := range s.data.Jobs {
|
|
if last == "" || job.CreatedAt.After(lastAt) {
|
|
last = job.ID
|
|
lastAt = job.CreatedAt
|
|
}
|
|
if job.Status == "queued" || job.Status == "running" || job.Status == "manual_intervention" {
|
|
if active == "" || job.CreatedAt.After(activeAt) {
|
|
active = job.ID
|
|
activeAt = job.CreatedAt
|
|
}
|
|
}
|
|
}
|
|
return active, last
|
|
}
|
|
|
|
func (s *StateStore) MaintenanceLocked() bool {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
return s.data.Maintenance
|
|
}
|
|
|
|
func (s *StateStore) persistLocked() error {
|
|
directory := filepath.Dir(s.path)
|
|
if err := os.MkdirAll(directory, 0o700); err != nil {
|
|
return fmt.Errorf("create update state directory: %w", err)
|
|
}
|
|
data, err := json.MarshalIndent(s.data, "", " ")
|
|
if err != nil {
|
|
return fmt.Errorf("encode update state: %w", err)
|
|
}
|
|
temporary, err := os.CreateTemp(directory, ".state-*.tmp")
|
|
if err != nil {
|
|
return fmt.Errorf("create temporary update state: %w", err)
|
|
}
|
|
temporaryPath := temporary.Name()
|
|
defer os.Remove(temporaryPath)
|
|
if err := temporary.Chmod(0o600); err != nil {
|
|
temporary.Close()
|
|
return err
|
|
}
|
|
if _, err := temporary.Write(append(data, '\n')); err != nil {
|
|
temporary.Close()
|
|
return err
|
|
}
|
|
if err := temporary.Sync(); err != nil {
|
|
temporary.Close()
|
|
return err
|
|
}
|
|
if err := temporary.Close(); err != nil {
|
|
return err
|
|
}
|
|
if err := os.Rename(temporaryPath, s.path); err != nil {
|
|
return fmt.Errorf("replace update state: %w", err)
|
|
}
|
|
directoryHandle, err := os.Open(directory)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer directoryHandle.Close()
|
|
return directoryHandle.Sync()
|
|
}
|