Files
seaweedfs/seaweed-block/core/lifecycle/placement_intent.go
T
759b7f3a36 seaweed-block: test the import syncfs selector and report each store's import mode (on #13458) (#13469)
* seaweed-block: preserve unchanged imports and batch durable publication

* seaweed-block: name the rejected entry in a startup import error

The batch import returned the bare validation error, so a bad cluster-spec
node or placement seed stopped startup without saying which entry. The
per-entry RegisterNode/ApplyPlan loop named it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: name the import path in the freshness row and registry guard

Startup now replays nodes through ImportNodes, not RegisterNode; list it
where the freshness invariant and the registry-writer guard name the
writers. Drop a doubled blank line in the operations manual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: poison a lifecycle store only on a persistence error

A node registration whose SeenAt cannot be encoded failed before any file
I/O, but RegisterNode latched the marshal error and every later mutation
returned ErrLifecycleRecoveryRequired until reopen. Latch only a
RecordPersistenceError, as the volume store already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: keep a node's SeenAt when its declaration changes

registrationLocked kept SeenAt only for an unchanged declaration. A
restart that changed a node's declared pools or address stamped the
current time, so a silent node passed the stale-observation check. A
declaration without an observation time now keeps the stored one; a new
node still gets the current time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: use the import syncfs only on filesystems that report its errors

The batch path was chosen from the kernel release alone. On overlayfs,
syncfs checks the overlay superblock's writeback errors, not the upper
file's, and on FUSE it does not send FSYNC to the daemon, so an import
could publish records whose data never became durable. Select syncfs
only when the records directory is on ext4, xfs, btrfs or tmpfs, and keep
per-file fsync elsewhere. The startup line now reports the path for the
lifecycle store, after it exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: assert the imported values before the reopen check

The import step control compared the store's snapshot with a reopen, so
an import that synced and renamed but committed the old values passed.
Check the changed and unchanged values before and after reopen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: check both views after a removal retry

present() returned record && snapshot, so a removal that cleared only one
view passed the final check. Report both and require both absent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: assert the one-second fail-stop bound

The blocked-logger control checked only exit status 1 inside a four-second
child timeout, so a longer exit timer still passed. The child now reports
when it triggers the failure, and the parent requires exit within the
one-second deadline plus one second of scheduler tolerance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: add the lifecycle machine's transition table

Every other Part A machine lists its transitions with guard, enforcing
code and Part B rows; the lifecycle record I/O machine had only its
diagram. Also name DeletePlacement and DeleteVolume beside RemoveNode in
the open gap: none of them syncs the directory after removing a record.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: scope the manual's lifecycle exit policy to the stores it covers

Only the node, placement and volume stores have the fail-stop handler.
State that deletion-reservation and workspace-binding write failures
return the error without exiting, and that an uncertain binding store
needs a restart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: test the import's syncfs selection through the production selector

TestSyncfsFilesystemGate checked the filesystem predicate directly and
the selector only with an unreadable directory, so a selector that took
syncfs after any successful Statfs passed. A test hook now rewrites the
filesystem type a successful Statfs reports; an import into a readable
directory reported as overlay must sync each file, and its ext4 twin
must issue one syncfs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: report import durability for the node and placement store directories

Startup probed the lifecycle root, but the node and placement imports
select syncfs from their own nodes/ and placements/ directories, so a
subdirectory on a separate mount could report one path and use the
other. Each store now reports the mode its import selects, startup
prints both, and nothing is printed without a lifecycle store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-block: list the syncfs selector and per-store mode tests in the ledger

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: pingqiu <pingqiu@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 12:25:46 -08:00

356 lines
12 KiB
Go

package lifecycle
import (
"encoding/json"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"sort"
"sync"
)
var ErrInsufficientPlacementCandidates = errors.New("lifecycle: insufficient placement candidates")
// PlacementSlotIntent is the controller-facing desired slot generated from a
// placement plan. It is still not authority: no epoch, no endpoint version,
// no readiness.
type PlacementSlotIntent struct {
ServerID string `json:"server_id"`
PoolID string `json:"pool_id,omitempty"`
ReplicaID string `json:"replica_id,omitempty"`
Source string `json:"source"`
DataAddr string `json:"data_addr,omitempty"`
CtrlAddr string `json:"ctrl_addr,omitempty"`
ISCSIListenPort int `json:"iscsi_listen_port,omitempty"`
NVMeListenPort int `json:"nvme_listen_port,omitempty"`
}
// PlacementIntent is durable controller input for one volume.
type PlacementIntent struct {
VolumeID string `json:"volume_id"`
DesiredRF int `json:"desired_rf"`
Slots []PlacementSlotIntent `json:"slots"`
}
// PlacementIntentStore persists one placement intent per volume.
type PlacementIntentStore struct {
mu sync.Mutex
dir string
writeErr error // failed persistence requires reopen before another mutation
onPersistenceFailure PersistenceFailureHandler
records map[string]PlacementIntent
published sync.Map // committed immutable PlacementIntent values; renewal never takes mu
}
// SetPersistenceFailureHandler installs the process host policy before serving.
// The callback runs under the writer mutex and must not reenter the store.
func (s *PlacementIntentStore) SetPersistenceFailureHandler(handler PersistenceFailureHandler) {
s.mu.Lock()
defer s.mu.Unlock()
s.onPersistenceFailure = handler
}
// OpenPlacementIntentStore opens or creates a placement intent store.
func OpenPlacementIntentStore(dir string) (*PlacementIntentStore, error) {
if dir == "" {
return nil, fmt.Errorf("%w: empty dir", ErrInvalidVolumeSpec)
}
dir, err := filepath.Abs(filepath.Clean(dir))
if err != nil {
return nil, fmt.Errorf("lifecycle: resolve store path: %w", err)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil, fmt.Errorf("lifecycle: mkdir placement intent %q: %w", dir, err)
}
// INV-LIFECYCLE-STORE-DURABLE-001: existence does not prove durability.
// Every open syncs the full ancestor chain, also after a failed first open.
for parent := filepath.Dir(dir); ; parent = filepath.Dir(parent) {
if err := syncBindingParent(parent); err != nil {
log.Printf("lifecycle: could not sync %s (%v): the store directory entry may not survive a crash right after its creation", parent, err)
}
if parent == filepath.Dir(parent) {
break
}
}
s := &PlacementIntentStore{
dir: dir,
records: make(map[string]PlacementIntent),
}
if err := s.load(); err != nil {
return nil, err
}
// Loaded names may come from a failed rename/barrier attempt. Establish
// their durability before exposing them or taking an equality shortcut.
if err := syncRecordDirectory(dir); err != nil {
return nil, &RecordPersistenceError{Store: dir, Record: "<recovery>", Err: err}
}
for volume, rec := range s.records {
s.published.Store(volume, copyPlacementIntent(rec))
}
return s, nil
}
// ApplyPlan records placement intent from a sufficient plan. Insufficient
// plans are rejected rather than persisted as partial authority-shaped state.
func (s *PlacementIntentStore) ApplyPlan(plan PlacementPlan) (PlacementIntent, error) {
intent, err := placementIntentFromPlan(plan)
if err != nil {
return PlacementIntent{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return PlacementIntent{}, err
}
// Equal input already has a durable record; preserve it on restart.
if old, ok := s.records[intent.VolumeID]; ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) {
return copyPlacementIntent(old), nil
}
if err := s.putLocked(intent); err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
return PlacementIntent{}, err
}
s.records[intent.VolumeID] = intent
s.published.Store(intent.VolumeID, copyPlacementIntent(intent))
return copyPlacementIntent(intent), nil
}
// DeletePlacement removes one placement intent. Missing intents are a
// successful no-op so reconciliation cleanup is retry-safe.
func (s *PlacementIntentStore) DeletePlacement(volumeID string) error {
if err := validateVolumeID(volumeID); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
if err := os.Remove(s.path(volumeID)); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("lifecycle: remove placement intent %s: %w", volumeID, err)
}
delete(s.records, volumeID)
s.published.Delete(volumeID)
return nil
}
// GetPlacement returns a copy of one placement intent.
func (s *PlacementIntentStore) GetPlacement(volumeID string) (PlacementIntent, bool) {
s.mu.Lock()
defer s.mu.Unlock()
rec, ok := s.records[volumeID]
return copyPlacementIntent(rec), ok
}
// GetPlacementSnapshot reads only committed placement, without waiting for a
// writer's filesystem I/O (INV-WS-RENEW-NONBLOCKING-001). The returned slice
// is a copy: a caller cannot change the published holder membership.
func (s *PlacementIntentStore) GetPlacementSnapshot(volumeID string) (PlacementIntent, bool) {
value, ok := s.published.Load(volumeID)
if !ok {
return PlacementIntent{}, false
}
return copyPlacementIntent(value.(PlacementIntent)), true
}
// ListPlacements returns intents ordered by VolumeID.
func (s *PlacementIntentStore) ListPlacements() []PlacementIntent {
s.mu.Lock()
defer s.mu.Unlock()
keys := make([]string, 0, len(s.records))
for k := range s.records {
keys = append(keys, k)
}
sort.Strings(keys)
out := make([]PlacementIntent, 0, len(keys))
for _, k := range keys {
out = append(out, copyPlacementIntent(s.records[k]))
}
return out
}
func (s *PlacementIntentStore) load() error {
entries, err := os.ReadDir(s.dir)
if err != nil {
return fmt.Errorf("lifecycle: readdir placement intent %q: %w", s.dir, err)
}
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
continue
}
path := filepath.Join(s.dir, entry.Name())
raw, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("lifecycle: read placement intent %q: %w", path, err)
}
var rec PlacementIntent
if err := json.Unmarshal(raw, &rec); err != nil {
return fmt.Errorf("lifecycle: parse placement intent %q: %w", path, err)
}
if err := validatePlacementIntent(rec); err != nil {
return fmt.Errorf("lifecycle: invalid placement intent %q: %w", path, err)
}
if filepath.Base(s.path(rec.VolumeID)) != entry.Name() {
return fmt.Errorf("lifecycle: placement filename %q does not match volume_id %q", entry.Name(), rec.VolumeID)
}
s.records[rec.VolumeID] = rec
}
return nil
}
func (s *PlacementIntentStore) putLocked(rec PlacementIntent) error {
raw, err := json.MarshalIndent(rec, "", " ")
if err != nil {
return fmt.Errorf("lifecycle: marshal placement intent %s: %w", rec.VolumeID, err)
}
return writeRecordDurably(s.dir, rec.VolumeID+".json", raw)
}
func (s *PlacementIntentStore) path(volumeID string) string {
return filepath.Join(s.dir, volumeID+".json")
}
func validatePlacementIntent(intent PlacementIntent) error {
if err := validateVolumeID(intent.VolumeID); err != nil {
return err
}
if intent.DesiredRF <= 0 {
return fmt.Errorf("%w: desired_rf must be > 0", ErrInvalidVolumeSpec)
}
if len(intent.Slots) != intent.DesiredRF {
return fmt.Errorf("%w: slot count %d != desired_rf %d", ErrInvalidVolumeSpec, len(intent.Slots), intent.DesiredRF)
}
seenServers := make(map[string]bool)
for _, slot := range intent.Slots {
if err := validateServerID(slot.ServerID); err != nil {
return err
}
if seenServers[slot.ServerID] {
return fmt.Errorf("%w: duplicate server %s", ErrInvalidVolumeSpec, slot.ServerID)
}
if err := validateOptionalPort("iscsi_listen_port", slot.ISCSIListenPort); err != nil {
return err
}
if err := validateOptionalPort("nvme_listen_port", slot.NVMeListenPort); err != nil {
return err
}
seenServers[slot.ServerID] = true
switch slot.Source {
case PlacementSourceBlankPool:
if slot.PoolID == "" {
return fmt.Errorf("%w: blank-pool slot on %s missing pool id", ErrInvalidVolumeSpec, slot.ServerID)
}
if slot.ReplicaID != "" {
return fmt.Errorf("%w: blank-pool slot on %s must not preassign replica id", ErrInvalidVolumeSpec, slot.ServerID)
}
case PlacementSourceExistingReplica:
if slot.ReplicaID == "" {
return fmt.Errorf("%w: existing-replica slot on %s missing replica id", ErrInvalidVolumeSpec, slot.ServerID)
}
default:
return fmt.Errorf("%w: unknown placement source %q", ErrInvalidVolumeSpec, slot.Source)
}
}
return nil
}
func validateOptionalPort(name string, port int) error {
if port < 0 || port > 65535 {
return fmt.Errorf("%w: %s %d outside 0..65535", ErrInvalidVolumeSpec, name, port)
}
return nil
}
func copyPlacementIntent(in PlacementIntent) PlacementIntent {
out := in
out.Slots = append([]PlacementSlotIntent(nil), in.Slots...)
return out
}
// ImportDurabilityMode reports the persistence path ImportPlans uses.
func (s *PlacementIntentStore) ImportDurabilityMode() string { return importDurabilityMode(s.dir) }
// ImportPlans replays one startup placement step and publishes only after
// the changed files and their shared directory barrier have completed.
func (s *PlacementIntentStore) ImportPlans(plans []PlacementPlan) error {
s.mu.Lock()
defer s.mu.Unlock()
if err := recoveryRequired(s.writeErr); err != nil {
return err
}
changed := make(map[string]PlacementIntent)
seen := make(map[string]bool)
order := make([]string, 0, len(plans))
for _, plan := range plans {
intent, err := placementIntentFromPlan(plan)
if err != nil {
return fmt.Errorf("lifecycle: import placement intent %s: %w", plan.VolumeID, err)
}
old, ok := s.records[intent.VolumeID]
if !seen[intent.VolumeID] {
order = append(order, intent.VolumeID)
seen[intent.VolumeID] = true
}
if ok && old.DesiredRF == intent.DesiredRF && slices.Equal(old.Slots, intent.Slots) {
delete(changed, intent.VolumeID)
continue
}
changed[intent.VolumeID] = intent
}
writes := make([]recordWrite, 0, len(order))
for _, id := range order {
if _, ok := changed[id]; !ok {
continue
}
raw, err := json.MarshalIndent(changed[id], "", " ")
if err != nil {
return fmt.Errorf("lifecycle: marshal placement intent %s: %w", id, err)
}
writes = append(writes, recordWrite{name: id + ".json", raw: raw})
}
if err := writeRecordBatchDurably(s.dir, writes); err != nil {
latchPersistenceFailure(err, &s.writeErr, s.onPersistenceFailure)
return err
}
for _, id := range order {
if _, ok := changed[id]; !ok {
continue
}
intent := changed[id]
s.records[id] = intent
s.published.Store(id, copyPlacementIntent(intent))
}
return nil
}
func placementIntentFromPlan(plan PlacementPlan) (PlacementIntent, error) {
if !plan.EnoughCandidates() {
return PlacementIntent{}, ErrInsufficientPlacementCandidates
}
intent := PlacementIntent{
VolumeID: plan.VolumeID,
DesiredRF: plan.DesiredRF,
Slots: make([]PlacementSlotIntent, 0, plan.DesiredRF),
}
for _, candidate := range plan.Candidates[:plan.DesiredRF] {
intent.Slots = append(intent.Slots, PlacementSlotIntent{
ServerID: candidate.ServerID,
PoolID: candidate.PoolID,
ReplicaID: candidate.ReplicaID,
Source: candidate.Source,
DataAddr: candidate.DataAddr,
CtrlAddr: candidate.CtrlAddr,
ISCSIListenPort: candidate.ISCSIListenPort,
NVMeListenPort: candidate.NVMeListenPort,
})
}
if err := validatePlacementIntent(intent); err != nil {
return PlacementIntent{}, err
}
return intent, nil
}