diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 66b3158d2a..2fee16c71f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "sync" "time" @@ -84,6 +85,25 @@ func chunkAuthority(proj frontend.Projection, volumeID string) bool { return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 && proj.ReplicaID != "" } +// chunkAuthorityGap names the projection fields that fail chunkAuthority, +// for the logs ("" when none fails). +func chunkAuthorityGap(proj frontend.Projection, volumeID string) string { + var gap []string + if proj.VolumeID != volumeID { + gap = append(gap, fmt.Sprintf("volume=%q", proj.VolumeID)) + } + if !proj.Healthy { + gap = append(gap, "healthy=false") + } + if proj.Epoch == 0 { + gap = append(gap, "epoch=0") + } + if proj.ReplicaID == "" { + gap = append(gap, `replica=""`) + } + return strings.Join(gap, " ") +} + // recoverChunk runs after a successful local Recover, generation gen. It // attaches the layer when the projection already carries master authority // and reports true. Otherwise it starts an authority wait bound to gen @@ -126,6 +146,13 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen if limit <= 0 { limit = 30 * time.Second } + start := time.Now() + log.Printf("durable: chunk layer for volume=%s waits for master authority (up to %s): projection lacks %s", + volumeID, limit, chunkAuthorityGap(p.view.Projection(), volumeID)) + ended := "superseded by a later recovery" + defer func() { + log.Printf("durable: chunk authority wait for volume=%s ended after %s: %s", volumeID, time.Since(start), ended) + }() waitCtx, endWait := context.WithTimeout(p.closeCtx, limit) defer endWait() defer func() { @@ -136,6 +163,7 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen h.attachMu.Lock() defer h.attachMu.Unlock() if p.current(h, gen) && h.chunk == nil { + ended = fmt.Sprintf("assignment unavailable, not serving (projection lacks %s)", chunkAuthorityGap(p.view.Projection(), volumeID)) h.backend.SetOperational(false, "chunk assignment unavailable: "+waitCtx.Err().Error()) } }() @@ -148,18 +176,28 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen }() t := time.NewTicker(chunkAuthorityPoll) defer t.Stop() + attempts := 0 for { select { case <-waitCtx.Done(): + ended = "provider closed" + if errors.Is(waitCtx.Err(), context.DeadlineExceeded) { + ended = "deadline" + } return case <-t.C: } if !p.current(h, gen) { return // a later recovery (successful or failed) owns the volume } - if !chunkAuthority(p.view.Projection(), volumeID) { + proj := p.view.Projection() + if !chunkAuthority(proj, volumeID) { continue } + if attempts++; attempts == 1 { + log.Printf("durable: chunk layer for volume=%s: master authority after %s (replica=%q epoch=%d endpoint=%d); first attach attempt", + volumeID, time.Since(start), proj.ReplicaID, proj.Epoch, proj.EndpointVersion) + } h.attachMu.Lock() if !p.current(h, gen) { // re-checked under the per-volume serialization h.attachMu.Unlock() @@ -176,9 +214,14 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } h.attachMu.Unlock() switch { - case err == nil, errors.Is(err, errProviderClosed): + case err == nil: + ended = fmt.Sprintf("attached after %d attempt(s)", attempts) + return + case errors.Is(err, errProviderClosed): + ended = "provider closed" return case errors.Is(err, storage.ErrChunkLayerFenced): + ended = "fenced, not serving" log.Printf("durable: chunk layer for volume=%s: %v (not serving)", volumeID, err) if errors.Is(err, ErrChunkStaleLocalRoot) { h.attachMu.Lock() @@ -189,11 +232,17 @@ func (p *DurableProvider) chunkAuthorityWait(volumeID string, h *volHandle, gen } return case errors.Is(err, errChunkNoAuthority): + log.Printf("durable: chunk layer attach for volume=%s: authority lost before attempt %d (projection lacks %s); waiting", + volumeID, attempts, chunkAuthorityGap(p.view.Projection(), volumeID)) continue } log.Printf("durable: chunk layer attach for volume=%s: %v (retrying)", volumeID, err) select { case <-waitCtx.Done(): + ended = "provider closed during the retry backoff" + if errors.Is(waitCtx.Err(), context.DeadlineExceeded) { + ended = "deadline during the retry backoff" + } return case <-time.After(chunkAttachRetry): } @@ -355,6 +404,8 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // Attach preparation is gated. Seed the exact observed HEAD before // its takeover CAS; only then finalize lazy attachment and expose I/O. cfg.PrepareRestore = func(head storage.ChunkHead) error { + log.Printf("durable: HEAD claim for volume=%s observed HEAD gen=%d epoch=%d holder=%q state=%v remote_lsn=%d; preparing", + volumeID, head.Gen, head.Epoch, head.Holder, head.State, head.RemoteLSN) if baseLSN, complete := ws.InstalledBaseLSN(); complete { // The fresh marker can outlive a full local BASE. It is not // permission to seed backwards or to fill from an older HEAD. @@ -383,10 +434,18 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h // restore here, so HEAD is never claimed for a mis-ordered ship. return h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(head.RemoteLSN) }) } + claimStart := time.Now() + log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder) head, err := storage.ClaimChunkHead(ctx, remote, cfg) if err != nil { + log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err) return nil, fmt.Errorf("durable: restore HEAD claim: %w", err) } + claimed := "claimed" + if head.Gen == 0 { + claimed = "no HEAD to claim (new lineage)" + } + log.Printf("durable: HEAD claim for volume=%s done in %s: gen=%d epoch=%d holder=%q, %s", volumeID, time.Since(claimStart), head.Gen, head.Epoch, head.Holder, claimed) cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch} } diff --git a/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go b/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go new file mode 100644 index 0000000000..9d3b9a2c4e --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_authority_log_test.go @@ -0,0 +1,225 @@ +package durable_test + +import ( + "bytes" + "context" + "errors" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type lockedLog struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (l *lockedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +func (l *lockedLog) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.String() +} + +// waitLog waits until the log holds want, then returns the log. +func waitLog(t *testing.T, l *lockedLog, want string) string { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for !strings.Contains(l.String(), want) { + if time.Now().After(deadline) { + t.Fatalf("log never held %q:\n%s", want, l.String()) + } + time.Sleep(time.Millisecond) + } + return l.String() +} + +// inOrder checks that every line holding a want[i] fragment set appears, +// each after the previous one. +func inOrder(t *testing.T, logs string, want ...[]string) { + t.Helper() + lines := strings.Split(logs, "\n") + at := 0 +next: + for _, frags := range want { + for ; at < len(lines); at++ { + ok := true + for _, f := range frags { + ok = ok && strings.Contains(lines[at], f) + } + if ok { + at++ + continue next + } + } + t.Fatalf("no line with %q after the previous expected line:\n%s", frags, logs) + } +} + +// The deferred attach logs its wait (with the projection fields that +// fail), the first attach attempt, the HEAD claim and how the wait ended. +func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p := chunkProviderForAssignment(t, v) + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + waitLog(t, logs, "waits for master authority") + close(v.assigned) + got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") + inOrder(t, got, + []string{"volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0"}, + []string{"volume=v1: master authority after", `replica="r1" epoch=3 endpoint=1`, "first attach attempt"}, + []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, + []string{`HEAD claim for volume=v1 observed HEAD gen=0 epoch=0 holder=""`, "; preparing"}, + []string{"HEAD claim for volume=v1 done in ", `gen=0 epoch=0 holder="", no HEAD to claim (new lineage)`}, + []string{"chunk authority wait for volume=v1 ended after", ": attached after 1 attempt(s)"}, + ) + if strings.Count(got, "first attach attempt") != 1 { + t.Fatalf("first attach attempt logged more than once:\n%s", got) + } +} + +// A wait that reaches its bound logs the assignment-unavailable transition +// with the fields still missing; a wait ended by Close says so. +func TestChunkAuthorityWaitLogsDeadlineAndClose(t *testing.T) { + for _, mode := range []string{"limit", "close"} { + t.Run(mode, func(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + limit := 40 * time.Millisecond + if mode == "close" { + limit = time.Minute + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkAssignmentTimeout: limit, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + }, v) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + want := "ended after" + if mode == "close" { + waitLog(t, logs, "waits for master authority") + if err := p.Close(); err != nil { + t.Fatal(err) + } + } + got := waitLog(t, logs, want) + end := ": assignment unavailable, not serving (projection lacks healthy=false epoch=0)" + if mode == "close" { + end = ": provider closed" + } + inOrder(t, got, + []string{"volume=v1 waits for master authority (up to " + limit.String() + "): projection lacks healthy=false epoch=0"}, + []string{"chunk authority wait for volume=v1 ended after", end}, + ) + if strings.Contains(got, "first attach attempt") || strings.Contains(got, "HEAD claim for") { + t.Fatalf("attach logged without authority:\n%s", got) + } + }) + } +} + +// headFailRemote fails GetHead while fails > 0 (forever when < 0). +type headFailRemote struct { + *storage.MemChunkRemote + fails atomic.Int32 +} + +var errHeadRead = errors.New("injected HEAD read failure") + +func (r *headFailRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + if n := r.fails.Load(); n != 0 { + if n > 0 { + r.fails.Add(-1) + } + return storage.ChunkHead{}, errHeadRead + } + return r.MemChunkRemote.GetHead(ctx) +} + +// A claim whose first HEAD read fails logs its start and its failure with +// the elapsed time; the retry then claims. Close during the retry backoff +// ends the wait as closed, not superseded. +func TestChunkAuthorityWaitLogsAFailedClaim(t *testing.T) { + for _, mode := range []string{"retried", "closed in backoff"} { + t.Run(mode, func(t *testing.T) { + logs := &lockedLog{} + captureWriteLogs(t, logs) + remote := &headFailRemote{MemChunkRemote: storage.NewMemChunkRemote()} + remote.fails.Store(1) + if mode != "retried" { + remote.fails.Store(-1) + } + v := &arrivingAssignment{seen: make(chan struct{}), assigned: make(chan struct{})} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v) + if err != nil { + t.Fatal(err) + } + defer p.Close() + if _, err := p.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + v.active.Store(true) + if _, err := p.RecoverVolume(context.Background(), "v1"); err != nil { + t.Fatal(err) + } + waitLog(t, logs, "waits for master authority") + close(v.assigned) + if mode == "retried" { + got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") + inOrder(t, got, + []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, + []string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()}, + []string{"chunk layer attach for volume=v1:", "(retrying)"}, + []string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`}, + []string{"HEAD claim for volume=v1 observed HEAD gen=0"}, + []string{"HEAD claim for volume=v1 done in "}, + []string{"chunk authority wait for volume=v1 ended after", ": attached after 2 attempt(s)"}, + ) + return + } + waitLog(t, logs, "(retrying)") + if err := p.Close(); err != nil { + t.Fatal(err) + } + got := waitLog(t, logs, "chunk authority wait for volume=v1 ended after") + inOrder(t, got, + []string{"HEAD claim for volume=v1 failed after ", errHeadRead.Error()}, + []string{"chunk authority wait for volume=v1 ended after", ": provider closed during the retry backoff"}, + ) + }) + } +} diff --git a/seaweed-block/core/storage/chunk_frontier.go b/seaweed-block/core/storage/chunk_frontier.go index 649fd1f581..46b0bdf94e 100644 --- a/seaweed-block/core/storage/chunk_frontier.go +++ b/seaweed-block/core/storage/chunk_frontier.go @@ -3,6 +3,8 @@ package storage import ( "errors" "fmt" + "log" + "time" ) // SeedChunkFrontier installs an empty fresh host's inherited remote frontier. @@ -66,11 +68,34 @@ func (s *WALStore) SeedChunkFrontier(lsn uint64) error { // An unmapped v3 store has no map candidate for the new checkpoint and is // refused. Order: captureMu -> lifecycleMu -> (syncMu ->) mu. func (s *WALStore) seedChunkFrontierV3(lsn uint64) error { + var t seedTimes + err := s.seedChunkFrontierV3Locked(lsn, &t) + // Logged after the capture and lifecycle locks are released: a slow log + // writer never extends them. A refused or no-op seed did no I/O. + if !t.validated.IsZero() { + stage := func(from, to time.Time) string { + if to.IsZero() { + return "-" + } + return to.Sub(from).String() + } + log.Printf("storage: seed frontier %d: capture+lifecycle lock wait %s, store mutex+validation %s, data sync (incl. sync serialization) %s, checkpoint publish %s, err=%v", + lsn, t.locked.Sub(t.start), t.validated.Sub(t.locked), stage(t.validated, t.synced), stage(t.synced, t.published), err) + } + return err +} + +// seedTimes are the stage boundaries of one v3 seed (zero: not reached). +type seedTimes struct{ start, locked, validated, synced, published time.Time } + +func (s *WALStore) seedChunkFrontierV3Locked(lsn uint64, t *seedTimes) (err error) { v := s.v3 + t.start = time.Now() s.captureMu.Lock() defer s.captureMu.Unlock() s.lifecycleMu.RLock() defer s.lifecycleMu.RUnlock() + t.locked = time.Now() s.mu.Lock() if s.closed || s.chunk.Load() != nil { s.mu.Unlock() @@ -96,10 +121,15 @@ func (s *WALStore) seedChunkFrontierV3(lsn uint64) error { } gen := v.recoverGen.Load() s.mu.Unlock() - if err := s.syncFile(nil, s.fd.Sync); err != nil { + t.validated = time.Now() + err = s.syncFile(nil, s.fd.Sync) + t.synced = time.Now() + if err != nil { return fmt.Errorf("storage: seed data sync: %w", err) } - if _, err := s.publishCheckpointV3(lsn, true, gen); err != nil { + _, err = s.publishCheckpointV3(lsn, true, gen) + t.published = time.Now() + if err != nil { return fmt.Errorf("storage: seed frontier %d: %w", lsn, err) } s.mu.Lock() diff --git a/seaweed-block/core/storage/chunk_frontier_v3_log_test.go b/seaweed-block/core/storage/chunk_frontier_v3_log_test.go new file mode 100644 index 0000000000..3d74b0dffb --- /dev/null +++ b/seaweed-block/core/storage/chunk_frontier_v3_log_test.go @@ -0,0 +1,160 @@ +package storage + +import ( + "bytes" + "log" + "regexp" + "strings" + "sync" + "testing" + "time" +) + +type seedLog struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (l *seedLog) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.buf.Write(p) +} + +func (l *seedLog) lines() []string { + l.mu.Lock() + defer l.mu.Unlock() + var out []string + for _, line := range strings.Split(l.buf.String(), "\n") { + if strings.Contains(line, "storage: seed frontier") { + out = append(out, line) + } + } + return out +} + +// Nonparallel: the standard logger is global. +func captureSeedLog(t *testing.T) *seedLog { + t.Helper() + l := &seedLog{} + old := log.Writer() + log.SetOutput(l) + t.Cleanup(func() { log.SetOutput(old) }) + return l +} + +var seedTimesLine = regexp.MustCompile(`storage: seed frontier 7: capture\+lifecycle lock wait [0-9.]+[a-zµ]+s, store mutex\+validation [0-9.]+[a-zµ]+s, data sync \(incl\. sync serialization\) [0-9.]+[a-zµ]+s, checkpoint publish [0-9.]+[a-zµ]+s, err=`) + +// A v3 seed logs its lock wait, data fsync and checkpoint publication +// times once per seed that did I/O, with its outcome; a no-op repeat and a +// refusal log nothing. +func TestWALStoreV3SeedLogsItsStageTimes(t *testing.T) { + t.Run("seeded", func(t *testing.T) { + logs := captureSeedLog(t) + s, _ := newMappedCheckpointStoreV3(t) + if err := s.SeedChunkFrontier(7); err != nil { + t.Fatal(err) + } + if err := s.SeedChunkFrontier(7); err != nil { // already seeded: no I/O + t.Fatal(err) + } + got := logs.lines() + if len(got) != 1 || !seedTimesLine.MatchString(got[0]) || !strings.HasSuffix(got[0], "err=") { + t.Fatalf("seed log lines %q; want one line with the three stage times and err=", got) + } + }) + t.Run("publish failed", func(t *testing.T) { + logs := captureSeedLog(t) + s, _ := newMappedCheckpointStoreV3(t) + fired := false + s.v3.testMapPrepared = func() { + if !fired { + fired = true + s.v3.recoverGen.Add(2) + } + } + if err := s.SeedChunkFrontier(7); err == nil { + t.Fatal("seed across a lifetime change succeeded") + } + got := logs.lines() + if len(got) != 1 || !seedTimesLine.MatchString(got[0]) || !strings.Contains(got[0], ErrMapCoverageStale.Error()) { + t.Fatalf("seed log lines %q; want one line with the stage times and the coverage error", got) + } + }) + t.Run("refused", func(t *testing.T) { + logs := captureSeedLog(t) + s, _ := newMappedCheckpointStoreV3(t) + writeSynced(t, s, 1, 1) + if err := s.SeedChunkFrontier(7); err == nil { + t.Fatal("seed over local writes succeeded") + } + if got := logs.lines(); len(got) != 0 { + t.Fatalf("a refused seed logged %q", got) + } + }) +} + +// blockingLog blocks its first write until released. +type blockingLog struct { + entered, release chan struct{} + once sync.Once +} + +func (b *blockingLog) Write(p []byte) (int, error) { + first := false + b.once.Do(func() { first = true }) + if first { + close(b.entered) + <-b.release + } + return len(p), nil +} + +// The seed's log line is written after the capture and lifecycle locks are +// released: while the log output is blocked, both are free. +func TestWALStoreV3SeedLogsOutsideTheStoreLocks(t *testing.T) { + s, _ := newMappedCheckpointStoreV3(t) + b := &blockingLog{entered: make(chan struct{}), release: make(chan struct{})} + old := log.Writer() + log.SetOutput(b) + t.Cleanup(func() { log.SetOutput(old) }) + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(b.release) }) } + done := make(chan error, 1) + joined := false + t.Cleanup(func() { // release the blocked writer, then join the seed, bounded + release() + if joined { + return + } + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("seed not joined") + } + }) + go func() { done <- s.SeedChunkFrontier(7) }() + select { + case <-b.entered: + case <-time.After(5 * time.Second): + t.Fatal("the seed never logged") + } + if !s.captureMu.TryLock() { + t.Fatal("captureMu held while the seed log output is blocked") + } + s.captureMu.Unlock() + if !s.lifecycleMu.TryLock() { + t.Fatal("lifecycleMu held while the seed log output is blocked") + } + s.lifecycleMu.Unlock() + release() + select { + case err := <-done: + joined = true + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("the seed did not finish after the log output was released") + } +}