Files
CephfsMig/internal/migration/state.go
T
Sebastian UnterschützandClaude Opus 5.5 a6fda8f8d3 style: add blank lines between declarations and statement blocks
Separate top-level declarations and multi-line statements with blank
lines, keeping an "if err != nil" check next to the statement it
belongs to. Expand semicolon one-liners, group the nativeTransport
fields by purpose, and format the cgo preamble as readable C.
Apart from the expanded one-liners and the C preamble, the change
is whitespace only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 18:36:19 +01:00

176 lines
4.3 KiB
Go

package migration
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"syscall"
)
const stateVersion = 1
// Snapshot is the journal record of one source snapshot and its transfer
// to the target.
type Snapshot struct {
Name string `json:"name"`
CreatedAt string `json:"source_created_at"`
TargetCreatedAt string `json:"target_created_at,omitempty"`
Owned bool `json:"owned"`
Final bool `json:"final,omitempty"`
Done bool `json:"done"`
Metadata map[string]string `json:"metadata,omitempty"`
Stats *TransferStats `json:"transfer,omitempty"`
}
// State is the persistent migration journal. It is written atomically
// after every step so that an interrupted run can be resumed.
type State struct {
Version int `json:"version"`
ID string `json:"id"`
Config Config `json:"config"`
SourceFSID string `json:"source_fsid"`
TargetFSID string `json:"target_fsid"`
SourcePath string `json:"source_path"`
TargetPath string `json:"target_path"`
Phase string `json:"phase"`
Snapshots []Snapshot `json:"snapshots"`
Notes []string `json:"notes,omitempty"`
LiveSnapshot string `json:"live_snapshot,omitempty"`
}
// LoadState reads and validates the migration journal at path. Symbolic
// links are not followed.
func LoadState(path string) (*State, error) {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0)
if err != nil {
return nil, err
}
defer f.Close()
var s State
d := json.NewDecoder(f)
d.DisallowUnknownFields()
if err := d.Decode(&s); err != nil {
return nil, fmt.Errorf("state: %w", err)
}
if err := d.Decode(new(any)); !errors.Is(err, io.EOF) {
return nil, errors.New("state must contain exactly one JSON object")
}
id, err := hex.DecodeString(s.ID)
if s.Version != stateVersion || err != nil || len(id) != 16 {
return nil, errors.New("unsupported or invalid state")
}
if s.Phase != "syncing" && s.Phase != "ready-for-cutover" {
return nil, errors.New("invalid state phase")
}
names := map[string]bool{}
for _, snap := range s.Snapshots {
if !validName(snap.Name) || names[snap.Name] || (snap.Done && (snap.CreatedAt == "" || snap.TargetCreatedAt == "")) {
return nil, errors.New("invalid snapshot state")
}
names[snap.Name] = true
}
if s.LiveSnapshot != "" {
confirmed := false
for _, snap := range s.Snapshots {
if snap.Name == s.LiveSnapshot && snap.Done {
confirmed = true
break
}
}
if !confirmed {
return nil, errors.New("live base must reference a completed snapshot")
}
}
if s.Phase == "ready-for-cutover" {
if len(s.Snapshots) == 0 {
return nil, errors.New("ready state has no snapshots")
}
for _, snap := range s.Snapshots {
if !snap.Done {
return nil, errors.New("ready state has incomplete snapshots")
}
}
if !s.Snapshots[len(s.Snapshots)-1].Final {
return nil, errors.New("ready state has no final snapshot")
}
}
if err := s.Config.Validate(); err != nil {
return nil, fmt.Errorf("state config: %w", err)
}
return &s, nil
}
// SaveState atomically replaces the journal at path with s and syncs the
// containing directory.
func SaveState(path string, s *State) error {
return atomicJSON(path, s)
}
func atomicJSON(path string, v any) error {
dir := filepath.Dir(path)
f, err := os.CreateTemp(dir, ".cephmig-state-*")
if err != nil {
return err
}
name := f.Name()
defer os.Remove(name)
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err = enc.Encode(v); err != nil {
return err
}
if err = f.Sync(); err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}
if err = os.Rename(name, path); err != nil {
return err
}
d, err := os.Open(dir)
if err != nil {
return err
}
defer d.Close()
return d.Sync()
}
func lockFile(path string) (*os.File, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0600)
if err != nil {
return nil, err
}
if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
f.Close()
return nil, fmt.Errorf("another process holds lock %s: %w", path, err)
}
return f, nil
}