mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Merge pull request #290 from seaweedfs/feat/master-journal-isolation
master: detect a shared authority journal; lease headroom alarm
This commit is contained in:
commit
c628c09e59
29 files changed
+2843
-645
No files matched your search
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// --strict-journal-isolation and --status-listen are off by default; a
|
||||
// non-loopback --status-listen is refused at startup with a clear error.
|
||||
func TestParseFlags_JournalIsolationAndStatusListen(t *testing.T) {
|
||||
f, err := parseFlags([]string{"--authority-store", t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.strictJournalIsolation || f.statusListen != "" {
|
||||
t.Fatalf("defaults: strict=%v status-listen=%q, want off", f.strictJournalIsolation, f.statusListen)
|
||||
}
|
||||
f, err = parseFlags([]string{"--authority-store", t.TempDir(), "--strict-journal-isolation", "--status-listen", "127.0.0.1:9335"})
|
||||
if err != nil || !f.strictJournalIsolation || f.statusListen != "127.0.0.1:9335" {
|
||||
t.Fatalf("set: %+v %v", f, err)
|
||||
}
|
||||
for _, bad := range []string{"0.0.0.0:9335", ":9335", "192.168.1.10:9335"} {
|
||||
_, err := parseFlags([]string{"--authority-store", t.TempDir(), "--status-listen", bad})
|
||||
if err == nil || !strings.Contains(err.Error(), "must be a loopback address") {
|
||||
t.Fatalf("--status-listen %s: %v, want a loopback refusal", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,8 @@ type flags struct {
|
||||
workspaceHEADBase string
|
||||
frontendPublicationRuntimeHTTP bool
|
||||
frontendPublicationRuntimeListen string
|
||||
strictJournalIsolation bool
|
||||
statusListen string
|
||||
version bool
|
||||
// printReadyLine: test-only flag that emits a single
|
||||
// structured JSON line to stdout after the gRPC listener is
|
||||
@@ -110,6 +112,8 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP directory containing per-volume HEAD files; required with --workspace-rpc")
|
||||
fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only")
|
||||
fs.StringVar(&f.frontendPublicationRuntimeListen, "frontend-publication-runtime-listen", "127.0.0.1:9334", "HTTP listen address for --frontend-publication-runtime-http")
|
||||
fs.BoolVar(&f.strictJournalIsolation, "strict-journal-isolation", false, "refuse new work on nodes whose durable root shares the authority store's file system (one journal): their heartbeats are refused until they serve a volume, and no placement or move targets them; off = alarm only")
|
||||
fs.StringVar(&f.statusListen, "status-listen", "", "loopback HTTP address for the read-only GET /status/workspace-lease endpoint; empty = off")
|
||||
fs.BoolVar(&f.version, "version", false, "print build provenance and exit")
|
||||
fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout after listener bound")
|
||||
fs.SetOutput(os.Stderr)
|
||||
@@ -131,6 +135,9 @@ func parseFlags(args []string) (flags, error) {
|
||||
if f.authorityStore == "" {
|
||||
return flags{}, fmt.Errorf("--authority-store is required")
|
||||
}
|
||||
if err := master.ValidateStatusListen(f.statusListen); err != nil {
|
||||
return flags{}, err
|
||||
}
|
||||
if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" {
|
||||
return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name")
|
||||
}
|
||||
@@ -182,6 +189,8 @@ func run(f flags) int {
|
||||
FailbackRuntimeRPC: f.failbackRuntimeRPC,
|
||||
FrontendPublicationRuntimeHTTP: f.frontendPublicationRuntimeHTTP,
|
||||
FrontendPublicationRuntimeListen: f.frontendPublicationRuntimeListen,
|
||||
StrictJournalIsolation: f.strictJournalIsolation,
|
||||
StatusListen: f.statusListen,
|
||||
}
|
||||
if f.workspaceRPC {
|
||||
reader, err := master.NewWorkspaceHEADReader(f.workspaceHEADBase)
|
||||
|
||||
@@ -36,6 +36,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"github.com/seaweedfs/seaweed-block/core/transport"
|
||||
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
|
||||
)
|
||||
@@ -1509,6 +1510,10 @@ func deriveDualLaneAddr(addr string) (string, error) {
|
||||
// beside the volume's durable files, or "" for non-durable memback runs.
|
||||
// hostConfig is the volume host's configuration from the flags.
|
||||
func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config {
|
||||
var ident storeident.Identity
|
||||
if f.durableRoot != "" {
|
||||
ident = storeident.Of(f.durableRoot)
|
||||
}
|
||||
return volume.Config{
|
||||
MasterAddr: f.masterAddr,
|
||||
ServerID: f.serverID,
|
||||
@@ -1522,6 +1527,7 @@ func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config {
|
||||
EnableT1Readiness: f.enableT1Readiness,
|
||||
WorkspaceLease: f.workspaceLease,
|
||||
RF1Only: rf1Only(f),
|
||||
StorageIdentity: ident,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
)
|
||||
|
||||
// The host config carries the durable root's file-system identity (what the
|
||||
// heartbeat reports); a memback run (no durable root) reports unknown.
|
||||
func TestHostConfigStorageIdentityFromDurableRoot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if got, want := hostConfig(flags{durableRoot: root}, nil).StorageIdentity, storeident.Of(root); got != want {
|
||||
t.Fatalf("durable root identity = %+v, want %+v", got, want)
|
||||
}
|
||||
if got := hostConfig(flags{}, nil).StorageIdentity; got != (storeident.Identity{}) {
|
||||
t.Fatalf("memback identity = %+v, want unknown", got)
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,8 @@ type Publisher struct {
|
||||
leaseMu sync.Mutex
|
||||
leaseViews map[string]*leaseView
|
||||
leaseClosing bool
|
||||
leaseStats leaseCounters // guarded by leaseMu
|
||||
leaseLog func(string) // renewal-path notes; nil = log.Print (test seam)
|
||||
extWG sync.WaitGroup
|
||||
extendFailures map[string]int // guarded by mu
|
||||
|
||||
|
||||
@@ -141,36 +141,70 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
|
||||
return persist()
|
||||
}
|
||||
|
||||
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
func validateWorkspaceMoveRequest(req WorkspaceMoveRequest) error {
|
||||
// v1 moves a replica between hosts without changing its logical slot.
|
||||
// Refuse before locking or persisting a reservation/authority epoch.
|
||||
if req.ExpectedReplicaID != req.TargetReplicaID {
|
||||
return WorkspaceMoveRecord{}, fmt.Errorf("workspace move: v1 requires the same logical replica id")
|
||||
return fmt.Errorf("workspace move: v1 requires the same logical replica id")
|
||||
}
|
||||
if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || req.ExpectedHost == req.TargetHost || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" ||
|
||||
req.TargetDataAddr == "" || req.TargetCtrlAddr == "" || (req.Kind != "clean" && req.Kind != "forced") || req.Force != (req.Kind == "forced") {
|
||||
return WorkspaceMoveRecord{}, fmt.Errorf("workspace move: invalid request")
|
||||
return fmt.Errorf("workspace move: invalid request")
|
||||
}
|
||||
p.mu.Lock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// issuedWorkspaceReplayLocked finds req's journal record: replay is true when
|
||||
// req repeats an issued move (same request id, same validated body); an id
|
||||
// reused with a different body is an error. Caller holds p.mu.
|
||||
func (p *Publisher) issuedWorkspaceReplayLocked(req WorkspaceMoveRequest) (WorkspaceMoveRecord, bool, error) {
|
||||
if s := p.workspace[req.VolumeID]; s != nil {
|
||||
for _, r := range s.Moves {
|
||||
if r.RequestID == req.RequestID {
|
||||
if !sameWorkspaceRequest(r, req) {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceMoveRecord{}, fmt.Errorf("workspace move request id reused")
|
||||
return WorkspaceMoveRecord{}, false, fmt.Errorf("workspace move request id reused")
|
||||
}
|
||||
if r.Issued {
|
||||
p.mu.Unlock()
|
||||
return r, nil
|
||||
return r, true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return WorkspaceMoveRecord{}, false, nil
|
||||
}
|
||||
|
||||
// IssuedWorkspaceMove reports whether req is an exact replay of an issued
|
||||
// move, with the same validation MoveWorkspace applies before its replay. It
|
||||
// only reads: MoveWorkspace of the same request returns that record and
|
||||
// mints nothing. Admission rules for new work (strict journal isolation) let
|
||||
// such a replay through: they refuse new decisions, never an issued one.
|
||||
func (p *Publisher) IssuedWorkspaceMove(req WorkspaceMoveRequest) bool {
|
||||
if validateWorkspaceMoveRequest(req) != nil {
|
||||
return false
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
_, replay, err := p.issuedWorkspaceReplayLocked(req)
|
||||
return replay && err == nil
|
||||
}
|
||||
|
||||
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
if err := validateWorkspaceMoveRequest(req); err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
p.mu.Lock()
|
||||
r, replay, err := p.issuedWorkspaceReplayLocked(req)
|
||||
p.mu.Unlock()
|
||||
err := p.applyWithWorkspaceMove(AssignmentAsk{VolumeID: req.VolumeID, ReplicaID: req.TargetReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign}, &workspaceGrant{req, head})
|
||||
if err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
if replay {
|
||||
return r, nil
|
||||
}
|
||||
err = p.applyWithWorkspaceMove(AssignmentAsk{VolumeID: req.VolumeID, ReplicaID: req.TargetReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign}, &workspaceGrant{req, head})
|
||||
if err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
@@ -239,25 +273,37 @@ func (p *Publisher) workspaceLineLocked(volume string) (subKey, assignmentState,
|
||||
}
|
||||
|
||||
func (p *Publisher) persistWorkspaceLocked(volume string, s *WorkspaceState) error {
|
||||
_, _, err := p.persistWorkspaceTimedLocked(volume, s)
|
||||
return err
|
||||
}
|
||||
|
||||
// persistWorkspaceTimedLocked is persistWorkspaceLocked that also reports how
|
||||
// long the durable store write itself took (write) and whether it was
|
||||
// attempted (wrote is false when it refused before writing). Caller holds
|
||||
// p.mu.
|
||||
func (p *Publisher) persistWorkspaceTimedLocked(volume string, s *WorkspaceState) (write time.Duration, wrote bool, err error) {
|
||||
if p.store == nil || p.workspaceUncertain[volume] {
|
||||
return fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
return 0, false, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
if !ok {
|
||||
return fmt.Errorf("workspace authority missing")
|
||||
return 0, false, fmt.Errorf("workspace authority missing")
|
||||
}
|
||||
i := line.info
|
||||
record := DurableRecord{VolumeID: volume, ReplicaID: i.ReplicaID, Epoch: i.Epoch, EndpointVersion: i.EndpointVersion, DataAddr: i.DataAddr, CtrlAddr: i.CtrlAddr,
|
||||
WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s)}
|
||||
if err := p.store.Put(record); err != nil {
|
||||
start := time.Now()
|
||||
err = p.store.Put(record)
|
||||
write = time.Since(start)
|
||||
if err != nil {
|
||||
p.workspaceUncertain[volume] = true
|
||||
p.refreshLeaseViewLocked(volume)
|
||||
return err
|
||||
return write, true, err
|
||||
}
|
||||
p.writeSeqByVolume[volume] = record.WriteSeq
|
||||
p.workspace[volume] = cloneWorkspace(s)
|
||||
p.refreshLeaseViewLocked(volume)
|
||||
return nil
|
||||
return write, true, nil
|
||||
}
|
||||
|
||||
type workspaceGrant struct {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Lease headroom observability. Headroom is the durable horizon minus now:
|
||||
// how long the published lease still covers a holder if no extension lands.
|
||||
// Extensions start below 1.25 TTL of headroom and grants are clamped below
|
||||
// 1 TTL, so a lagging authority store shows first as an extension in flight
|
||||
// with headroom under 1.125 TTL, and only later as clamps.
|
||||
//
|
||||
// The extension store write latency (LeaseStats.ExtensionWrite*) is
|
||||
// completed-write telemetry: a write is sampled when its Put returns, so a
|
||||
// write that is still blocked shows up only after it returns, possibly after
|
||||
// headroom is already lost; it is not an early warning by itself. The alarm
|
||||
// is sampled at renewals, never by a timer: it fires at the latest
|
||||
// together with the first clamped grant of a streak (logged before the clamp
|
||||
// line), and earlier only if a renewal lands in the 1-1.125 TTL band while an
|
||||
// extension is pending. A renewer slower than that band may see both on one
|
||||
// renewal.
|
||||
|
||||
// LeaseStats is a snapshot of the workspace lease renewal counters.
|
||||
type LeaseStats struct {
|
||||
// HeadroomAlarms counts alarm streaks, once per volume per streak: a
|
||||
// renewal that found headroom below 1.125 TTL with an extension in
|
||||
// flight, or the first clamped grant (headroom below 1 TTL) of a streak.
|
||||
HeadroomAlarms uint64
|
||||
// ClampsTotal counts grants clamped to the durable horizon.
|
||||
ClampsTotal uint64
|
||||
// ClampsLastMinute counts clamped grants in the last minute.
|
||||
ClampsLastMinute uint64
|
||||
// MinHeadroom is the smallest headroom observed at a grant; valid only
|
||||
// when MinHeadroomObserved.
|
||||
MinHeadroom time.Duration
|
||||
MinHeadroomObserved bool
|
||||
// ExtensionWriteLast is the duration of the latest lease extension's
|
||||
// durable store write (the write alone, failed or not); valid only when
|
||||
// ExtensionWriteObserved. Completed-write telemetry: recorded when the
|
||||
// Put returns, so a write still blocked is not visible here yet.
|
||||
ExtensionWriteLast time.Duration
|
||||
ExtensionWriteObserved bool
|
||||
// ExtensionWriteMaxLastMinute is the slowest extension write in the last
|
||||
// minute (rolling, one bucket per second like ClampsLastMinute); valid
|
||||
// only when ExtensionWriteInLastMinute.
|
||||
ExtensionWriteMaxLastMinute time.Duration
|
||||
ExtensionWriteInLastMinute bool
|
||||
}
|
||||
|
||||
const clampBuckets = 60 // one per second of the last minute
|
||||
|
||||
// leaseCounters is guarded by Publisher.leaseMu.
|
||||
type leaseCounters struct {
|
||||
alarms uint64
|
||||
clamps uint64
|
||||
buckets [clampBuckets]struct{ sec, n int64 } // clamps by unix second
|
||||
minHeadroom int64
|
||||
minObserved bool
|
||||
// Extension store writes: the latest, and the slowest per second of the
|
||||
// last minute.
|
||||
writeLast int64
|
||||
writeObserved bool
|
||||
writeBuckets [clampBuckets]struct {
|
||||
sec, max int64
|
||||
set bool
|
||||
}
|
||||
// Per-minute summary, emitted by the first renewal attempt after the
|
||||
// window, granted or refused: no goroutine or timer of its own. With no
|
||||
// renewal attempts at all nothing is emitted; the counters above (the
|
||||
// status endpoint) still show the clamps.
|
||||
windowStart time.Time
|
||||
windowClamps uint64
|
||||
windowMin int64
|
||||
windowMinSet bool
|
||||
}
|
||||
|
||||
func (c *leaseCounters) clampsSince(now time.Time) uint64 {
|
||||
cut := now.Unix() - clampBuckets
|
||||
var n uint64
|
||||
for _, b := range c.buckets {
|
||||
if b.n > 0 && b.sec > cut && b.sec <= now.Unix() {
|
||||
n += uint64(b.n)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (c *leaseCounters) recordClamp(now time.Time) {
|
||||
c.clamps++
|
||||
c.windowClamps++
|
||||
sec := now.Unix()
|
||||
b := &c.buckets[uint64(sec)%clampBuckets]
|
||||
if b.sec != sec {
|
||||
b.sec, b.n = sec, 0
|
||||
}
|
||||
b.n++
|
||||
}
|
||||
|
||||
// recordExtensionWrite records the duration of one extension store write
|
||||
// that returned at now.
|
||||
func (c *leaseCounters) recordExtensionWrite(now time.Time, d time.Duration) {
|
||||
c.writeLast, c.writeObserved = int64(d), true
|
||||
sec := now.Unix()
|
||||
b := &c.writeBuckets[uint64(sec)%clampBuckets]
|
||||
if !b.set || b.sec != sec {
|
||||
b.sec, b.max, b.set = sec, int64(d), true
|
||||
} else if int64(d) > b.max {
|
||||
b.max = int64(d)
|
||||
}
|
||||
}
|
||||
|
||||
// extensionWriteMaxSince returns the slowest extension write of the last
|
||||
// minute, and whether there was one.
|
||||
func (c *leaseCounters) extensionWriteMaxSince(now time.Time) (int64, bool) {
|
||||
cut := now.Unix() - clampBuckets
|
||||
max, ok := int64(0), false
|
||||
for _, b := range c.writeBuckets {
|
||||
if b.set && b.sec > cut && b.sec <= now.Unix() && (!ok || b.max > max) {
|
||||
max, ok = b.max, true
|
||||
}
|
||||
}
|
||||
return max, ok
|
||||
}
|
||||
|
||||
// summaryDue closes a window that has lasted a minute and returns its summary
|
||||
// note when it had clamps. Every renewal attempt calls it, granted or refused,
|
||||
// so a stall through expiry (only refusals after the clamps) is still
|
||||
// summarized. It opens no window: the first grant does.
|
||||
func (c *leaseCounters) summaryDue(now time.Time) string {
|
||||
if c.windowStart.IsZero() || now.Sub(c.windowStart) < time.Minute {
|
||||
return ""
|
||||
}
|
||||
var note string
|
||||
if c.windowClamps > 0 {
|
||||
note = fmt.Sprintf("workspace lease: %d clamped grants in the last %s (total %d, min headroom %s); the authority store is lagging",
|
||||
c.windowClamps, now.Sub(c.windowStart).Round(time.Second), c.clamps, time.Duration(c.windowMin).Round(time.Millisecond))
|
||||
}
|
||||
c.windowStart, c.windowClamps, c.windowMinSet = now, 0, false
|
||||
return note
|
||||
}
|
||||
|
||||
// observeGrant records the headroom of a grant and returns a per-minute
|
||||
// summary note when a window with clamps has just ended. Call it before
|
||||
// recordClamp of the same grant (it may open a new window).
|
||||
func (c *leaseCounters) observeGrant(now time.Time, headroom int64) string {
|
||||
if c.windowStart.IsZero() {
|
||||
c.windowStart = now
|
||||
}
|
||||
note := c.summaryDue(now)
|
||||
if !c.windowMinSet || headroom < c.windowMin {
|
||||
c.windowMin, c.windowMinSet = headroom, true
|
||||
}
|
||||
if !c.minObserved || headroom < c.minHeadroom {
|
||||
c.minHeadroom, c.minObserved = headroom, true
|
||||
}
|
||||
return note
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStats returns a snapshot of the lease renewal counters.
|
||||
func (p *Publisher) WorkspaceLeaseStats() LeaseStats {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
c := &p.leaseStats
|
||||
now := p.workspaceNow()
|
||||
writeMax, writeRecent := c.extensionWriteMaxSince(now)
|
||||
return LeaseStats{
|
||||
HeadroomAlarms: c.alarms,
|
||||
ClampsTotal: c.clamps,
|
||||
ClampsLastMinute: c.clampsSince(now),
|
||||
MinHeadroom: time.Duration(c.minHeadroom),
|
||||
MinHeadroomObserved: c.minObserved,
|
||||
ExtensionWriteLast: time.Duration(c.writeLast),
|
||||
ExtensionWriteObserved: c.writeObserved,
|
||||
ExtensionWriteMaxLastMinute: time.Duration(writeMax),
|
||||
ExtensionWriteInLastMinute: writeRecent,
|
||||
}
|
||||
}
|
||||
|
||||
// headroomAlarmLocked runs the alarm state machine of one renewal, before the
|
||||
// renewal clamps (a grant clamps exactly when headroom < 1 TTL). Caller holds
|
||||
// leaseMu. It returns a note to log after the unlock, before the clamp note.
|
||||
//
|
||||
// state | condition at a renewal | next | effect
|
||||
// -----------+-----------------------------------------------+------------+------------------
|
||||
// quiet | extending && headroom < 1.125 TTL | alarmed | count + log once
|
||||
// quiet | headroom < 1 TTL (this grant clamps) | alarmed | count + log once
|
||||
// quiet | otherwise | quiet | -
|
||||
// alarmed | headroom >= 1.25 TTL | quiet | streak ends
|
||||
// alarmed | !extending && headroom >= 1.125 TTL | quiet | streak ends
|
||||
// alarmed | otherwise | alarmed | -
|
||||
//
|
||||
// A clamp streak (headroom < 1 TTL) therefore never starts without an alarm
|
||||
// on the same or an earlier renewal, and never re-alarms while it lasts.
|
||||
func (p *Publisher) headroomAlarmLocked(volume string, lv *leaseView, headroom int64) string {
|
||||
ttl := int64(p.workspaceTTL)
|
||||
low, high := ttl+ttl/8, ttl+ttl/4
|
||||
if lv.alarmed {
|
||||
if headroom >= high || (!lv.extending && headroom >= low) {
|
||||
lv.alarmed = false
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var why string
|
||||
switch {
|
||||
case lv.extending && headroom < low:
|
||||
why = "below 1.125 TTL while the extension write is pending"
|
||||
case headroom < ttl:
|
||||
why = "below 1 TTL: this grant is the first clamped to the durable horizon"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
lv.alarmed = true
|
||||
p.leaseStats.alarms++
|
||||
return fmt.Sprintf("workspace lease: volume=%s headroom %s %s; the authority store is lagging",
|
||||
volume, time.Duration(headroom).Round(time.Millisecond), why)
|
||||
}
|
||||
|
||||
func (p *Publisher) logLease(note string) {
|
||||
if note == "" {
|
||||
return
|
||||
}
|
||||
if p.leaseLog != nil {
|
||||
p.leaseLog(note)
|
||||
return
|
||||
}
|
||||
log.Print(note)
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// blockedLeaseStore holds every armed workspace-lease write until release
|
||||
// closes, standing in for an authority journal stuck behind other fsyncs.
|
||||
type blockedLeaseStore struct {
|
||||
AuthorityStore
|
||||
armed atomic.Bool
|
||||
entered chan struct{}
|
||||
once sync.Once
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (s *blockedLeaseStore) Put(r DurableRecord) error {
|
||||
if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
s.once.Do(func() { close(s.entered) })
|
||||
<-s.release
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
type noteLog struct {
|
||||
mu sync.Mutex
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (l *noteLog) add(s string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.lines = append(l.lines, s)
|
||||
}
|
||||
|
||||
func (l *noteLog) snapshot() []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]string(nil), l.lines...)
|
||||
}
|
||||
|
||||
func indexOf(lines []string, sub string) int {
|
||||
for i, s := range lines {
|
||||
if strings.Contains(s, sub) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// With the authority store's lease write stuck, renewals at an advancing
|
||||
// clock must raise the headroom alarm on a renewal strictly before the first
|
||||
// clamped grant, then count clamps (total and last minute) and the minimum
|
||||
// headroom, and log a per-minute summary once a minute with clamps ends.
|
||||
func TestWorkspaceLeaseHeadroomAlarmPrecedesFirstClamp(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
var nowNS atomic.Int64
|
||||
t0 := time.Unix(1000, 0)
|
||||
nowNS.Store(t0.UnixNano())
|
||||
at := func(d time.Duration) { nowNS.Store(t0.Add(d).UnixNano()) }
|
||||
const ttl = 30 * time.Second
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
notes := ¬eLog{}
|
||||
p.leaseLog = notes.add
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(store.release) }) }
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // runs after release (LIFO)
|
||||
t.Cleanup(release)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// First grant: synchronous write, horizon t0+45s.
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := p.WorkspaceLeaseStats(); s.HeadroomAlarms != 0 || s.ClampsTotal != 0 || s.MinHeadroomObserved {
|
||||
t.Fatalf("stats after the first grant: %+v", s)
|
||||
}
|
||||
store.armed.Store(true)
|
||||
renew := func(d time.Duration) (WorkspaceLease, LeaseStats) {
|
||||
t.Helper()
|
||||
at(d)
|
||||
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("renewal at +%s: %v", d, err)
|
||||
}
|
||||
return l, p.WorkspaceLeaseStats()
|
||||
}
|
||||
|
||||
// +10s: headroom 35s < 1.25 TTL starts the extension, which blocks.
|
||||
_, s := renew(10 * time.Second)
|
||||
if s.HeadroomAlarms != 0 || s.ClampsTotal != 0 {
|
||||
t.Fatalf("+10s (headroom 35s, extension just started): %+v", s)
|
||||
}
|
||||
select {
|
||||
case <-store.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the extension write never reached the store")
|
||||
}
|
||||
// +12s: headroom 33s < 33.75s (1.125 TTL), extension pending: alarm, no clamp.
|
||||
l, s := renew(12 * time.Second)
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 0 {
|
||||
t.Fatalf("+12s (headroom 33s, extension pending): want 1 alarm and 0 clamps, got %+v", s)
|
||||
}
|
||||
if want := t0.Add(12*time.Second + ttl).UnixNano(); l.ExpiresAtNS != want {
|
||||
t.Fatalf("+12s grant %d, want unclamped %d", l.ExpiresAtNS, want)
|
||||
}
|
||||
// +13s: same streak, no second alarm.
|
||||
if _, s = renew(13 * time.Second); s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+13s: alarm repeated within one streak: %+v", s)
|
||||
}
|
||||
// +20s, +25s: headroom 25s, 20s < TTL: clamped grants.
|
||||
l, s = renew(20 * time.Second)
|
||||
if want := t0.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want {
|
||||
t.Fatalf("+20s grant %d, want clamped to horizon %d", l.ExpiresAtNS, want)
|
||||
}
|
||||
if s.ClampsTotal != 1 || s.ClampsLastMinute != 1 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+20s: %+v", s)
|
||||
}
|
||||
_, s = renew(25 * time.Second)
|
||||
if s.ClampsTotal != 2 || s.ClampsLastMinute != 2 || !s.MinHeadroomObserved || s.MinHeadroom != 20*time.Second {
|
||||
t.Fatalf("+25s: want 2 clamps, min headroom 20s; got %+v", s)
|
||||
}
|
||||
lines := notes.snapshot()
|
||||
alarmAt, clampAt := indexOf(lines, "below 1.125 TTL while the extension write is pending"), indexOf(lines, "are clamped to the durable horizon")
|
||||
if alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt {
|
||||
t.Fatalf("alarm line must precede the first clamp line: alarm=%d clamp=%d\n%s", alarmAt, clampAt, strings.Join(lines, "\n"))
|
||||
}
|
||||
if !strings.Contains(lines[alarmAt], "volume=v headroom 33s") {
|
||||
t.Fatalf("alarm line: %q", lines[alarmAt])
|
||||
}
|
||||
|
||||
// The store recovers: the extension lands (horizon +10s+45s = +55s).
|
||||
release()
|
||||
waitExtenders(t, p)
|
||||
// +26s: horizon +55s, headroom 29s < TTL: one more clamp; a new extension
|
||||
// starts (trigger +26s, horizon +71s) and lands at once.
|
||||
_, s = renew(26 * time.Second)
|
||||
waitExtenders(t, p)
|
||||
if s.ClampsTotal != 3 {
|
||||
t.Fatalf("+26s: %+v", s)
|
||||
}
|
||||
// +27s: headroom 44s >= 1.25 TTL: unclamped, the alarm streak ends.
|
||||
if _, s = renew(27 * time.Second); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+27s: %+v", s)
|
||||
}
|
||||
// Healthy renewals keep the lease ahead: no clamps, no alarms.
|
||||
for _, d := range []time.Duration{40 * time.Second, 55 * time.Second} {
|
||||
if _, s = renew(d); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+%s: %+v", d, s)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
}
|
||||
if indexOf(notes.snapshot(), "clamped grants in the last") >= 0 {
|
||||
t.Fatal("summary logged before the minute ended")
|
||||
}
|
||||
// +70s: a minute after the window's first renewal (+10s): the window with
|
||||
// clamps ends and its summary is logged by this renewal.
|
||||
if _, s = renew(70 * time.Second); s.ClampsTotal != 3 {
|
||||
t.Fatalf("+70s: %+v", s)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
lines = notes.snapshot()
|
||||
if i := indexOf(lines, "workspace lease: 3 clamped grants in the last 1m0s (total 3, min headroom 20s)"); i < 0 {
|
||||
t.Fatalf("no per-minute summary:\n%s", strings.Join(lines, "\n"))
|
||||
}
|
||||
// The +20s/+25s/+26s clamps are older than a minute at +87s.
|
||||
at(87 * time.Second)
|
||||
if s = p.WorkspaceLeaseStats(); s.ClampsLastMinute != 0 || s.ClampsTotal != 3 || s.MinHeadroom != 20*time.Second {
|
||||
t.Fatalf("+87s: clamps should age out of the last minute: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// stalledLeaseRig is a publisher whose lease writes, once armed, block until
|
||||
// release, with a settable clock (t0 = first grant, TTL 30s, horizon +45s).
|
||||
type stalledLeaseRig struct {
|
||||
p *Publisher
|
||||
store *blockedLeaseStore
|
||||
notes *noteLog
|
||||
t0 time.Time
|
||||
nowNS atomic.Int64
|
||||
release func()
|
||||
}
|
||||
|
||||
func newStalledLeaseRig(t *testing.T) *stalledLeaseRig {
|
||||
t.Helper()
|
||||
disk, _ := newTempStore(t)
|
||||
r := &stalledLeaseRig{store: &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}, notes: ¬eLog{}, t0: time.Unix(1000, 0)}
|
||||
r.nowNS.Store(r.t0.UnixNano())
|
||||
r.p = NewPublisher(nil, WithStore(r.store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, r.nowNS.Load()) }))
|
||||
r.p.leaseLog = r.notes.add
|
||||
var once sync.Once
|
||||
r.release = func() { once.Do(func() { close(r.store.release) }) }
|
||||
t.Cleanup(r.p.CloseWorkspaceExtenders) // runs after release (LIFO)
|
||||
t.Cleanup(r.release)
|
||||
if err := r.p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.store.armed.Store(true)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *stalledLeaseRig) renew(d time.Duration) (WorkspaceLease, LeaseStats, error) {
|
||||
r.nowNS.Store(r.t0.Add(d).UnixNano())
|
||||
l, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
return l, r.p.WorkspaceLeaseStats(), err
|
||||
}
|
||||
|
||||
func (r *stalledLeaseRig) waitEntered(t *testing.T) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-r.store.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the extension write never reached the store")
|
||||
}
|
||||
}
|
||||
|
||||
// assertAlarmBeforeClamp checks exactly one alarm line containing want, logged
|
||||
// before the first clamp line.
|
||||
func assertAlarmBeforeClamp(t *testing.T, lines []string, want string) {
|
||||
t.Helper()
|
||||
alarms := 0
|
||||
for _, s := range lines {
|
||||
if strings.Contains(s, "the authority store is lagging") && strings.Contains(s, "headroom") && strings.Contains(s, "volume=v") {
|
||||
alarms++
|
||||
}
|
||||
}
|
||||
alarmAt, clampAt := indexOf(lines, want), indexOf(lines, "are clamped to the durable horizon")
|
||||
if alarms != 1 || alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt {
|
||||
t.Fatalf("want one alarm %q before the first clamp line: alarms=%d alarm=%d clamp=%d\n%s", want, alarms, alarmAt, clampAt, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// Skipped band: the extension starts and stalls at +10s, and the next renewal
|
||||
// (+20s) lands already clamped, never in the 1-1.125 TTL band. The alarm fires
|
||||
// on that same renewal, logged before the clamp line, and counts once.
|
||||
func TestWorkspaceLeaseAlarmWhenTheBandIsSkipped(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
if _, s, err := r.renew(10 * time.Second); err != nil || s.HeadroomAlarms != 0 {
|
||||
t.Fatalf("+10s: %+v %v", s, err)
|
||||
}
|
||||
r.waitEntered(t)
|
||||
l, s, err := r.renew(20 * time.Second)
|
||||
if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() {
|
||||
t.Fatalf("+20s: want a grant clamped to the horizon, got %+v %v", l, err)
|
||||
}
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 {
|
||||
t.Fatalf("+20s: want 1 alarm and 1 clamp, got %+v", s)
|
||||
}
|
||||
if _, s, err = r.renew(25 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+25s: alarm repeated or clamp missed: %+v %v", s, err)
|
||||
}
|
||||
assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 25s below 1.125 TTL while the extension write is pending")
|
||||
}
|
||||
|
||||
// First renewal below one TTL: no extension has started yet (the renewal
|
||||
// itself starts it), and the grant clamps. The alarm still fires with that
|
||||
// first clamp, before the clamp line, and does not repeat in the streak.
|
||||
func TestWorkspaceLeaseAlarmWithAFirstRenewalBelowTTL(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
l, s, err := r.renew(16 * time.Second)
|
||||
if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() {
|
||||
t.Fatalf("+16s: want a grant clamped to the horizon, got %+v %v", l, err)
|
||||
}
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 {
|
||||
t.Fatalf("+16s: want 1 alarm with the first clamp, got %+v", s)
|
||||
}
|
||||
r.waitEntered(t) // the renewal started the extension; it stalls
|
||||
if _, s, err = r.renew(18 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+18s: %+v %v", s, err)
|
||||
}
|
||||
assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 29s below 1 TTL: this grant is the first clamped to the durable horizon")
|
||||
}
|
||||
|
||||
// Stall through expiry: after the clamps, every renewal is refused (no host
|
||||
// validity, then expired) and none is granted again. The per-minute summary
|
||||
// is still logged, by the first refused renewal after the minute, once.
|
||||
func TestWorkspaceLeaseSummaryWithoutALaterGrant(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
if _, _, err := r.renew(10 * time.Second); err != nil { // opens the window, starts the extension
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.waitEntered(t)
|
||||
for _, d := range []time.Duration{20 * time.Second, 25 * time.Second} {
|
||||
if _, _, err := r.renew(d); err != nil {
|
||||
t.Fatalf("+%s: %v", d, err)
|
||||
}
|
||||
}
|
||||
for _, d := range []time.Duration{36 * time.Second, 46 * time.Second, 60 * time.Second} {
|
||||
if l, _, err := r.renew(d); err == nil {
|
||||
t.Fatalf("+%s: granted %+v through a stalled store past the horizon", d, l)
|
||||
}
|
||||
}
|
||||
if indexOf(r.notes.snapshot(), "clamped grants in the last") >= 0 {
|
||||
t.Fatal("summary logged before the minute ended")
|
||||
}
|
||||
if _, s, err := r.renew(71 * time.Second); err == nil || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+71s: %+v %v, want a refusal", s, err)
|
||||
}
|
||||
if _, _, err := r.renew(72 * time.Second); err == nil {
|
||||
t.Fatal("+72s granted")
|
||||
}
|
||||
lines := r.notes.snapshot()
|
||||
want := "workspace lease: 2 clamped grants in the last 1m1s (total 2, min headroom 20s)"
|
||||
n := 0
|
||||
for _, s := range lines {
|
||||
if strings.Contains(s, "clamped grants in the last") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if indexOf(lines, want) < 0 || n != 1 {
|
||||
t.Fatalf("want the summary %q once from refused renewals, got %d summaries:\n%s", want, n, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// delayedLeaseStore makes every lease write take delay (when set): a slow
|
||||
// authority journal that still completes.
|
||||
type delayedLeaseStore struct {
|
||||
AuthorityStore
|
||||
delay atomic.Int64
|
||||
}
|
||||
|
||||
func (s *delayedLeaseStore) Put(r DurableRecord) error {
|
||||
if d := time.Duration(s.delay.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
time.Sleep(d)
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
// The extension's store write latency is recorded at every extension write:
|
||||
// the latest one, and the slowest of the last minute (rolling per second),
|
||||
// which ages out a minute after the write. The first grant's write is not an
|
||||
// extension and records nothing.
|
||||
func TestWorkspaceLeaseExtensionWriteLatency(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &delayedLeaseStore{AuthorityStore: disk}
|
||||
var nowNS atomic.Int64
|
||||
t0 := time.Unix(1000, 0)
|
||||
nowNS.Store(t0.UnixNano())
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
p.leaseLog = func(string) {}
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
renew := func(d time.Duration) LeaseStats {
|
||||
t.Helper()
|
||||
nowNS.Store(t0.Add(d).UnixNano())
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatalf("renewal at +%s: %v", d, err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
return p.WorkspaceLeaseStats()
|
||||
}
|
||||
if s := renew(0); s.ExtensionWriteObserved || s.ExtensionWriteInLastMinute { // first grant
|
||||
t.Fatalf("the first grant recorded an extension write: %+v", s)
|
||||
}
|
||||
const slow = 300 * time.Millisecond
|
||||
store.delay.Store(int64(slow))
|
||||
// +10s: headroom 35s < 1.25 TTL starts an extension; its write takes 300 ms.
|
||||
s := renew(10 * time.Second)
|
||||
if !s.ExtensionWriteObserved || s.ExtensionWriteLast < slow || s.ExtensionWriteLast > slow+time.Second {
|
||||
t.Fatalf("+10s: want the last extension write ~%s, got %+v", slow, s)
|
||||
}
|
||||
if !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute < slow {
|
||||
t.Fatalf("+10s: want max >= %s in the last minute, got %+v", slow, s)
|
||||
}
|
||||
store.delay.Store(0)
|
||||
// +20s: horizon +55s, headroom 35s: a fast extension write.
|
||||
s = renew(20 * time.Second)
|
||||
if s.ExtensionWriteLast >= slow || s.ExtensionWriteMaxLastMinute < slow {
|
||||
t.Fatalf("+20s: want a fast last write and the 300 ms max kept, got %+v", s)
|
||||
}
|
||||
// +71s: the +10s write is older than a minute; the +20s one is not.
|
||||
nowNS.Store(t0.Add(71 * time.Second).UnixNano())
|
||||
if s = p.WorkspaceLeaseStats(); !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute >= slow || s.ExtensionWriteLast >= slow {
|
||||
t.Fatalf("+71s: the 300 ms max must age out, got %+v", s)
|
||||
}
|
||||
// +81s: no write in the last minute; the last write stays reported.
|
||||
nowNS.Store(t0.Add(81 * time.Second).UnixNano())
|
||||
if s = p.WorkspaceLeaseStats(); s.ExtensionWriteInLastMinute || !s.ExtensionWriteObserved {
|
||||
t.Fatalf("+81s: want no write in the last minute, last still observed; got %+v", s)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ type leaseDerived struct {
|
||||
bound bool // an authority line exists for the volume
|
||||
replica string
|
||||
epoch uint64
|
||||
issuedHost string // NewHost of the issued move that minted the line; "" if none
|
||||
leasePresent bool
|
||||
revoking bool
|
||||
movePending bool // the last workspace move is reserved, not issued
|
||||
@@ -33,6 +34,7 @@ type leaseView struct {
|
||||
deadline time.Time
|
||||
extending bool
|
||||
clamped bool // a renewal was clamped below now+TTL; logged once per streak
|
||||
alarmed bool // a headroom alarm streak is open (headroomAlarmLocked)
|
||||
}
|
||||
|
||||
// deriveLeaseLocked computes the derived lease view from published state.
|
||||
@@ -44,6 +46,11 @@ func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived {
|
||||
}
|
||||
if s := p.workspace[volume]; s != nil {
|
||||
d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued
|
||||
for _, r := range s.Moves {
|
||||
if d.bound && r.Issued && r.NewReplicaID == d.replica && r.NewEpoch == d.epoch {
|
||||
d.issuedHost = r.NewHost
|
||||
}
|
||||
}
|
||||
if s.Lease != nil {
|
||||
d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease
|
||||
d.maxSkewNS = int64(p.workspaceSkew(s.Lease))
|
||||
@@ -140,6 +147,33 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
|
||||
return l, true
|
||||
}
|
||||
|
||||
// PublishedLine is a volume's committed authority line as the lease view
|
||||
// publishes it.
|
||||
type PublishedLine struct {
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
// IssuedHost is the target host of the issued move that minted this line;
|
||||
// "" when no issued move did (a placement or static topology line).
|
||||
IssuedHost string
|
||||
}
|
||||
|
||||
// PublishedAuthorityLines returns the committed authority line of every
|
||||
// volume that has one. It reads the lease views under the leaf leaseMu only:
|
||||
// it never waits on p.mu, which writers hold across store writes, and it
|
||||
// sees only state those writers already published (a reserved, unissued
|
||||
// move never shows here).
|
||||
func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
out := make(map[string]PublishedLine, len(p.leaseViews))
|
||||
for volume, lv := range p.leaseViews {
|
||||
if lv.d.bound {
|
||||
out[volume] = PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RenewWorkspaceLease answers a live holder from memory: it takes only the
|
||||
// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant
|
||||
// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu
|
||||
@@ -151,35 +185,47 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
}
|
||||
p.leaseMu.Lock()
|
||||
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
|
||||
// unlock releases leaseMu on a path that grants nothing and logs a due
|
||||
// per-minute summary after the unlock: every renewal attempt, granted or
|
||||
// refused, may close the window (a stall through expiry refuses only).
|
||||
unlock := func() {
|
||||
summary := p.leaseStats.summaryDue(now)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(summary)
|
||||
}
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
if lv.d.movePending {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending")
|
||||
}
|
||||
if !lv.d.leasePresent {
|
||||
p.leaseMu.Unlock() // never re-enter p.mu while holding the leaf
|
||||
unlock() // never re-enter p.mu while holding the leaf
|
||||
return p.firstWorkspaceGrant(ctx, volume, holder, epoch)
|
||||
}
|
||||
if lv.d.revoking { // tell the host to drain; never extend
|
||||
l := lv.d.lease
|
||||
l.ExpiresAtNS = lv.replyExpiryNS()
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return l, nil
|
||||
}
|
||||
if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking")
|
||||
}
|
||||
// Where the synchronous write used to refuse (persistWorkspaceLocked):
|
||||
// a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001).
|
||||
if lv.d.storeless || lv.d.uncertain {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
// The headroom alarm is sampled here, before the clamp: at the latest it
|
||||
// fires on the first clamped grant of a streak (headroomAlarmLocked).
|
||||
headroom := lv.d.horizon - now.UnixNano()
|
||||
alarm := p.headroomAlarmLocked(volume, lv, headroom)
|
||||
grant := now.Add(p.workspaceTTL).UnixNano()
|
||||
clamped := grant > lv.d.horizon
|
||||
if clamped {
|
||||
@@ -190,12 +236,19 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
// its remaining validity; refuse with an error instead.
|
||||
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
|
||||
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
|
||||
summary := p.leaseStats.summaryDue(now)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(alarm)
|
||||
p.logLease(summary)
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if g := time.Unix(0, grant); g.After(lv.deadline) {
|
||||
lv.deadline = g
|
||||
}
|
||||
summary := p.leaseStats.observeGrant(now, headroom)
|
||||
if clamped {
|
||||
p.leaseStats.recordClamp(now)
|
||||
}
|
||||
var note string
|
||||
switch {
|
||||
case clamped && !lv.clamped:
|
||||
@@ -213,9 +266,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
}
|
||||
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}
|
||||
p.leaseMu.Unlock()
|
||||
if note != "" {
|
||||
log.Print(note)
|
||||
}
|
||||
p.logLease(alarm)
|
||||
p.logLease(note)
|
||||
p.logLease(summary)
|
||||
return l, nil
|
||||
}
|
||||
|
||||
@@ -305,9 +358,15 @@ func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, tr
|
||||
return
|
||||
}
|
||||
s.Lease.ExpiresAtNS = h
|
||||
start := time.Now()
|
||||
err := p.persistWorkspaceLocked(volume, s)
|
||||
took := time.Since(start).Round(time.Millisecond)
|
||||
write, wrote, err := p.persistWorkspaceTimedLocked(volume, s)
|
||||
if wrote {
|
||||
// The store write alone, failed or not, recorded when it returns
|
||||
// (completed-write telemetry; a blocked write is not seen until then).
|
||||
p.leaseMu.Lock()
|
||||
p.leaseStats.recordExtensionWrite(p.workspaceNow(), write)
|
||||
p.leaseMu.Unlock()
|
||||
}
|
||||
took := write.Round(time.Millisecond)
|
||||
if err != nil {
|
||||
if p.extendFailures[volume] == 0 {
|
||||
note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v",
|
||||
|
||||
@@ -17,6 +17,7 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -30,6 +31,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -78,6 +80,18 @@ type Config struct {
|
||||
FrontendPublicationRuntimeHTTP bool
|
||||
FrontendPublicationRuntimeListen string
|
||||
|
||||
// StrictJournalIsolation refuses nodes whose durable root shares the
|
||||
// authority store's file system (one journal): a co-located node that
|
||||
// serves no volume yet gets its heartbeats refused, and no new placement
|
||||
// or move targets a co-located node. A co-located node that already
|
||||
// serves volumes is only alarmed (refusing it would stop its lease
|
||||
// renewals). Off: alarm only.
|
||||
StrictJournalIsolation bool
|
||||
|
||||
// StatusListen, when non-empty, serves the read-only status endpoint
|
||||
// GET /status/workspace-lease on this loopback address.
|
||||
StatusListen string
|
||||
|
||||
// Logger is used for structured startup and error logging. If
|
||||
// nil, the default log package logger is used.
|
||||
Logger *log.Logger
|
||||
@@ -107,6 +121,9 @@ type Host struct {
|
||||
ln net.Listener
|
||||
frontendRuntimeLn net.Listener
|
||||
frontendRuntimeHTTP *http.Server
|
||||
statusLn net.Listener
|
||||
statusHTTP *http.Server
|
||||
journal *journalIsolation
|
||||
grpc *grpc.Server
|
||||
topo authority.AcceptedTopology
|
||||
lifecycle *LifecycleStores
|
||||
@@ -184,6 +201,9 @@ func New(cfg Config) (*Host, error) {
|
||||
if cfg.Listen == "" {
|
||||
return nil, fmt.Errorf("master.New: Listen is required")
|
||||
}
|
||||
if err := ValidateStatusListen(cfg.StatusListen); err != nil {
|
||||
return nil, fmt.Errorf("master.New: %w", err)
|
||||
}
|
||||
lg := cfg.Logger
|
||||
if lg == nil {
|
||||
lg = log.Default()
|
||||
@@ -205,11 +225,12 @@ func New(cfg Config) (*Host, error) {
|
||||
ctrl := authority.NewTopologyController(ctrlCfg, holder)
|
||||
|
||||
h := &Host{
|
||||
cfg: cfg,
|
||||
log: lg,
|
||||
ctrl: ctrl,
|
||||
topo: cfg.Topology,
|
||||
events: newEventRing(1024),
|
||||
cfg: cfg,
|
||||
log: lg,
|
||||
ctrl: ctrl,
|
||||
topo: cfg.Topology,
|
||||
events: newEventRing(1024),
|
||||
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
|
||||
}
|
||||
|
||||
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
|
||||
@@ -221,6 +242,10 @@ func New(cfg Config) (*Host, error) {
|
||||
return nil, fmt.Errorf("master.New: Bootstrap: %w", err)
|
||||
}
|
||||
holder.set(boot.Publisher)
|
||||
// Bootstrap creates a fresh store directory: sample its file system only
|
||||
// now, or a first start would compare against an unknown device forever.
|
||||
// An unknown identity (stat error, unsupported platform) never matches.
|
||||
h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir))
|
||||
|
||||
var sink authority.ControllerSink = ctrl
|
||||
if len(cfg.Topology.Volumes) == 0 {
|
||||
@@ -277,6 +302,23 @@ func New(cfg Config) (*Host, error) {
|
||||
h.frontendRuntimeHTTP = &http.Server{Handler: h.frontendPublicationRuntimeHandler()}
|
||||
}
|
||||
|
||||
if cfg.StatusListen != "" {
|
||||
statusLn, err := net.Listen("tcp", cfg.StatusListen)
|
||||
if err != nil {
|
||||
if h.frontendRuntimeLn != nil {
|
||||
_ = h.frontendRuntimeLn.Close()
|
||||
}
|
||||
_ = ln.Close()
|
||||
_ = boot.Close()
|
||||
return nil, fmt.Errorf("master.New: status listen %q: %w", cfg.StatusListen, err)
|
||||
}
|
||||
h.statusLn = statusLn
|
||||
// Every connection phase is bounded: a client that withholds a
|
||||
// declared body or never reads the reply is cut off.
|
||||
h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: statusReadTimeout, ReadTimeout: statusReadTimeout,
|
||||
WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout}
|
||||
}
|
||||
|
||||
grpcSrv := grpc.NewServer()
|
||||
svc := newServices(h)
|
||||
control.RegisterObservationServiceServer(grpcSrv, svc)
|
||||
@@ -293,6 +335,12 @@ func New(cfg Config) (*Host, error) {
|
||||
if h.frontendRuntimeLn != nil {
|
||||
lg.Printf("blockmaster: frontend publication runtime listen=%s", h.frontendRuntimeLn.Addr().String())
|
||||
}
|
||||
if h.statusLn != nil {
|
||||
lg.Printf("blockmaster: status listen=%s", h.statusLn.Addr().String())
|
||||
}
|
||||
if cfg.StrictJournalIsolation {
|
||||
lg.Printf("blockmaster: strict journal isolation: nodes sharing the authority store's file system are refused new work")
|
||||
}
|
||||
for _, e := range boot.ReloadSkips {
|
||||
lg.Printf("blockmaster: reload skip: %v", e)
|
||||
}
|
||||
@@ -344,6 +392,15 @@ func (h *Host) FrontendPublicationRuntimeAddr() string {
|
||||
return h.frontendRuntimeLn.Addr().String()
|
||||
}
|
||||
|
||||
// StatusAddr returns the bound status HTTP address, or empty when the status
|
||||
// endpoint is disabled.
|
||||
func (h *Host) StatusAddr() string {
|
||||
if h.statusLn == nil {
|
||||
return ""
|
||||
}
|
||||
return h.statusLn.Addr().String()
|
||||
}
|
||||
|
||||
// Publisher exposes the reloaded publisher for tests and for the
|
||||
// evidence-query path.
|
||||
func (h *Host) Publisher() *authority.Publisher {
|
||||
@@ -454,6 +511,16 @@ func (h *Host) Start() context.Context {
|
||||
}()
|
||||
}
|
||||
|
||||
if h.statusHTTP != nil && h.statusLn != nil {
|
||||
h.wg.Add(1)
|
||||
go func() {
|
||||
defer h.wg.Done()
|
||||
if err := h.statusHTTP.Serve(h.statusLn); err != nil && err != http.ErrServerClosed {
|
||||
h.log.Printf("blockmaster: status Serve: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return ctx
|
||||
}
|
||||
|
||||
@@ -466,6 +533,10 @@ func (h *Host) Close(ctx context.Context) error {
|
||||
if h.frontendRuntimeHTTP != nil {
|
||||
_ = h.frontendRuntimeHTTP.Shutdown(ctx)
|
||||
}
|
||||
var statusErr error
|
||||
if h.statusHTTP != nil {
|
||||
statusErr = h.closeStatusHTTP(ctx)
|
||||
}
|
||||
h.obs.Stop()
|
||||
|
||||
done := make(chan struct{})
|
||||
@@ -484,5 +555,29 @@ func (h *Host) Close(ctx context.Context) error {
|
||||
if h.boot != nil && h.boot.Publisher != nil {
|
||||
h.boot.Publisher.CloseWorkspaceExtenders()
|
||||
}
|
||||
return h.boot.Close()
|
||||
return errors.Join(statusErr, h.boot.Close())
|
||||
}
|
||||
|
||||
// Status endpoint connection bounds.
|
||||
const (
|
||||
statusReadTimeout = 5 * time.Second
|
||||
statusWriteTimeout = 5 * time.Second
|
||||
statusIdleTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// closeStatusHTTP shuts the status endpoint down gracefully until ctx ends,
|
||||
// then force-closes the connections still open (Shutdown leaves them). It
|
||||
// returns the force close's error, if any; an expired graceful shutdown that
|
||||
// the force close completed is only logged.
|
||||
func (h *Host) closeStatusHTTP(ctx context.Context) error {
|
||||
defer h.statusLn.Close() // a listener Start never served is not Shutdown's
|
||||
err := h.statusHTTP.Shutdown(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
h.log.Printf("blockmaster: status graceful shutdown: %v; closing its open connections", err)
|
||||
if cerr := h.statusHTTP.Close(); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
|
||||
return fmt.Errorf("status endpoint close: %w", cerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
)
|
||||
|
||||
// journalIsolation tracks nodes whose durable root shares the authority
|
||||
// store's file system. On one ext4 file system every fsync goes through one
|
||||
// jbd2 journal: a volume's WAL fsync storm delays the authority journal's
|
||||
// lease extensions, grants clamp to the durable horizon and leases run out.
|
||||
//
|
||||
// The colocated set is the latest heartbeat fact per server (memory only): a
|
||||
// node that moves its durable root off the store's file system leaves the set
|
||||
// on its next heartbeat. What a node serves is never read from here; that is
|
||||
// decided from durable state (nodeServesVolumes).
|
||||
type journalIsolation struct {
|
||||
mu sync.Mutex
|
||||
self storeident.Identity
|
||||
colocated map[string]storeident.Identity // server id -> its reported identity
|
||||
}
|
||||
|
||||
func newJournalIsolation(self storeident.Identity) *journalIsolation {
|
||||
return &journalIsolation{self: self, colocated: map[string]storeident.Identity{}}
|
||||
}
|
||||
|
||||
// observe records server's reported identity. It returns whether the node is
|
||||
// co-located and, on its first detection, the line to log.
|
||||
func (j *journalIsolation) observe(server string, id storeident.Identity) (bool, string) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
if !j.self.SameFileSystem(id) {
|
||||
delete(j.colocated, server)
|
||||
return false, ""
|
||||
}
|
||||
if _, seen := j.colocated[server]; seen {
|
||||
return true, ""
|
||||
}
|
||||
j.colocated[server] = id
|
||||
return true, fmt.Sprintf("blockmaster: node %s shares the authority store's file system (machine %s, dev %d): its fsyncs share the authority journal", server, id.MachineID, id.Dev)
|
||||
}
|
||||
|
||||
func (j *journalIsolation) isColocated(server string) bool {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
_, ok := j.colocated[server]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (j *journalIsolation) count() int {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
return len(j.colocated)
|
||||
}
|
||||
|
||||
func (j *journalIsolation) setSelf(id storeident.Identity) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
j.self = id
|
||||
}
|
||||
|
||||
// nodeServesVolumes reports whether durable state already gives server work:
|
||||
// a lifecycle placement slot on it, or a current authority line whose source
|
||||
// host (an issued move's target, the placement, or a static topology slot) is
|
||||
// it. Both survive a master restart, so a restart never turns a serving node
|
||||
// into a new one. A heartbeat must not wait behind a slow authority write: it
|
||||
// takes neither workspaceMu nor the publisher lock (held across authority
|
||||
// store writes), only the published authority lines and the lifecycle
|
||||
// stores, whose locks cover only their own file I/O.
|
||||
func (h *Host) nodeServesVolumes(server string) bool {
|
||||
lines := h.Publisher().PublishedAuthorityLines()
|
||||
if h.lifecycle != nil {
|
||||
for _, p := range h.lifecycle.Placements.ListPlacements() {
|
||||
for _, slot := range p.Slots {
|
||||
if slot.ServerID == server {
|
||||
return true // also every line a placement slot sources
|
||||
}
|
||||
}
|
||||
}
|
||||
for volume, line := range lines {
|
||||
if _, live := h.lifecycle.Volumes.GetVolumeSnapshot(volume); live && line.IssuedHost == server {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range h.topo.Volumes {
|
||||
line, ok := lines[v.VolumeID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, slot := range v.Slots {
|
||||
if slot.ServerID == server && slot.ReplicaID == line.ReplicaID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// refuseColocatedHeartbeat is the strict heartbeat rule: a co-located node
|
||||
// that serves nothing yet is refused; a serving one is only alarmed.
|
||||
func (h *Host) refuseColocatedHeartbeat(server string, id storeident.Identity) error {
|
||||
colocated, note := h.journal.observe(server, id)
|
||||
if note != "" {
|
||||
h.log.Print(note)
|
||||
}
|
||||
if !colocated || !h.cfg.StrictJournalIsolation || h.nodeServesVolumes(server) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("heartbeat: node %s shares the authority store's file system (machine %s, dev %d) and serves no volume; strict journal isolation refuses it", server, id.MachineID, id.Dev)
|
||||
}
|
||||
|
||||
// colocatedTargetRefused reports whether strict isolation refuses new work
|
||||
// (a placement or move target) on server.
|
||||
func (h *Host) colocatedTargetRefused(server string) bool {
|
||||
return h.cfg.StrictJournalIsolation && h.journal.isColocated(server)
|
||||
}
|
||||
|
||||
// reconcilePlacements runs the product loop's placement reconcile. Under
|
||||
// strict isolation each volume plans against the nodes without co-located
|
||||
// ones, except the nodes its existing placement already names: a placement
|
||||
// on a co-located node is kept (re-planning it away would move a serving
|
||||
// volume), and no new placement chooses a co-located node.
|
||||
func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.NodeRegistration) []lifecycle.ReconcileResult {
|
||||
if !h.cfg.StrictJournalIsolation {
|
||||
return lifecycle.ReconcilePlacement(stores.liveVolumes(), nodes, stores.Placements)
|
||||
}
|
||||
var out []lifecycle.ReconcileResult
|
||||
for _, v := range stores.liveVolumes() {
|
||||
placed := map[string]bool{}
|
||||
if p, ok := stores.Placements.GetPlacement(v.Spec.VolumeID); ok {
|
||||
for _, slot := range p.Slots {
|
||||
placed[slot.ServerID] = true
|
||||
}
|
||||
}
|
||||
allowed := make([]lifecycle.NodeRegistration, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
if placed[n.ServerID] || !h.journal.isColocated(n.ServerID) {
|
||||
allowed = append(allowed, n)
|
||||
}
|
||||
}
|
||||
out = append(out, lifecycle.ReconcilePlacement([]lifecycle.VolumeRecord{v}, allowed, stores.Placements)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ValidateStatusListen accepts "" (disabled) or a loopback host:port
|
||||
// (127.0.0.0/8, ::1, localhost). The status endpoint is unauthenticated.
|
||||
func ValidateStatusListen(addr string) error {
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--status-listen %q: %v", addr, err)
|
||||
}
|
||||
if host == "localhost" {
|
||||
return nil
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("--status-listen %q must be a loopback address (127.0.0.0/8, ::1 or localhost)", addr)
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStatus is the GET /status/workspace-lease body.
|
||||
type WorkspaceLeaseStatus struct {
|
||||
ColocatedNodes int `json:"colocated_nodes"`
|
||||
HeadroomAlarms uint64 `json:"headroom_alarms"`
|
||||
ClampsTotal uint64 `json:"clamps_total"`
|
||||
ClampsLastMinute uint64 `json:"clamps_last_minute"`
|
||||
MinHeadroomMS int64 `json:"min_headroom_ms"` // -1: no grant observed yet
|
||||
StrictJournalIsolation bool `json:"strict_journal_isolation"`
|
||||
// Lease extension store write latency, the earliest lag signal.
|
||||
ExtensionWriteLastMS int64 `json:"extension_write_last_ms"` // -1: no extension write yet
|
||||
ExtensionWriteMaxLastMinuteMS int64 `json:"extension_write_max_last_minute_ms"` // -1: none in the last minute
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStatus returns the journal-isolation and lease headroom
|
||||
// counters served by the status endpoint.
|
||||
func (h *Host) WorkspaceLeaseStatus() WorkspaceLeaseStatus {
|
||||
st := WorkspaceLeaseStatus{ColocatedNodes: h.journal.count(), MinHeadroomMS: -1, StrictJournalIsolation: h.cfg.StrictJournalIsolation,
|
||||
ExtensionWriteLastMS: -1, ExtensionWriteMaxLastMinuteMS: -1}
|
||||
if p := h.Publisher(); p != nil {
|
||||
s := p.WorkspaceLeaseStats()
|
||||
st.HeadroomAlarms, st.ClampsTotal, st.ClampsLastMinute = s.HeadroomAlarms, s.ClampsTotal, s.ClampsLastMinute
|
||||
if s.MinHeadroomObserved {
|
||||
st.MinHeadroomMS = s.MinHeadroom.Milliseconds()
|
||||
}
|
||||
if s.ExtensionWriteObserved {
|
||||
st.ExtensionWriteLastMS = s.ExtensionWriteLast.Milliseconds()
|
||||
}
|
||||
if s.ExtensionWriteInLastMinute {
|
||||
st.ExtensionWriteMaxLastMinuteMS = s.ExtensionWriteMaxLastMinute.Milliseconds()
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func (h *Host) statusHandler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/status/workspace-lease", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(h.WorkspaceLeaseStatus())
|
||||
})
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const colocatedMoveRefusal = `move target node "node-b" shares the authority store's file system (strict journal isolation)`
|
||||
|
||||
// issueMove serves vol from node-a at epoch 1 and moves it cleanly to node-b
|
||||
// through the Workspace RPC. It returns the request and its grant.
|
||||
func (r *isolationRig) issueMove(t *testing.T, vol, requestID string) (*control.WorkspaceMove, *control.WorkspaceGrant) {
|
||||
t.Helper()
|
||||
r.createVolume(t, vol)
|
||||
r.place(t, vol, "node-a")
|
||||
if err := r.m.ObservationHost().Ingest(authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(),
|
||||
Slots: []authority.SlotFact{{VolumeID: vol, ReplicaID: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, r.m.Publisher(), vol)
|
||||
if line.Epoch != 1 || line.ReplicaID != "r1" {
|
||||
t.Fatalf("fixture authority line: %+v", line)
|
||||
}
|
||||
id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: 1}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RevokeWorkspace(r.ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := &control.WorkspaceMove{RequestId: requestID, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}
|
||||
grant, err := r.ws.MoveWorkspace(r.ctx, q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !grant.Issued || grant.NewEpoch != 2 || grant.NewHost != "node-b" {
|
||||
t.Fatalf("fixture grant: %+v", grant)
|
||||
}
|
||||
return q, grant
|
||||
}
|
||||
|
||||
// Strict isolation refuses new work, never an issued decision: a move issued
|
||||
// to node-b before node-b reported its identity, whose reply was lost, is
|
||||
// retried after node-b turned out co-located. The SAME request gets the
|
||||
// identical durable grant (no new epoch, no second record); a new request id
|
||||
// or a changed body to node-b is refused for co-location. Also after a
|
||||
// master restart, whose co-located set starts empty.
|
||||
func TestStrictReplaysAnIssuedMoveToANowColocatedTarget(t *testing.T) {
|
||||
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
|
||||
r := newIsolationRig(t, true, authorityDir, lifecycleDir)
|
||||
q, issued := r.issueMove(t, "moved", "m1") // the caller never sees this reply
|
||||
check := func(r *isolationRig, what string) {
|
||||
t.Helper()
|
||||
if err := r.heartbeat("node-b", masterStore); err != nil {
|
||||
t.Fatalf("%s: the issued move's target was refused: %v", what, err)
|
||||
}
|
||||
if !r.m.colocatedTargetRefused("node-b") {
|
||||
t.Fatalf("%s: node-b not recorded as co-located", what)
|
||||
}
|
||||
before, _ := r.m.Publisher().VolumeAuthorityLine("moved")
|
||||
again, err := r.ws.MoveWorkspace(r.ctx, q)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: retry of the issued request: %v, want its durable grant", what, err)
|
||||
}
|
||||
if !proto.Equal(again, issued) {
|
||||
t.Fatalf("%s: retry returned %+v, want the issued grant %+v", what, again, issued)
|
||||
}
|
||||
after, _ := r.m.Publisher().VolumeAuthorityLine("moved")
|
||||
if after != before || after.Epoch != issued.NewEpoch {
|
||||
t.Fatalf("%s: retry published again: line %+v -> %+v", what, before, after)
|
||||
}
|
||||
if st := r.m.Publisher().WorkspaceState("moved"); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued {
|
||||
t.Fatalf("%s: move journal after the retry: %+v", what, st)
|
||||
}
|
||||
fresh := proto.Clone(q).(*control.WorkspaceMove)
|
||||
fresh.RequestId = "m2"
|
||||
changed := proto.Clone(q).(*control.WorkspaceMove)
|
||||
changed.Kind, changed.Force = "forced", true
|
||||
for name, m := range map[string]*control.WorkspaceMove{"new request id": fresh, "same id, changed body": changed} {
|
||||
_, err := r.ws.MoveWorkspace(r.ctx, m)
|
||||
if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != colocatedMoveRefusal {
|
||||
t.Fatalf("%s: %s to the co-located node: %v, want %q", what, name, err, colocatedMoveRefusal)
|
||||
}
|
||||
}
|
||||
if final, _ := r.m.Publisher().VolumeAuthorityLine("moved"); final != before {
|
||||
t.Fatalf("%s: a refused request changed authority: %+v -> %+v", what, before, final)
|
||||
}
|
||||
}
|
||||
check(r, "live master")
|
||||
r.close(t)
|
||||
check(newIsolationRig(t, true, authorityDir, lifecycleDir), "restarted master")
|
||||
}
|
||||
|
||||
// The recorded placement repeated after its node turned out co-located keeps
|
||||
// its idempotent result; a different placement on that node is refused.
|
||||
func TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
r.createVolume(t, "fresh")
|
||||
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
place := &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"}
|
||||
if _, err := r.ws.PlaceWorkspace(r.ctx, place); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.heartbeat("node-b", masterStore); err != nil {
|
||||
t.Fatalf("the placed node was refused: %v", err)
|
||||
}
|
||||
if !r.m.colocatedTargetRefused("node-b") {
|
||||
t.Fatal("node-b not recorded as co-located")
|
||||
}
|
||||
if _, err := r.ws.PlaceWorkspace(r.ctx, place); err != nil {
|
||||
t.Fatalf("repeating the recorded placement: %v, want its idempotent result", err)
|
||||
}
|
||||
_, err := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r2"})
|
||||
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("a different placement on the co-located node: %v, want a co-location refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
// On a first start the authority store directory does not exist before
|
||||
// Bootstrap creates it. The master must sample the created directory: a
|
||||
// heartbeat carrying that file system's identity is co-located (alarm by
|
||||
// default, refusal under strict) without any test override.
|
||||
func TestFirstStartSamplesTheCreatedAuthorityStore(t *testing.T) {
|
||||
for _, strict := range []bool{false, true} {
|
||||
t.Run(map[bool]string{true: "strict", false: "default"}[strict], func(t *testing.T) {
|
||||
authorityDir := filepath.Join(t.TempDir(), "authority") // created by Bootstrap
|
||||
r := startIsolationRig(t, strict, authorityDir, t.TempDir(), nil)
|
||||
self := storeident.Of(authorityDir)
|
||||
if !self.Known() {
|
||||
t.Skip("file system identity is unknown on this platform")
|
||||
}
|
||||
err := r.heartbeat("node-a", self)
|
||||
if strict {
|
||||
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("strict heartbeat on the fresh store's file system: %v, want a co-location refusal", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("default heartbeat refused: %v", err)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), "node node-a "+colocatedLine) || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatalf("co-located node on the fresh store not detected:\n%s", r.logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A heartbeat never waits on the publisher lock, which writers hold across
|
||||
// durable writes: with a write held under that lock, the heartbeat of an
|
||||
// issued move's target (serving only through that move) completes at once,
|
||||
// and a co-located node that serves nothing is still refused at once.
|
||||
func TestStrictServingHeartbeatDoesNotWaitOnAHeldAuthorityWrite(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
r.issueMove(t, "moved", "m1")
|
||||
if p, _ := r.m.Lifecycle().Placements.GetPlacement("moved"); len(p.Slots) != 1 || p.Slots[0].ServerID != "node-a" {
|
||||
t.Fatalf("fixture: node-b must serve through the issued move only: %+v", p)
|
||||
}
|
||||
r.createVolume(t, "held")
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
held := make(chan error, 1)
|
||||
// RecordWorkspacePlacement holds the publisher lock across its durable
|
||||
// write, as an extension does across its authority fsync.
|
||||
go func() {
|
||||
held <- r.m.Publisher().RecordWorkspacePlacement(r.ctx, "held", func() error {
|
||||
close(entered)
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
var beats sync.WaitGroup
|
||||
t.Cleanup(func() { // release first, then join every worker
|
||||
releaseOnce.Do(func() { close(release) })
|
||||
select {
|
||||
case <-held:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("held write did not settle")
|
||||
}
|
||||
beats.Wait()
|
||||
})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("the held write never started")
|
||||
}
|
||||
beat := func(server string) error {
|
||||
t.Helper()
|
||||
done := make(chan error, 1)
|
||||
start := time.Now()
|
||||
beats.Add(1)
|
||||
go func() { defer beats.Done(); done <- r.heartbeat(server, masterStore) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Logf("heartbeat of %s took %s with the authority write held", server, time.Since(start).Round(time.Millisecond))
|
||||
return err
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("heartbeat of %s still blocked %s behind the held authority write", server, time.Since(start).Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := beat("node-b"); err != nil {
|
||||
t.Fatalf("serving co-located node refused: %v", err)
|
||||
}
|
||||
if err := beat("node-c"); status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("idle co-located node: %v, want a co-location refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
// stalledStatusRequest opens a connection to the status endpoint and sends a
|
||||
// request whose declared body never comes.
|
||||
func stalledStatusRequest(t *testing.T, addr string) net.Conn {
|
||||
t.Helper()
|
||||
conn, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
if _, err := fmt.Fprintf(conn, "POST /status/workspace-lease HTTP/1.1\r\nHost: status\r\nContent-Length: 100\r\n\r\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
// readUntilClosed reads conn until the server closes it; it fails the test
|
||||
// when the connection is still open at deadline.
|
||||
func readUntilClosed(t *testing.T, conn net.Conn, deadline time.Time, what string) {
|
||||
t.Helper()
|
||||
if err := conn.SetReadDeadline(deadline); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := io.Copy(io.Discard, conn)
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() {
|
||||
t.Fatalf("%s: the stalled status connection was still open at the deadline", what)
|
||||
}
|
||||
}
|
||||
|
||||
// A status client that declares a body and never sends it is cut off by the
|
||||
// read bound, not held open forever.
|
||||
func TestStatusEndpointCutsOffAStalledBody(t *testing.T) {
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: "127.0.0.1:0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
start := time.Now()
|
||||
conn := stalledStatusRequest(t, m.StatusAddr())
|
||||
readUntilClosed(t, conn, start.Add(statusReadTimeout+3*time.Second), "read bound")
|
||||
t.Logf("stalled body cut off after %s (bound %s)", time.Since(start).Round(time.Millisecond), statusReadTimeout)
|
||||
}
|
||||
|
||||
// When graceful shutdown runs out, Close force-closes the status connections
|
||||
// still open, long before their read bound would.
|
||||
func TestHostCloseForceClosesAStalledStatusConnection(t *testing.T) {
|
||||
logs := &syncBuffer{}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: "127.0.0.1:0", Logger: log.New(logs, "", 0)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
conn := stalledStatusRequest(t, m.StatusAddr())
|
||||
time.Sleep(200 * time.Millisecond) // the server has read the headers: the connection is active
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
if err := m.Close(ctx); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
readUntilClosed(t, conn, start.Add(2*time.Second), "Close")
|
||||
if took := time.Since(start); took >= statusReadTimeout-time.Second {
|
||||
t.Fatalf("connection closed after %s: that is the read bound, not Close", took)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "status graceful shutdown") {
|
||||
t.Fatalf("expired graceful shutdown not logged:\n%s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The status endpoint carries the extension write latency: -1 before any
|
||||
// extension, then the measured write once a renewal past 1.25 TTL of
|
||||
// headroom (7.5 s after the first grant, TTL 30 s) has started one.
|
||||
func TestStatusReportsExtensionWriteLatency(t *testing.T) {
|
||||
h, c, _ := reviewBindingHost(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
reviewLegacyBind(t, h, c, ctx, "vol-b")
|
||||
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
|
||||
svc := &services{host: h}
|
||||
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
|
||||
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
|
||||
t.Fatal(err) // first grant: not an extension
|
||||
}
|
||||
get := func() map[string]any {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
h.statusHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/status/workspace-lease", nil))
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
if b := get(); b["extension_write_last_ms"] != float64(-1) || b["extension_write_max_last_minute_ms"] != float64(-1) {
|
||||
t.Fatalf("before any extension: %v", b)
|
||||
}
|
||||
time.Sleep(8 * time.Second)
|
||||
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) {
|
||||
b := get()
|
||||
last, _ := b["extension_write_last_ms"].(float64)
|
||||
max, _ := b["extension_write_max_last_minute_ms"].(float64)
|
||||
if last >= 0 && max >= last {
|
||||
t.Logf("extension write: last %v ms, max in the last minute %v ms", last, max)
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("no extension write reported: %v", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With a known file system id on both sides, machine id + device alone no
|
||||
// longer make a node co-located: a different fsid is another file system.
|
||||
// The same three facts are co-located; a heartbeat without an fsid (an older
|
||||
// volume binary) falls back to machine id + device.
|
||||
func TestColocationComparesFSIDWhenBothSidesKnowIt(t *testing.T) {
|
||||
self := storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0x1111}
|
||||
r := startIsolationRig(t, false, t.TempDir(), t.TempDir(), &self)
|
||||
for _, c := range []struct {
|
||||
server string
|
||||
id storeident.Identity
|
||||
want bool
|
||||
}{
|
||||
{"node-a", storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0x2222}, false},
|
||||
{"node-b", storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0x1111}, true},
|
||||
{"node-c", storeident.Identity{MachineID: "machine-1", Dev: 2049}, true},
|
||||
} {
|
||||
if err := r.heartbeat(c.server, c.id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.Contains(r.logs.String(), "node "+c.server+" "+colocatedLine); got != c.want {
|
||||
t.Fatalf("%s reporting %+v: co-located alarm = %v, want %v\n%s", c.server, c.id, got, c.want, r.logs.String())
|
||||
}
|
||||
}
|
||||
if n := r.m.WorkspaceLeaseStatus().ColocatedNodes; n != 2 {
|
||||
t.Fatalf("colocated_nodes = %d, want 2", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// masterStore is the identity the tests give the master's authority store
|
||||
// (the real one is platform-dependent: unknown on Windows).
|
||||
var masterStore = storeident.Identity{MachineID: "machine-1", Dev: 2049}
|
||||
|
||||
const colocatedLine = "shares the authority store's file system"
|
||||
|
||||
type isolationRig struct {
|
||||
m *Host
|
||||
logs *syncBuffer
|
||||
ws control.WorkspaceServiceClient
|
||||
lc control.LifecycleServiceClient
|
||||
obs control.ObservationServiceClient
|
||||
ctx context.Context
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newIsolationRig(t *testing.T, strict bool, authorityDir, lifecycleDir string) *isolationRig {
|
||||
t.Helper()
|
||||
return startIsolationRig(t, strict, authorityDir, lifecycleDir, &masterStore)
|
||||
}
|
||||
|
||||
// startIsolationRig starts the rig's master; self, when not nil, replaces the
|
||||
// identity the master sampled from its authority store.
|
||||
func startIsolationRig(t *testing.T, strict bool, authorityDir, lifecycleDir string, self *storeident.Identity) *isolationRig {
|
||||
t.Helper()
|
||||
logs := &syncBuffer{}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true,
|
||||
StrictJournalIsolation: strict, Logger: log.New(logs, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if self != nil {
|
||||
m.journal.setSelf(*self) // before Start: no RPC has run yet
|
||||
}
|
||||
m.Start()
|
||||
r := &isolationRig{m: m, logs: logs}
|
||||
t.Cleanup(func() {
|
||||
if !r.closed {
|
||||
closeTestMaster(t, m)
|
||||
}
|
||||
})
|
||||
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
for _, n := range []lifecycle.NodeRegistration{
|
||||
{ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"},
|
||||
{ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"},
|
||||
} {
|
||||
if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r.ws, r.lc, r.obs, r.ctx = control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn), control.NewObservationServiceClient(conn), ctx
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *isolationRig) close(t *testing.T) {
|
||||
t.Helper()
|
||||
r.closed = true
|
||||
closeTestMaster(t, r.m)
|
||||
}
|
||||
|
||||
var hbPorts = map[string][2]string{
|
||||
"node-a": {"127.0.0.1:19111", "127.0.0.1:19112"},
|
||||
"node-b": {"127.0.0.1:19311", "127.0.0.1:19312"},
|
||||
"node-c": {"127.0.0.1:19511", "127.0.0.1:19512"},
|
||||
}
|
||||
|
||||
func (r *isolationRig) heartbeat(server string, id storeident.Identity) error {
|
||||
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
MachineId: id.MachineID, DurableRootDev: id.Dev, DurableRootFsid: id.FSID,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-" + server, ReplicaId: "r-" + server, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1]}}})
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *isolationRig) createVolume(t *testing.T, vol string) {
|
||||
t.Helper()
|
||||
if _, err := r.lc.CreateVolume(r.ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *isolationRig) place(t *testing.T, vol, server string) {
|
||||
t.Helper()
|
||||
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1,
|
||||
Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Default (not strict): a node on the authority store's file system is
|
||||
// alarmed once and counted, and its heartbeats are accepted. A different
|
||||
// device, or a different machine with the same device number, is silent.
|
||||
func TestColocatedNodeIsAlarmedButAcceptedByDefault(t *testing.T) {
|
||||
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := r.heartbeat("node-a", masterStore); err != nil {
|
||||
t.Fatalf("heartbeat %d of the co-located node refused without strict isolation: %v", i, err)
|
||||
}
|
||||
}
|
||||
want := "blockmaster: node node-a shares the authority store's file system (machine machine-1, dev 2049): its fsyncs share the authority journal"
|
||||
if n := strings.Count(r.logs.String(), want); n != 1 {
|
||||
t.Fatalf("alarm logged %d times, want once:\n%s", n, r.logs.String())
|
||||
}
|
||||
if got := r.m.WorkspaceLeaseStatus().ColocatedNodes; got != 1 {
|
||||
t.Fatalf("colocated_nodes = %d, want 1", got)
|
||||
}
|
||||
for _, id := range []storeident.Identity{
|
||||
{MachineID: "machine-1", Dev: 2050}, // same machine, other file system
|
||||
{MachineID: "machine-2", Dev: 2049}, // same device number, other machine
|
||||
{}, // unknown
|
||||
} {
|
||||
if err := r.heartbeat("node-b", id); err != nil {
|
||||
t.Fatalf("heartbeat %+v: %v", id, err)
|
||||
}
|
||||
}
|
||||
if strings.Contains(r.logs.String(), "node node-b "+colocatedLine) {
|
||||
t.Fatalf("node-b alarmed:\n%s", r.logs.String())
|
||||
}
|
||||
if got := r.m.WorkspaceLeaseStatus().ColocatedNodes; got != 1 {
|
||||
t.Fatalf("colocated_nodes = %d after silent nodes, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A node that moves its durable root off the authority store's file system
|
||||
// leaves the co-located set on its next heartbeat: strict isolation accepts
|
||||
// it again and no longer refuses new work on it.
|
||||
func TestColocatedNodeLeavesTheSetWhenItMovesOff(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
if err := r.heartbeat("node-a", masterStore); status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("strict heartbeat of a co-located new node: %v, want FailedPrecondition", err)
|
||||
}
|
||||
if !r.m.colocatedTargetRefused("node-a") || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatal("co-located node not recorded")
|
||||
}
|
||||
if err := r.heartbeat("node-a", storeident.Identity{MachineID: "machine-1", Dev: 2050}); err != nil {
|
||||
t.Fatalf("strict refused the node after it moved off the store's file system: %v", err)
|
||||
}
|
||||
if r.m.colocatedTargetRefused("node-a") || r.m.WorkspaceLeaseStatus().ColocatedNodes != 0 {
|
||||
t.Fatal("node still counted as co-located after it moved off")
|
||||
}
|
||||
}
|
||||
|
||||
// Strict: a co-located node that serves no volume is refused
|
||||
// (FailedPrecondition) and still alarmed; a node elsewhere is accepted.
|
||||
func TestStrictRefusesColocatedNodeWithoutVolumes(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
err := r.heartbeat("node-a", masterStore)
|
||||
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("strict heartbeat of a co-located new node: %v, want FailedPrecondition naming the shared file system", err)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), "node node-a "+colocatedLine) || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatalf("refused node not alarmed/counted:\n%s", r.logs.String())
|
||||
}
|
||||
if err := r.heartbeat("node-b", storeident.Identity{MachineID: "machine-1", Dev: 2050}); err != nil {
|
||||
t.Fatalf("strict refused a node on another file system: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strict: a co-located node that already serves a volume keeps getting its
|
||||
// heartbeats accepted (alarm only), also after a master restart: "serves" is
|
||||
// read from durable state, not from what this process has seen.
|
||||
func TestStrictAcceptsColocatedNodeThatAlreadyServes(t *testing.T) {
|
||||
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
|
||||
r := newIsolationRig(t, true, authorityDir, lifecycleDir)
|
||||
r.createVolume(t, "placed")
|
||||
r.place(t, "placed", "node-a")
|
||||
if err := r.heartbeat("node-a", masterStore); err != nil {
|
||||
t.Fatalf("strict refused a co-located node that serves a volume: %v", err)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), "node node-a "+colocatedLine) || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatalf("serving co-located node not alarmed:\n%s", r.logs.String())
|
||||
}
|
||||
r.close(t)
|
||||
|
||||
again := newIsolationRig(t, true, authorityDir, lifecycleDir)
|
||||
if err := again.heartbeat("node-a", masterStore); err != nil {
|
||||
t.Fatalf("after a master restart, strict refused the serving co-located node: %v", err)
|
||||
}
|
||||
if !strings.Contains(again.logs.String(), "node node-a "+colocatedLine) {
|
||||
t.Fatalf("restarted master did not alarm:\n%s", again.logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Strict refuses a new placement or move onto a co-located node; without
|
||||
// strict neither is refused for that reason.
|
||||
func TestStrictRefusesPlacementAndMoveOntoColocatedNode(t *testing.T) {
|
||||
for _, strict := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "strict", false: "default"}[strict], func(t *testing.T) {
|
||||
r := newIsolationRig(t, strict, t.TempDir(), t.TempDir())
|
||||
_ = r.heartbeat("node-b", masterStore) // strict refuses it (no volume); both modes record it
|
||||
if r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatal("node-b not recorded as co-located")
|
||||
}
|
||||
r.createVolume(t, "placed")
|
||||
r.place(t, "placed", "node-a")
|
||||
r.createVolume(t, "fresh")
|
||||
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, placeErr := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"})
|
||||
_, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
|
||||
if strict {
|
||||
if status.Code(placeErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(placeErr).Message(), colocatedLine) {
|
||||
t.Fatalf("strict PlaceWorkspace onto a co-located node: %v", placeErr)
|
||||
}
|
||||
if _, ok := r.m.Lifecycle().Placements.GetPlacement("fresh"); ok {
|
||||
t.Fatal("refused placement was recorded")
|
||||
}
|
||||
want := `move target node "node-b" shares the authority store's file system (strict journal isolation)`
|
||||
if status.Code(moveErr) != codes.FailedPrecondition || status.Convert(moveErr).Message() != want {
|
||||
t.Fatalf("strict MoveWorkspace onto a co-located node: %v, want %q", moveErr, want)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), `MoveWorkspace refused volume="placed" request="m1": `+want) {
|
||||
t.Fatalf("move refusal not logged:\n%s", r.logs.String())
|
||||
}
|
||||
return
|
||||
}
|
||||
if placeErr != nil {
|
||||
t.Fatalf("default PlaceWorkspace onto a co-located node refused: %v", placeErr)
|
||||
}
|
||||
if moveErr != nil && strings.Contains(moveErr.Error(), colocatedLine) {
|
||||
t.Fatalf("default MoveWorkspace refused for co-location: %v", moveErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Strict: the product loop never creates a new placement on a co-located
|
||||
// node (the only node with capacity here); without strict it does.
|
||||
func TestStrictProductLoopSkipsColocatedNodeForNewPlacement(t *testing.T) {
|
||||
for _, strict := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "strict", false: "default"}[strict], func(t *testing.T) {
|
||||
r := newIsolationRig(t, strict, t.TempDir(), t.TempDir())
|
||||
if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-c", DataAddr: "127.0.0.1:19501", CtrlAddr: "127.0.0.1:19502",
|
||||
Pools: []lifecycle.StoragePool{{PoolID: "p1", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = r.heartbeat("node-c", masterStore)
|
||||
r.createVolume(t, "auto")
|
||||
if _, err := r.m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, ok := r.m.Lifecycle().Placements.GetPlacement("auto")
|
||||
if strict && ok {
|
||||
t.Fatalf("strict product loop placed a new volume on the co-located node: %+v", p)
|
||||
}
|
||||
if !strict && (!ok || p.Slots[0].ServerID != "node-c") {
|
||||
t.Fatalf("default product loop did not place on node-c: %+v ok=%v", p, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The status endpoint is loopback-only and serves the counters as JSON.
|
||||
func TestStatusEndpointLoopbackOnlyAndServesJSON(t *testing.T) {
|
||||
for _, bad := range []string{"0.0.0.0:9335", ":9335", "10.0.0.5:9335", "[::]:9335", "example.com:9335"} {
|
||||
if err := ValidateStatusListen(bad); err == nil {
|
||||
t.Fatalf("ValidateStatusListen(%q) accepted a non-loopback address", bad)
|
||||
}
|
||||
if _, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: bad}); err == nil || !strings.Contains(err.Error(), "loopback") {
|
||||
t.Fatalf("master.New with --status-listen %q: %v, want a loopback refusal", bad, err)
|
||||
}
|
||||
}
|
||||
for _, ok := range []string{"", "127.0.0.1:9335", "127.1.2.3:0", "[::1]:9335", "localhost:9335"} {
|
||||
if err := ValidateStatusListen(ok); err != nil {
|
||||
t.Fatalf("ValidateStatusListen(%q): %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: "127.0.0.1:0", StrictJournalIsolation: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
resp, err := http.Get("http://" + m.StatusAddr() + "/status/workspace-lease")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "application/json" {
|
||||
t.Fatalf("status %d content-type %q", resp.StatusCode, resp.Header.Get("Content-Type"))
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range []string{"colocated_nodes", "headroom_alarms", "clamps_total", "clamps_last_minute", "min_headroom_ms", "strict_journal_isolation",
|
||||
"extension_write_last_ms", "extension_write_max_last_minute_ms"} {
|
||||
if _, ok := body[k]; !ok {
|
||||
t.Fatalf("status JSON lacks %q: %v", k, body)
|
||||
}
|
||||
}
|
||||
if body["strict_journal_isolation"] != true || body["colocated_nodes"] != float64(0) || body["min_headroom_ms"] != float64(-1) ||
|
||||
body["extension_write_last_ms"] != float64(-1) || body["extension_write_max_last_minute_ms"] != float64(-1) {
|
||||
t.Fatalf("status JSON values: %v", body)
|
||||
}
|
||||
if post, err := http.Post("http://"+m.StatusAddr()+"/status/workspace-lease", "application/json", nil); err != nil || post.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("POST: %v %v", post, err)
|
||||
} else {
|
||||
post.Body.Close()
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,9 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) {
|
||||
return LifecycleProductTickResult{}, nil
|
||||
}
|
||||
nodes := stores.Nodes.ListNodes()
|
||||
reconciled := lifecycle.ReconcilePlacement(stores.liveVolumes(), nodes, stores.Placements)
|
||||
// New placements never choose a co-located node under strict journal
|
||||
// isolation; existing placements still verify against every node.
|
||||
reconciled := h.reconcilePlacements(stores, nodes)
|
||||
placements := stores.Placements.ListPlacements()
|
||||
verified := h.verifyPlacements(placements, nodes)
|
||||
result := LifecycleProductTickResult{
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
@@ -285,6 +286,12 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
|
||||
if err := validateHeartbeat(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Journal isolation: alarm on a durable root sharing the authority
|
||||
// store's file system; under strict isolation refuse it unless the node
|
||||
// already serves volumes (refusing a serving node stops its renewals).
|
||||
if err := s.host.refuseColocatedHeartbeat(r.ServerId, storeident.Identity{MachineID: r.GetMachineId(), Dev: r.GetDurableRootDev(), FSID: r.GetDurableRootFsid()}); err != nil {
|
||||
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
||||
}
|
||||
msg := heartbeatFromWire(r)
|
||||
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
|
||||
return nil, fmt.Errorf("ingest: %w", err)
|
||||
|
||||
@@ -136,9 +136,17 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace
|
||||
if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok {
|
||||
return nil, workspaceError(fmt.Errorf("workspace placement: unknown server"))
|
||||
}
|
||||
identical := func(p lifecycle.PlacementIntent) bool {
|
||||
return len(p.Slots) == 1 && p.Slots[0].ServerID == binding.ServerID && p.Slots[0].ReplicaID == q.GetReplicaId() && p.Slots[0].DataAddr == binding.DataAddr && p.Slots[0].CtrlAddr == binding.CtrlAddr
|
||||
}
|
||||
// Strict journal isolation refuses new work only: repeating the
|
||||
// recorded placement keeps its idempotent result.
|
||||
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); !(ok && identical(p)) && s.host.colocatedTargetRefused(binding.ServerID) {
|
||||
return nil, workspaceError(fmt.Errorf("workspace placement: node %q shares the authority store's file system (strict journal isolation)", binding.ServerID))
|
||||
}
|
||||
err = s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error {
|
||||
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok {
|
||||
if len(p.Slots) == 1 && p.Slots[0].ServerID == binding.ServerID && p.Slots[0].ReplicaID == q.GetReplicaId() && p.Slots[0].DataAddr == binding.DataAddr && p.Slots[0].CtrlAddr == binding.CtrlAddr {
|
||||
if identical(p) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("workspace placement: existing intent differs")
|
||||
|
||||
@@ -189,6 +189,12 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
req := authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID,
|
||||
ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()}
|
||||
// Strict journal isolation refuses new work only: an exact replay of an
|
||||
// issued move (its reply lost, the target found co-located since) gets
|
||||
// its durable grant back from MoveWorkspace, never a definite refusal.
|
||||
replay := ok && s.host.Publisher().IssuedWorkspaceMove(req)
|
||||
switch {
|
||||
case endpointErr != nil:
|
||||
refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr)
|
||||
@@ -198,6 +204,8 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId())
|
||||
case target.ServerID == oldHost:
|
||||
refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID)
|
||||
case !replay && s.host.colocatedTargetRefused(target.ServerID):
|
||||
refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
|
||||
case !matched:
|
||||
refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
|
||||
}
|
||||
@@ -207,8 +215,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
r, err := s.host.Publisher().MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID,
|
||||
ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()}, head)
|
||||
r, err := s.host.Publisher().MoveWorkspace(ctx, req, head)
|
||||
if err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
|
||||
@@ -162,4 +162,17 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
|
||||
if state := restarted.Publisher().WorkspaceState("vol-a"); state == nil || len(state.Moves) != 1 || !state.Moves[0].Issued {
|
||||
t.Fatal(state)
|
||||
}
|
||||
// Journal isolation reads "serves" from durable state: the issued move's
|
||||
// target serves vol-a through its authority line alone (the placement
|
||||
// still names the old node), also on a restarted master.
|
||||
if p, ok := restarted.Lifecycle().Placements.GetPlacement("vol-a"); ok {
|
||||
for _, slot := range p.Slots {
|
||||
if slot.ServerID == "node-b" {
|
||||
t.Fatalf("placement already names the move target: %+v", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !restarted.nodeServesVolumes("node-b") {
|
||||
t.Fatal("the issued move's target does not count as serving vol-a")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -72,6 +73,12 @@ type Config struct {
|
||||
// readiness is installed, and latched like a failed role admission.
|
||||
RF1Only string
|
||||
|
||||
// StorageIdentity identifies the file system of the durable root
|
||||
// (machine id + st_dev + statfs f_fsid), reported in every heartbeat so the master can
|
||||
// detect a durable root that shares the authority store's journal. Zero
|
||||
// means unknown (memback, non-unix, or the root could not be read).
|
||||
StorageIdentity storeident.Identity
|
||||
|
||||
// ReplicationVolume, when non-nil, receives peer-set updates on
|
||||
// every self-replica AssignmentFact. The Host calls
|
||||
// UpdateReplicaSet(peer_set_generation, targets) BEFORE
|
||||
@@ -639,6 +646,10 @@ func (h *Host) buildReport() *control.HeartbeatReport {
|
||||
SentAt: timestamppb.Now(),
|
||||
Reachable: true,
|
||||
Eligible: true,
|
||||
// Raw identity facts; the master compares them with its own store.
|
||||
MachineId: h.cfg.StorageIdentity.MachineID,
|
||||
DurableRootDev: h.cfg.StorageIdentity.Dev,
|
||||
DurableRootFsid: h.cfg.StorageIdentity.FSID,
|
||||
Slots: []*control.HeartbeatSlot{
|
||||
{
|
||||
VolumeId: h.cfg.VolumeID,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
)
|
||||
|
||||
// Every heartbeat carries the durable root's file-system identity as raw
|
||||
// facts, so the master can detect a root on its authority store's journal.
|
||||
// An unconfigured identity reports zero (unknown).
|
||||
func TestBuildReportCarriesStorageIdentity(t *testing.T) {
|
||||
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "node-a", VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101",
|
||||
StorageIdentity: storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0xfeed}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = h.Close() }()
|
||||
r := h.buildReport()
|
||||
if r.GetMachineId() != "machine-1" || r.GetDurableRootDev() != 2049 || r.GetDurableRootFsid() != 0xfeed {
|
||||
t.Fatalf("report identity = (%q, %d, %#x), want (machine-1, 2049, 0xfeed)", r.GetMachineId(), r.GetDurableRootDev(), r.GetDurableRootFsid())
|
||||
}
|
||||
|
||||
plain := newTestVolumeHost(t)
|
||||
defer func() { _ = plain.Close() }()
|
||||
if r := plain.buildReport(); r.GetMachineId() != "" || r.GetDurableRootDev() != 0 {
|
||||
t.Fatalf("unconfigured identity reported (%q, %d), want unknown", r.GetMachineId(), r.GetDurableRootDev())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -116,6 +116,17 @@ message HeartbeatReport {
|
||||
bool reachable = 3;
|
||||
bool eligible = 4;
|
||||
repeated HeartbeatSlot slots = 5;
|
||||
// machine_id and durable_root_dev identify the file system of the
|
||||
// reporting process's durable root (the machine's /etc/machine-id and
|
||||
// the root's st_dev). Raw observation facts: the master compares them
|
||||
// with its own authority store to detect a shared file system (one
|
||||
// journal). Empty / 0 means unknown and is never compared.
|
||||
string machine_id = 6;
|
||||
uint64 durable_root_dev = 7;
|
||||
// durable_root_fsid is the durable root's statfs f_fsid (high word
|
||||
// first). 0 means unknown (older reporters, platforms without statfs):
|
||||
// the master then compares machine_id and durable_root_dev only.
|
||||
uint64 durable_root_fsid = 8;
|
||||
}
|
||||
|
||||
// HeartbeatSlot — per-replica slot fact. local_role_claim is the
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// Package storeident identifies the file system a durable directory lives
|
||||
// on, so that two processes can tell whether their fsyncs share one journal
|
||||
// (one ext4 file system = one jbd2 journal).
|
||||
//
|
||||
// An Identity is a raw observation fact: the machine's id, the directory's
|
||||
// device number and its file system id. Zero values mean unknown and never
|
||||
// compare equal.
|
||||
package storeident
|
||||
|
||||
// Identity is the (machine, device, file system id) of a directory's file
|
||||
// system.
|
||||
type Identity struct {
|
||||
MachineID string // trimmed /etc/machine-id; "" = unknown
|
||||
Dev uint64 // st_dev of the directory; 0 = unknown
|
||||
// FSID is statfs f_fsid of the directory (its two 32-bit words, high
|
||||
// word first); 0 = unknown. Peers that predate it report 0.
|
||||
FSID uint64
|
||||
}
|
||||
|
||||
// Of returns the identity of dir's file system. On a platform without
|
||||
// st_dev or statfs, or on any error, the unknown parts are left zero.
|
||||
func Of(dir string) Identity {
|
||||
return Identity{MachineID: machineID(), Dev: devOf(dir), FSID: fsidOf(dir)}
|
||||
}
|
||||
|
||||
// Known reports whether the machine id and device are known (the parts
|
||||
// every comparison needs; FSID is compared only when both sides know it).
|
||||
func (a Identity) Known() bool { return a.MachineID != "" && a.Dev != 0 }
|
||||
|
||||
// SameFileSystem reports whether a and b are known to name the same file
|
||||
// system: same machine and same device, and, when both sides know their file
|
||||
// system id, the same file system id. One unknown FSID (a peer that predates
|
||||
// it, a platform without statfs) falls back to machine id + device, as
|
||||
// before FSID existed. Unknown machine id or device never matches.
|
||||
func (a Identity) SameFileSystem(b Identity) bool {
|
||||
if !a.Known() || !b.Known() || a.MachineID != b.MachineID || a.Dev != b.Dev {
|
||||
return false
|
||||
}
|
||||
return a.FSID == 0 || b.FSID == 0 || a.FSID == b.FSID
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build linux
|
||||
|
||||
package storeident
|
||||
|
||||
import "syscall"
|
||||
|
||||
// fsidOf returns statfs f_fsid of dir as one value (high word first), or 0
|
||||
// when dir cannot be read.
|
||||
func fsidOf(dir string) uint64 {
|
||||
if dir == "" {
|
||||
return 0
|
||||
}
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(dir, &st); err != nil {
|
||||
return 0
|
||||
}
|
||||
return uint64(uint32(st.Fsid.X__val[0]))<<32 | uint64(uint32(st.Fsid.X__val[1]))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//go:build linux
|
||||
|
||||
package storeident
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// On Linux Of reports the directory's statfs f_fsid: non-zero, the value
|
||||
// statfs itself gives, and equal for two directories of one file system.
|
||||
// Skipped only where the file system reports no f_fsid at all.
|
||||
func TestOfReportsFSIDOnLinux(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(root, &st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st.Fsid.X__val[0] == 0 && st.Fsid.X__val[1] == 0 {
|
||||
t.Skipf("the file system of %s reports no f_fsid", root)
|
||||
}
|
||||
sub := filepath.Join(root, "sub")
|
||||
if err := os.Mkdir(sub, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := Of(root)
|
||||
want := uint64(uint32(st.Fsid.X__val[0]))<<32 | uint64(uint32(st.Fsid.X__val[1]))
|
||||
if a.FSID == 0 || a.FSID != want {
|
||||
t.Fatalf("Of(%s).FSID = %#x, want statfs f_fsid %#x", root, a.FSID, want)
|
||||
}
|
||||
if b := Of(sub); b.FSID != a.FSID {
|
||||
t.Fatalf("two dirs of one file system: fsid %#x vs %#x", a.FSID, b.FSID)
|
||||
}
|
||||
if Of(filepath.Join(root, "absent")).FSID != 0 {
|
||||
t.Fatal("missing dir reported an fsid")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package storeident
|
||||
|
||||
// No statfs f_fsid here: the file system id is unknown and comparisons fall
|
||||
// back to machine id + device.
|
||||
func fsidOf(string) uint64 { return 0 }
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !unix
|
||||
|
||||
package storeident
|
||||
|
||||
// No st_dev here: the identity is unknown and never matches.
|
||||
func machineID() string { return "" }
|
||||
|
||||
func devOf(string) uint64 { return 0 }
|
||||
@@ -0,0 +1,110 @@
|
||||
package storeident
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Two identities match only when both are fully known and equal: an unknown
|
||||
// machine id or device (zero value) never matches, not even another unknown.
|
||||
func TestSameFileSystemTruthTable(t *testing.T) {
|
||||
known := Identity{MachineID: "m1", Dev: 7}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
a, b Identity
|
||||
want bool
|
||||
}{
|
||||
{"same machine same dev", known, Identity{MachineID: "m1", Dev: 7}, true},
|
||||
{"same machine other dev", known, Identity{MachineID: "m1", Dev: 8}, false},
|
||||
{"other machine same dev", known, Identity{MachineID: "m2", Dev: 7}, false},
|
||||
{"both zero", Identity{}, Identity{}, false},
|
||||
{"empty machine ids, same dev", Identity{Dev: 7}, Identity{Dev: 7}, false},
|
||||
{"same machine, both dev unknown", Identity{MachineID: "m1"}, Identity{MachineID: "m1"}, false},
|
||||
{"one side unknown dev", known, Identity{MachineID: "m1"}, false},
|
||||
{"one side unknown machine", known, Identity{Dev: 7}, false},
|
||||
{"known vs zero", known, Identity{}, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := c.a.SameFileSystem(c.b); got != c.want {
|
||||
t.Fatalf("%+v.SameFileSystem(%+v) = %v, want %v", c.a, c.b, got, c.want)
|
||||
}
|
||||
if got := c.b.SameFileSystem(c.a); got != c.want {
|
||||
t.Fatalf("not symmetric: %+v.SameFileSystem(%+v) = %v, want %v", c.b, c.a, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Of on a missing directory leaves the device unknown, so it never matches.
|
||||
func TestOfMissingDirIsUnknown(t *testing.T) {
|
||||
id := Of(filepath.Join(t.TempDir(), "absent"))
|
||||
if id.Dev != 0 {
|
||||
t.Fatalf("missing dir: Dev = %d, want 0", id.Dev)
|
||||
}
|
||||
if id.SameFileSystem(id) {
|
||||
t.Fatal("an identity with an unknown device matched itself")
|
||||
}
|
||||
}
|
||||
|
||||
// On Linux two directories of one file system have the same identity, and
|
||||
// both parts are known (machine-id present on the test hosts).
|
||||
func TestOfSameFileSystemOnLinux(t *testing.T) {
|
||||
if runtime.GOOS != "linux" {
|
||||
t.Skip("st_dev / machine-id identity is Linux-only in practice")
|
||||
}
|
||||
if _, err := os.Stat("/etc/machine-id"); err != nil {
|
||||
if _, err := os.Stat("/var/lib/dbus/machine-id"); err != nil {
|
||||
t.Skip("no machine-id on this host")
|
||||
}
|
||||
}
|
||||
root := t.TempDir()
|
||||
sub := filepath.Join(root, "sub")
|
||||
if err := os.Mkdir(sub, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a, b := Of(root), Of(sub)
|
||||
if !a.Known() {
|
||||
t.Fatalf("identity of %s unknown: %+v", root, a)
|
||||
}
|
||||
if !a.SameFileSystem(b) {
|
||||
t.Fatalf("two dirs of one file system differ: %+v vs %+v", a, b)
|
||||
}
|
||||
if proc := Of("/proc"); proc.Dev != 0 && a.SameFileSystem(proc) {
|
||||
t.Fatalf("temp dir and /proc reported as one file system: %+v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// The file system id refines machine id + device: when both sides know it,
|
||||
// all three must be equal; when either side does not (a peer that predates
|
||||
// it), the comparison falls back to machine id + device.
|
||||
func TestSameFileSystemComparesFSIDWhenBothKnowIt(t *testing.T) {
|
||||
a := Identity{MachineID: "m1", Dev: 7, FSID: 0xabc}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
b Identity
|
||||
want bool
|
||||
}{
|
||||
{"same machine, dev and fsid", Identity{MachineID: "m1", Dev: 7, FSID: 0xabc}, true},
|
||||
{"same machine and dev, other fsid", Identity{MachineID: "m1", Dev: 7, FSID: 0xabd}, false},
|
||||
{"fsid unknown on the peer", Identity{MachineID: "m1", Dev: 7}, true},
|
||||
{"fsid unknown on the peer, other dev", Identity{MachineID: "m1", Dev: 8}, false},
|
||||
{"same fsid, other dev", Identity{MachineID: "m1", Dev: 8, FSID: 0xabc}, false},
|
||||
{"same fsid and dev, other machine", Identity{MachineID: "m2", Dev: 7, FSID: 0xabc}, false},
|
||||
{"fsid alone known", Identity{FSID: 0xabc}, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := a.SameFileSystem(c.b); got != c.want {
|
||||
t.Fatalf("%+v.SameFileSystem(%+v) = %v, want %v", a, c.b, got, c.want)
|
||||
}
|
||||
if got := c.b.SameFileSystem(a); got != c.want {
|
||||
t.Fatalf("not symmetric: %+v.SameFileSystem(%+v) = %v, want %v", c.b, a, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
both := Identity{MachineID: "m1", Dev: 7}
|
||||
if !both.SameFileSystem(Identity{MachineID: "m1", Dev: 7}) {
|
||||
t.Fatal("both fsids unknown: machine id + device must still match")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//go:build unix
|
||||
|
||||
package storeident
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var machineIDPaths = []string{"/etc/machine-id", "/var/lib/dbus/machine-id"}
|
||||
|
||||
func machineID() string {
|
||||
for _, p := range machineIDPaths {
|
||||
b, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if id := strings.TrimSpace(string(b)); id != "" {
|
||||
return id
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func devOf(dir string) uint64 {
|
||||
if dir == "" {
|
||||
return 0
|
||||
}
|
||||
var st syscall.Stat_t
|
||||
if err := syscall.Stat(dir, &st); err != nil {
|
||||
return 0
|
||||
}
|
||||
return uint64(st.Dev) //nolint:unconvert // int32 on some unix platforms
|
||||
}
|
||||
Reference in new issue
Block a user