Merge pull request #789 from seaweedfs/fix/single-filer-bound-race

fix(chunkstore): the single-filer census passes only when every master answered
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-29 14:31:29 -08:00
commit f5d43af2ae
5 files changed
+188 -56

No files matched your search

@@ -0,0 +1,72 @@
package main
import (
"bytes"
"context"
"net"
"strings"
"testing"
"time"
"google.golang.org/grpc"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/masterpb"
"github.com/seaweedfs/seaweed-block/core/ops"
)
type unansweredFiler struct {
filerpb.UnimplementedSeaweedFilerServer
masters []string
}
func (f *unansweredFiler) GetFilerConfiguration(context.Context, *filerpb.GetFilerConfigurationRequest) (*filerpb.GetFilerConfigurationResponse, error) {
return &filerpb.GetFilerConfigurationResponse{Masters: f.masters}, nil
}
type listingMaster struct {
masterpb.UnimplementedSeaweedServer
filer string
}
func (m *listingMaster) ListClusterNodes(context.Context, *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) {
return &masterpb.ListClusterNodesResponse{ClusterNodes: []*masterpb.ListClusterNodesResponse_ClusterNode{{Address: m.filer}}}, nil
}
// The shell's single-filer start check is the census's: a master address of
// the filer that does not parse is a master that did not answer, so one
// favourable master does not pass alone; the command is refused as invalid,
// naming that master and saying to rerun when it answers.
func TestOpsChunk_StartCheckRefusesAnUnparsableMaster(t *testing.T) {
flis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
filer := flis.Addr().String()
_, fport, _ := net.SplitHostPort(filer)
mlis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
ms := grpc.NewServer()
masterpb.RegisterSeaweedServer(ms, &listingMaster{filer: "127.0.0.1:8888." + fport})
go func() { _ = ms.Serve(mlis) }()
t.Cleanup(ms.Stop)
_, mport, _ := net.SplitHostPort(mlis.Addr().String())
fs := grpc.NewServer()
filerpb.RegisterSeaweedFilerServer(fs, &unansweredFiler{masters: []string{"127.0.0.1:9333." + mport, "m1:9333.notaport"}})
go func() { _ = fs.Serve(flis) }()
t.Cleanup(fs.Stop)
f, closeFiler, err := dialChunkFiler(filer)
if err != nil {
t.Fatal(err)
}
defer closeFiler()
var stdout, stderr bytes.Buffer
code := refuseUnlessSingleFiler("snapshot-delete", f, 2*time.Second, &stdout, &stderr)
out := stdout.String() + stderr.String()
if code != ops.VolumeStatusExitInvalid || !strings.Contains(out, "m1:9333.notaport") || !strings.Contains(out, "rerun when they answer") {
t.Fatalf("one favourable master and one unparsable: exit %d, %q; want exit %d naming m1:9333.notaport, rerun when they answer", code, out, ops.VolumeStatusExitInvalid)
}
}
@@ -39,11 +39,15 @@ var (
// CheckSingleFiler asks the filer for its masters and filer group
// (filer_pb.SeaweedFiler/GetFilerConfiguration), then asks every master for
// the filers registered in that group (master_pb.Seaweed/ListClusterNodes,
// client_type "filer"). It passes when a master lists exactly one filer and
// that filer is the configured one. Any master listing another filer, or
// several, refuses at once, whichever master answers first. No master
// listing the target yet, or none answering, is retried until the bound and
// then refused (fail closed).
// client_type "filer"). It passes only in a round where EVERY master
// answered, none refused, and at least one listed exactly the configured
// filer. Any master listing another filer, or several, refuses at once,
// whichever master answers first. A master that did not answer, for any
// reason and at any time, leaves the round unconfirmed, and the masters are
// asked again; so is a round where no master lists the target yet. The bound
// only ends the asking: then the start is refused (fail closed), naming the
// masters that did not answer. There is no clock in the verdict: a chunk
// volume does not start while any master is unreachable.
func (c *SWFS) CheckSingleFiler(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, singleFilerWait)
defer cancel()
@@ -55,39 +59,49 @@ func (c *SWFS) CheckSingleFiler(ctx context.Context) error {
if len(cfg.GetMasters()) == 0 {
return fmt.Errorf("%w: filer %s reports no master, cannot list its group", ErrNotSingleFiler, c.cfg.FilerGRPC)
}
var tried []string
var tried, unanswered []string
for {
ok, err := c.singleFilerRound(ctx, cfg, &tried)
ok, err := c.singleFilerRound(ctx, cfg, &tried, &unanswered)
if ok || err != nil {
return err
}
select {
case <-ctx.Done():
return fmt.Errorf("%w: could not confirm filer %s as the only filer within %s: %s", ErrNotSingleFiler, c.cfg.FilerGRPC, singleFilerWait, strings.Join(tried, "; "))
missing := ""
if len(unanswered) > 0 {
missing = "; every master must answer, these did not: " + strings.Join(unanswered, ", ") + " (rerun when they answer)"
}
return fmt.Errorf("%w: could not confirm filer %s as the only filer within %s: %s%s", ErrNotSingleFiler, c.cfg.FilerGRPC, singleFilerWait, strings.Join(tried, "; "), missing)
case <-time.After(singleFilerRetry):
}
}
}
// singleFilerRound asks every master once. It refuses when any master lists
// several filers or a filer other than the target; it passes when no master
// refuses and at least one lists exactly the target; otherwise it asks for
// another round (tried keeps each master's answer).
func (c *SWFS) singleFilerRound(ctx context.Context, cfg *filerpb.GetFilerConfigurationResponse, tried *[]string) (bool, error) {
*tried = (*tried)[:0]
// several filers or a filer other than the target; it passes only when every
// master answered, none refused, and at least one lists exactly the target;
// otherwise it asks for another round. tried keeps each master's answer,
// unanswered the masters that did not answer in this round.
func (c *SWFS) singleFilerRound(ctx context.Context, cfg *filerpb.GetFilerConfigurationResponse, tried, unanswered *[]string) (bool, error) {
*tried, *unanswered = (*tried)[:0], (*unanswered)[:0]
group := cfg.GetFilerGroup()
sawTarget := false
for _, m := range cfg.GetMasters() {
addr, err := grpcAddress(m)
if err != nil {
*tried = append(*tried, fmt.Sprintf("%s: %v", m, err))
*unanswered = append(*unanswered, m)
continue
}
actx, cancel := context.WithTimeout(ctx, singleFilerAttempt)
nodes, err := listFilers(actx, addr, group)
cancel()
if err != nil {
*tried = append(*tried, fmt.Sprintf("%s: %v", addr, err))
// Its view is unknown, whatever the reason and whenever it
// happened: the round is not confirmed (asking the rest still
// finds a refusal).
*tried = append(*tried, fmt.Sprintf("%s: no answer: %v", addr, err))
*unanswered = append(*unanswered, addr)
continue
}
switch {
@@ -101,13 +115,7 @@ func (c *SWFS) singleFilerRound(ctx context.Context, cfg *filerpb.GetFilerConfig
*tried = append(*tried, addr+": lists no filer in group "+strconv.Quote(group)+" yet")
}
}
if ctx.Err() != nil {
// The bound passed while a later master was still being asked:
// its view is unknown, so an earlier favourable answer does not
// count.
return false, nil
}
return sawTarget, nil
return sawTarget && len(*unanswered) == 0, nil
}
// isTarget reports whether a filer address listed by a master is the
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"net"
"slices"
"strings"
"sync"
"testing"
@@ -40,18 +41,29 @@ type nodesMaster struct {
filers []string
emptyN int // the first emptyN calls list no filer (not registered yet)
stall bool // never answers (until the caller's deadline)
calls int
got *masterpb.ListClusterNodesRequest
// early, with stall: answers DeadlineExceeded this long BEFORE its own
// deadline, as a gRPC server whose deadline (from the client's
// grpc-timeout) runs out ahead of the client's context does.
early time.Duration
calls int
got *masterpb.ListClusterNodesRequest
}
func (m *nodesMaster) ListClusterNodes(ctx context.Context, r *masterpb.ListClusterNodesRequest) (*masterpb.ListClusterNodesResponse, error) {
m.mu.Lock()
m.got = r
m.calls++
calls, stall := m.calls, m.stall
calls, stall, early := m.calls, m.stall, m.early
filers := append([]string(nil), m.filers...)
m.mu.Unlock()
if stall {
if dl, ok := ctx.Deadline(); ok && early > 0 {
select {
case <-ctx.Done():
case <-time.After(time.Until(dl) - early):
}
return nil, status.Error(codes.DeadlineExceeded, "context deadline exceeded")
}
<-ctx.Done()
return nil, ctx.Err()
}
@@ -178,7 +190,8 @@ func refusedAtBound(t *testing.T, what string, c *SWFS) {
}
// The configured filer passes only as the one filer of its group, listed by
// a master; also when it registers only after a few rounds.
// a master, in a round where every master answered; also when it registers
// only after a few rounds.
func TestCheckSingleFilerPasses(t *testing.T) {
shortBounds(t)
c, ms := cluster(t, "g1", lists("self"))
@@ -192,20 +205,10 @@ func TestCheckSingleFilerPasses(t *testing.T) {
if err := c.CheckSingleFiler(context.Background()); err != nil || ms[0].callCount() != 4 {
t.Fatalf("target registered on the 4th round: %v after %d calls; want a pass", err, ms[0].callCount())
}
// A dead or stalled first master does not hide a healthy second one, and
// a stalled call costs one attempt, not the whole bound.
c, _ = cluster(t, "", func(string) *nodesMaster { return &nodesMaster{stall: true} }, lists("self"))
start := time.Now()
if err := c.CheckSingleFiler(context.Background()); err != nil || time.Since(start) > 2*singleFilerAttempt {
t.Fatalf("stalled first master: %v after %s; want a pass within one attempt", err, time.Since(start))
}
f := &configFiler{}
c, self := startConfigFiler(t, f)
f.mu.Lock()
f.masters = []string{deadAddress(t), startMaster(t, &nodesMaster{filers: []string{self}})}
f.mu.Unlock()
// Two masters, both listing the target: a pass (every master answered).
c, _ = cluster(t, "", lists("self"), lists("self"))
if err := c.CheckSingleFiler(context.Background()); err != nil {
t.Fatalf("dead first master: %v", err)
t.Fatalf("two masters, both favourable: %v", err)
}
}
@@ -250,17 +253,61 @@ func TestIsTargetComparesScopedAddresses(t *testing.T) {
}
}
// A favourable first master does not pass once the bound has run out while
// a later master is still being asked: that master's view is unknown.
func TestCheckSingleFilerFavourableThenStalledRefuses(t *testing.T) {
w, r, a := singleFilerWait, singleFilerRetry, singleFilerAttempt
singleFilerWait, singleFilerRetry, singleFilerAttempt = 800*time.Millisecond, 100*time.Millisecond, 5*time.Second
t.Cleanup(func() { singleFilerWait, singleFilerRetry, singleFilerAttempt = w, r, a })
c, _ := cluster(t, "", lists("self"), func(string) *nodesMaster { return &nodesMaster{stall: true} })
start := time.Now()
err := c.CheckSingleFiler(context.Background())
if !errors.Is(err, ErrNotSingleFiler) || time.Since(start) < singleFilerWait {
t.Fatalf("favourable then stalled past the bound: %v after %s; want a refusal at the bound", err, time.Since(start))
// A round passes only when every master answered: with one favourable
// master, any other master that does not answer (it stalls past its attempt,
// answers DeadlineExceeded before its deadline, is down, or its address does
// not parse), in either order, leaves every round unconfirmed, and the start
// is refused at the bound naming it. No clock decides: the same master is a
// refusal whenever it does not answer.
func TestCheckSingleFilerNeedsEveryMasterToAnswer(t *testing.T) {
shortBounds(t)
for _, c := range []struct {
name string
other func(t *testing.T) (string, func(string) *nodesMaster)
}{
{"stalled", func(t *testing.T) (string, func(string) *nodesMaster) {
return "", func(string) *nodesMaster { return &nodesMaster{stall: true} }
}},
{"deadline answer before its deadline", func(t *testing.T) (string, func(string) *nodesMaster) {
return "", func(string) *nodesMaster { return &nodesMaster{stall: true, early: 100 * time.Millisecond} }
}},
{"down", func(t *testing.T) (string, func(string) *nodesMaster) { return deadAddress(t), nil }},
{"address does not parse", func(t *testing.T) (string, func(string) *nodesMaster) { return "m1:9333.notaport", nil }},
} {
for _, otherFirst := range []bool{false, true} {
f := &configFiler{}
cl, self := startConfigFiler(t, f)
good := startMaster(t, &nodesMaster{filers: []string{self}})
bad, mk := c.other(t)
if mk != nil {
bad = startMaster(t, mk(self))
}
masters := []string{good, bad}
if otherFirst {
masters = []string{bad, good}
}
f.mu.Lock()
f.masters = masters
f.mu.Unlock()
err := cl.CheckSingleFiler(context.Background())
// It names the master that did not answer (its gRPC address, or
// the address as given when it does not parse) among those that
// did not answer in the last round (the bound may also cut the
// favourable master's last call).
want := bad
if g, gerr := grpcAddress(bad); gerr == nil {
want = g
}
const lead = "every master must answer, these did not: "
msg := ""
if err != nil {
msg = err.Error()
}
i, j := strings.Index(msg, lead), strings.Index(msg, " (rerun when they answer)")
if !errors.Is(err, ErrNotSingleFiler) || i < 0 || j < i || !slices.Contains(strings.Split(msg[i+len(lead):j], ", "), want) {
t.Errorf("%s (other first %v): %v; want a refusal naming %s among the masters that did not answer", c.name, otherFirst, err, want)
}
}
}
}
+1 -1
View File
@@ -823,7 +823,7 @@ Notes:
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go`; `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal`; `core/frontend/chunkstore/layout/volume.go`, `start.go`, `create.go`; `core/frontend/chunkstore/catalog_b.go` | `TestGeometryFlagsRefusalComparesTheRecord`, `TestVolumeRequiresGeometry`, `TestVolumeGeometryChecksAndIsImmutable`, `TestStartGeometryMismatchPrecedesClaim`, `TestBCatalogRestoreCopiesVolumeGeometry`, `TestVolumeGeometryLivesOnlyInVolume` | K3: immutable required VOLUME geometry; Start checks the local persisted shape before claim; restores copy source geometry; no resize or compatibility path. | ACTIVE |
| `INV-WS-STALE-LOCAL-ROOT-001` | An old or rolled-back local root is refused by `layout.Start` before serving; synchronous and deferred attach end without retry and report the typed stale-root error and cure. A fresh root at its own epoch likewise ends with `ErrMissingLocalRoot` and its cure. | M4 Claiming → Refused | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_chunk.go` `recoverChunk`, `chunkAuthorityWait`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot`, `TestFinalLayoutStartRefusalTable` (`core/frontend/durable/provider_layout_test.go`, `provider_layout_start_class_test.go`) | — | ACTIVE |
| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is its group's only filer, confirmed in a round where every master answered: a master listing another filer or several refuses at once; an unanswered master leaves the round unconfirmed; 60 s unconfirmed is refused. A startup census, not a fence. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerNeedsEveryMasterToAnswer`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_StartCheckRefusesAnUnparsableMaster` (`cmd/sw-block/chunk_single_filer_unanswered_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | ACTIVE |
| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE |
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspaceRevocationAckOutlastsTheMastersBoundedSteps`, `TestWorkspaceRevocationAckIsCutAtTheLeaseDeadline` (`core/host/volume/workspace_ack_budget_test.go`); `TestWorkspaceRevocationAckIsAskedAgainAfterALostAnswer`, `TestWorkspaceCloseoutFitsTheUnitsStopBudget` (`cmd/blockvolume/process_exit_ack_retry_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
+11 -6
View File
@@ -438,12 +438,17 @@ The `--chunk-*` and `--workspace-lease` flags are refused unless
`--chunk-filer` must name the only filer of its filer group. At startup
blockvolume asks that filer for its masters, then every master for the
filers in the group. It starts only when a master lists exactly that filer.
Any master listing another filer, or several, refuses at once. If no master
lists it yet (a fresh filer registers with its master some seconds after it
serves), or none answers, blockvolume asks again every second until 60 s,
then refuses. This is checked at startup only; do not add filers to the
group while volumes run.
filers in the group. It starts only when, in one round, every master
answers, none lists another filer or several, and at least one lists
exactly that filer. Any master listing another filer, or several, refuses at
once. If a master does not answer, or no master lists the filer yet (a fresh
filer registers with its master some seconds after it serves), blockvolume
asks again every second until 60 s, then refuses, naming the masters that
did not answer. A chunk volume therefore does not start while any master of
the filer's group is unreachable: start it again once they answer. At start,
the leader master listed this filer and no other; a filer added within about
15 seconds before the start, or at any time after, is not detected. This is
checked at startup only; do not add filers to the group while volumes run.
## Notes