mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
feat: detect master journal sharing and alarm on lease headroom
A volume whose durable root sits on the authority store's file system shares its jbd2 journal: under a WAL fsync storm the lease extensions lag, grants clamp to the durable horizon and leases run out. - core/storeident: (machine-id, st_dev) identity of a directory; unknown never matches. - Heartbeats carry the durable root's identity (machine_id, durable_root_dev); the master compares it with its authority store, logs and counts co-located nodes once per detection. - --strict-journal-isolation (default off = alarm only): refuses heartbeats of a co-located node that serves no volume (durable state decides), and refuses PlaceWorkspace/MoveWorkspace and new product-loop placements onto co-located nodes. - Publisher: headroom alarm while an extension is pending and headroom < 1.125 TTL (before the first clamp), clamp counters (total, last minute), min headroom at grants, lazy per-minute summary; WorkspaceLeaseStats snapshot. - --status-listen (loopback only): GET /status/workspace-lease JSON. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e6c74a55bc
commit
e57f399c07
23 files changed
+1817
-616
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)
|
||||
|
||||
@@ -35,6 +35,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"
|
||||
)
|
||||
@@ -1490,6 +1491,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,
|
||||
@@ -1503,6 +1508,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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
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 (the alarm), and only later as clamps.
|
||||
|
||||
// LeaseStats is a snapshot of the workspace lease renewal counters.
|
||||
type LeaseStats struct {
|
||||
// HeadroomAlarms counts alarm streaks: renewals that found an extension
|
||||
// in flight with headroom below 1.125 TTL, once per volume per 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
|
||||
}
|
||||
|
||||
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
|
||||
// Per-minute summary, emitted lazily by the first renewal after the
|
||||
// window: no goroutine of its own.
|
||||
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++
|
||||
}
|
||||
|
||||
// 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 {
|
||||
var note string
|
||||
if c.windowStart.IsZero() {
|
||||
c.windowStart = now
|
||||
} else if now.Sub(c.windowStart) >= time.Minute {
|
||||
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
|
||||
}
|
||||
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
|
||||
return LeaseStats{
|
||||
HeadroomAlarms: c.alarms,
|
||||
ClampsTotal: c.clamps,
|
||||
ClampsLastMinute: c.clampsSince(p.workspaceNow()),
|
||||
MinHeadroom: time.Duration(c.minHeadroom),
|
||||
MinHeadroomObserved: c.minObserved,
|
||||
}
|
||||
}
|
||||
|
||||
// headroomAlarmLocked runs the alarm state machine of one renewal. Caller
|
||||
// holds leaseMu. It returns a note to log after the unlock.
|
||||
//
|
||||
// state | condition at a renewal | next | effect
|
||||
// -----------+-----------------------------------------------+------------+------------------
|
||||
// quiet | extending && headroom < 1.125 TTL | 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 | -
|
||||
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 ""
|
||||
}
|
||||
if !lv.extending || headroom >= low {
|
||||
return ""
|
||||
}
|
||||
lv.alarmed = true
|
||||
p.leaseStats.alarms++
|
||||
return fmt.Sprintf("workspace lease: volume=%s headroom %s below 1.125 TTL while the extension write is pending; the authority store is lagging",
|
||||
volume, time.Duration(headroom).Round(time.Millisecond))
|
||||
}
|
||||
|
||||
func (p *Publisher) logLease(note string) {
|
||||
if note == "" {
|
||||
return
|
||||
}
|
||||
if p.leaseLog != nil {
|
||||
p.leaseLog(note)
|
||||
return
|
||||
}
|
||||
log.Print(note)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,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.
|
||||
@@ -161,6 +162,10 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
p.leaseMu.Unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
// The headroom alarm is evaluated before the clamp: it fires while an
|
||||
// extension is pending and headroom is still above one TTL.
|
||||
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 {
|
||||
@@ -172,11 +177,16 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
|
||||
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(alarm)
|
||||
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:
|
||||
@@ -194,9 +204,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
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,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 +79,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 +120,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 +200,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 +224,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.Of(cfg.AuthorityStoreDir)),
|
||||
}
|
||||
|
||||
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
|
||||
@@ -277,6 +297,20 @@ 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
|
||||
h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: 5 * time.Second}
|
||||
}
|
||||
|
||||
grpcSrv := grpc.NewServer()
|
||||
svc := newServices(h)
|
||||
control.RegisterObservationServiceServer(grpcSrv, svc)
|
||||
@@ -293,6 +327,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 +384,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 +503,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 +525,10 @@ func (h *Host) Close(ctx context.Context) error {
|
||||
if h.frontendRuntimeHTTP != nil {
|
||||
_ = h.frontendRuntimeHTTP.Shutdown(ctx)
|
||||
}
|
||||
if h.statusHTTP != nil {
|
||||
_ = h.statusHTTP.Shutdown(ctx)
|
||||
_ = h.statusLn.Close() // a listener Start never served is not Shutdown's
|
||||
}
|
||||
h.obs.Stop()
|
||||
|
||||
done := make(chan struct{})
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
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. It takes no workspaceMu: a heartbeat must not wait behind a
|
||||
// slow authority write.
|
||||
func (h *Host) nodeServesVolumes(server string) bool {
|
||||
if h.lifecycle != nil {
|
||||
for _, p := range h.lifecycle.Placements.ListPlacements() {
|
||||
for _, slot := range p.Slots {
|
||||
if slot.ServerID == server {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range h.lifecycle.Volumes.ListVolumes() {
|
||||
if line, ok := h.Publisher().VolumeAuthorityLine(v.Spec.VolumeID); ok && h.workspaceSourceHost(v.Spec.VolumeID, line.ReplicaID, line.Epoch) == server {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range h.topo.Volumes {
|
||||
line, ok := h.Publisher().VolumeAuthorityLine(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"`
|
||||
}
|
||||
|
||||
// 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}
|
||||
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()
|
||||
}
|
||||
}
|
||||
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,304 @@
|
||||
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()
|
||||
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)
|
||||
}
|
||||
m.journal.setSelf(masterStore) // 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,
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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}}}); 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"} {
|
||||
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) {
|
||||
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()}); 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,6 +136,9 @@ 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"))
|
||||
}
|
||||
if 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 {
|
||||
|
||||
@@ -188,6 +188,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 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))
|
||||
}
|
||||
|
||||
@@ -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), 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
|
||||
@@ -634,6 +641,9 @@ 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,
|
||||
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}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = h.Close() }()
|
||||
r := h.buildReport()
|
||||
if r.GetMachineId() != "machine-1" || r.GetDurableRootDev() != 2049 {
|
||||
t.Fatalf("report identity = (%q, %d), want (machine-1, 2049)", r.GetMachineId(), r.GetDurableRootDev())
|
||||
}
|
||||
|
||||
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,13 @@ 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;
|
||||
}
|
||||
|
||||
// HeartbeatSlot — per-replica slot fact. local_role_claim is the
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// 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 and the directory's
|
||||
// device number. Zero values mean unknown and never compare equal.
|
||||
package storeident
|
||||
|
||||
// Identity is the (machine, device) pair 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
|
||||
}
|
||||
|
||||
// Of returns the identity of dir's file system. On a platform without
|
||||
// st_dev or on any error the unknown parts are left zero.
|
||||
func Of(dir string) Identity {
|
||||
return Identity{MachineID: machineID(), Dev: devOf(dir)}
|
||||
}
|
||||
|
||||
// Known reports whether both parts of the identity are known.
|
||||
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. Unknown never matches.
|
||||
func (a Identity) SameFileSystem(b Identity) bool {
|
||||
return a.Known() && b.Known() && a.MachineID == b.MachineID && a.Dev == b.Dev
|
||||
}
|
||||
@@ -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,77 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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