feat: expose holder maintenance pass observations

This commit is contained in:
pingqiu committed 2026-11-29 00:13:36 -08:00
1 parent 7fe026461e
commit 7948d1a167
9 files changed
+358 -14

No files matched your search

@@ -9,6 +9,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// errNoLayoutHolder: the process has no holder identity for the volume yet
@@ -47,6 +48,9 @@ func newChunkMaintenance(cat *chunkstore.BCatalog, ref chunkstore.VolumeRef, cle
var session string
err = remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, s string) error {
session = s
// This generation is diagnostic only; it does not authorize removal.
head, _, _ := cat.ReadHead(ctx, ref)
defer func() { durable.ReportMaintenance(ctx, int64(res.ChunkPlanned), int64(res.ChunkRemoved), head.Gen) }()
var rerr error
res, rerr = cat.RemoveUnreachableAll(ctx, ref, me, s)
return rerr
@@ -0,0 +1,178 @@
package main
import (
"bytes"
"context"
"encoding/json"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil"
"path"
"testing"
"time"
)
func maintenanceJSON(t *testing.T, p *durable.DurableProvider) map[string]any {
t.Helper()
b, err := json.Marshal(p.DurableStatuses())
if err != nil {
t.Fatal(err)
}
var v []map[string]any
if err = json.Unmarshal(b, &v); err != nil {
t.Fatal(err)
}
c := v[0]["Chunk"].(map[string]any)
m, ok := c["Maintenance"].(map[string]any)
if !ok {
t.Fatalf("maintenance loop has no status: %s", b)
}
return m
}
func TestMaintenanceStatusRealPassAndTimeout(t *testing.T) {
for _, timeout := range []bool{false, true} {
t.Run(map[bool]string{false: "completed", true: "timeout"}[timeout], func(t *testing.T) {
ctx := context.Background()
fixture := testutil.NewLayoutFixture(t, "v1", 256, 16)
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, ChunkMaintenanceInterval: time.Hour, ChunkMaintenanceTimeout: 100 * time.Millisecond, ChunkStagger: true}
fixture.Configure(&cfg)
var p *durable.DurableProvider
entered, release := make(chan struct{}), make(chan struct{})
pass := newChunkMaintenance(fixture.Catalog, fixture.Ref, func(ctx context.Context) (layoutCleaner, error) {
r, e := p.LayoutRemote(ctx, "v1")
if e != nil {
return nil, e
}
return r.(layoutCleaner), nil
}, true, time.Now)
cfg.ChunkMaintenance = func(ctx context.Context, v string) error {
close(entered)
if timeout {
<-ctx.Done()
return ctx.Err()
}
select {
case <-release:
case <-ctx.Done():
return ctx.Err()
}
return pass(ctx, v)
}
var err error
p, err = durable.NewDurableProvider(cfg, cleaningView{})
if err != nil {
t.Fatal(err)
}
defer p.Close()
if _, err = p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
m := maintenanceJSON(t, p)
if m["passesOk"] != float64(0) || m["inProgress"] != false || m["currentStartNs"] != float64(0) || m["lastPass"] != nil {
t.Fatalf("initial=%v", m)
}
if !timeout {
st, e := fixture.Catalog.Store(fixture.Ref)
if e != nil {
t.Fatal(e)
}
data := bytes.Repeat([]byte{99}, 4096)
if e = fixture.Filer.CreateEntry(ctx, path.Join("/provider-test", fixture.Ref.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); e != nil {
t.Fatal(e)
}
if e = layout.EnsureObject(ctx, st, layout.NameChunk(0, data).Path(), data, "ended-session"); e != nil {
t.Fatal(e)
}
}
before, _, err := fixture.Catalog.ReadHead(ctx, fixture.Ref)
if err != nil {
t.Fatal(err)
}
if !p.KickMaintenance("v1") {
t.Fatal("kick refused")
}
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("not entered")
}
m = maintenanceJSON(t, p)
if m["inProgress"] != true || m["currentStartNs"].(float64) <= 0 {
t.Fatalf("running=%v", m)
}
if !timeout {
close(release)
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
m = maintenanceJSON(t, p)
if m["lastPass"] != nil {
break
}
time.Sleep(time.Millisecond)
}
last, ok := m["lastPass"].(map[string]any)
if !ok {
t.Fatalf("no completion: %v", m)
}
if m["inProgress"] != false || m["currentStartNs"] != float64(0) || last["atNs"].(float64) <= 0 {
t.Fatalf("ended=%v", m)
}
if timeout {
if m["passesOk"] != float64(0) || last["error"] == "" {
t.Fatalf("timeout=%v", m)
}
return
}
after, _, err := fixture.Catalog.ReadHead(ctx, fixture.Ref)
if err != nil {
t.Fatal(err)
}
if after.Gen != before.Gen+2 || m["passesOk"] != float64(1) || last["error"] != "" || last["headGen"].(float64) != float64(before.Gen+1) {
t.Fatalf("before=%d after=%d status=%v", before.Gen, after.Gen, m)
}
if last["planned"] != float64(1) || last["removed"] != float64(1) {
t.Fatalf("chunk counts=%v", last)
}
if _, ok := last["planned"]; !ok {
t.Fatal("planned absent")
}
if _, ok := last["removed"]; !ok {
t.Fatal("removed absent")
}
})
}
}
func TestMaintenanceStatusAbsentWithoutLoop(t *testing.T) {
fixture := testutil.NewLayoutFixture(t, "v1", 256, 16)
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16}
fixture.Configure(&cfg)
p, err := durable.NewDurableProvider(cfg, cleaningView{})
if err != nil {
t.Fatal(err)
}
defer p.Close()
if _, err = p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err = p.RecoverVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
b, err := json.Marshal(p.DurableStatuses())
if err != nil {
t.Fatal(err)
}
var v []map[string]any
if err = json.Unmarshal(b, &v); err != nil {
t.Fatal(err)
}
if _, exists := v[0]["Chunk"].(map[string]any)["Maintenance"]; exists {
t.Fatalf("disabled loop exposed Maintenance")
}
}
@@ -15,11 +15,13 @@ var cleanPage uint32 = 1000
// CleanResult counts names examined/deleted by this bounded pass, all kinds.
type CleanResult struct {
Shards int
Planned int
Removed int
Roots int
Segments int
ChunkPlanned int
ChunkRemoved int
Shards int
Planned int
Removed int
Roots int
Segments int
}
// The cursor is scheduling only: after a timeout a new session re-plans tags
@@ -142,8 +144,10 @@ func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me lay
names[i] = n.String()
}
res.Planned += len(page)
res.ChunkPlanned += len(page)
out, err := cleaner.Page(ctx, layout.PoolDir, shard, names)
res.Removed += len(out.Names)
res.ChunkRemoved += len(out.Names)
if out.After != "" {
cur.poolAfter = path.Base(out.After)
}
@@ -0,0 +1,72 @@
package durable
import (
"context"
"strings"
"sync"
"time"
)
// MaintenanceStatus is process-local observation of the holder's maintenance loop.
type MaintenanceStatus struct {
PassesOK int64 `json:"passesOk"` // completed passes since this holder process started
InProgress bool `json:"inProgress"` // a maintenance callback is running
CurrentStartNs int64 `json:"currentStartNs"` // unix ns start of the running pass; zero when idle
LastPass *MaintenancePassStatus `json:"lastPass,omitempty"` // absent until a pass ends
}
// MaintenancePassStatus describes the last completed or failed pass.
type MaintenancePassStatus struct {
AtNs int64 `json:"atNs"` // unix ns when the pass ended
Planned int64 `json:"planned"` // chunk objects considered for removal
Removed int64 `json:"removed"` // chunk objects removed
Error string `json:"error"` // one-line error; empty when completed
HeadGen uint64 `json:"headGen"` // observed cleaning HEAD generation; diagnostic only
}
type maintenanceSlot struct {
mu sync.Mutex
s MaintenanceStatus
result MaintenancePassStatus
}
type maintenanceContextKey struct{}
// ReportMaintenance supplies counts from the existing cleaning callback. It does
// not read or write storage, and cannot affect the pass's safety decisions.
func ReportMaintenance(ctx context.Context, planned, removed int64, headGen uint64) {
slot, _ := ctx.Value(maintenanceContextKey{}).(*maintenanceSlot)
if slot == nil {
return
}
slot.mu.Lock()
defer slot.mu.Unlock()
slot.result.Planned, slot.result.Removed, slot.result.HeadGen = planned, removed, headGen
}
func (m *maintenanceSlot) begin() {
m.mu.Lock()
defer m.mu.Unlock()
m.s.InProgress, m.s.CurrentStartNs = true, time.Now().UnixNano()
m.result = MaintenancePassStatus{}
}
func (m *maintenanceSlot) end(err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.result.AtNs = time.Now().UnixNano()
if err != nil {
m.result.Error = strings.Join(strings.Fields(err.Error()), " ")
} else {
m.s.PassesOK++
}
last := m.result
m.s.LastPass, m.s.InProgress, m.s.CurrentStartNs = &last, false, 0
}
func (m *maintenanceSlot) status() MaintenanceStatus {
m.mu.Lock()
defer m.mu.Unlock()
out := m.s
if out.LastPass != nil {
last := *out.LastPass
out.LastPass = &last
}
return out
}
@@ -0,0 +1,28 @@
package durable
import (
"context"
"errors"
"testing"
)
func TestMaintenanceStatusSnapshotIsIndependent(t *testing.T) {
var s maintenanceSlot
s.begin()
ReportMaintenance(context.WithValue(context.Background(), maintenanceContextKey{}, &s), 9, 4, 7)
s.end(errors.New("first line\nsecond line"))
a := s.status()
if a.LastPass.Error != "first line second line" || a.PassesOK != 0 || a.LastPass.Planned != 9 || a.LastPass.Removed != 4 || a.LastPass.HeadGen != 7 {
t.Fatalf("failed=%+v", a)
}
a.LastPass.Removed = 99
if s.status().LastPass.Removed != 4 {
t.Fatal("status aliases mutable history")
}
s.begin()
s.end(nil)
a = s.status()
if a.PassesOK != 1 || a.LastPass.Error != "" || a.LastPass.Planned != 0 || a.LastPass.HeadGen != 0 {
t.Fatalf("successful=%+v", a)
}
}
@@ -352,7 +352,8 @@ type volHandle struct {
cutWait *cutWaitSlot
// maintKick asks the running maintenance loop for one pass now (one
// buffered token: kicks coalesce); nil when the loop is off.
maintKick chan struct{}
maintKick chan struct{}
maintenance *maintenanceSlot
}
// VolumeStatus is a read-only diagnostic snapshot of one durable volume
@@ -393,7 +394,7 @@ type VolumeStatus struct {
// AwaitingAuthority: recovered, the layer waits for master authority to
// attach. Stats is zero until the layer is attached.
type ChunkStatus struct {
CurrentCut *storage.CurrentCutStatus `json:",omitempty"` // active cut phase; absent when idle
Maintenance *MaintenanceStatus `json:",omitempty"` // the holder maintenance loop; absent when disabled
Attached bool // the chunk layer is attached to the remote
AwaitingAuthority bool // recovered; the layer waits for master authority to attach
Fenced bool // a newer holder fenced this layer: it publishes nothing
@@ -402,6 +403,7 @@ type ChunkStatus struct {
HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir
ScheduledSnapshot *ScheduledSnapshotStatus `json:",omitempty"` // the scheduled-snapshot state; absent when the schedule is off or its loop has not started
CutSchedule *CutScheduleStatus `json:",omitempty"` // the automatic-cut timer's state; absent when the timer is off or its loop has not started
CurrentCut *storage.CurrentCutStatus `json:",omitempty"` // active cut phase; absent when idle
}
// CutScheduleStatus is the automatic-cut timer's view of host slot waits.
@@ -772,11 +774,12 @@ func durableIdentityConflict(got, want frontend.Identity) error {
// durable lineage latching without scraping logs.
func (p *DurableProvider) DurableStatuses() []VolumeStatus {
type chunkView struct {
head layout.HeadStore
layer storage.ChunkLayer
awaiting bool
snapshots *snapshotSlot
cutWait *cutWaitSlot
head layout.HeadStore
layer storage.ChunkLayer
awaiting bool
snapshots *snapshotSlot
cutWait *cutWaitSlot
maintenance *maintenanceSlot
}
p.mu.Lock()
handles := make(map[string]*volHandle, len(p.volumes))
@@ -784,7 +787,11 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus {
for volumeID, h := range p.volumes {
handles[volumeID] = h
if p.cfg.Impl == ImplWALStoreChunk {
chunks[volumeID] = chunkView{head: h.layoutHead, layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots, cutWait: h.cutWait}
cv := chunkView{head: h.layoutHead, layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots, cutWait: h.cutWait}
if h.chunkStop != nil {
cv.maintenance = h.maintenance
}
chunks[volumeID] = cv
}
}
p.mu.Unlock()
@@ -814,6 +821,10 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus {
cw := cv.cutWait.status(cs.Stats.CutSeq)
cs.CutSchedule = &cw
}
if cv.maintenance != nil {
m := cv.maintenance.status()
cs.Maintenance = &m
}
st.Chunk = cs
}
out = append(out, st)
@@ -441,8 +441,12 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st
}
if p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil {
h.maintKick = nil
h.maintenance = nil
} else if h.maintKick == nil {
h.maintKick = make(chan struct{}, 1)
if h.maintenance == nil {
h.maintenance = &maintenanceSlot{}
}
}
lin := h.chunkLineage
current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) }
@@ -1217,7 +1221,24 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
timeout = time.Minute
}
err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error {
return p.cfg.ChunkMaintenance(passCtx, volumeID)
p.mu.Lock()
h := p.volumes[volumeID]
var slot *maintenanceSlot
if h != nil && h.chunk == layer {
slot = h.maintenance
}
p.mu.Unlock()
if slot == nil {
return p.cfg.ChunkMaintenance(passCtx, volumeID)
}
slot.begin()
err := p.cfg.ChunkMaintenance(context.WithValue(passCtx, maintenanceContextKey{}, slot), volumeID)
observedErr := err
if observedErr == nil {
observedErr = passCtx.Err()
}
slot.end(observedErr)
return err
})
if err == nil && observed != nil {
seen = observed
@@ -21,3 +21,19 @@ describe that release; this change replaces those limits when it is released.
See [cleaning and the schedule command](../standalone-deployment.md#resuming-cleaning-passes).
Linux/race qualification and the production-layout CLI verifier evidence remain
separate gates. A live graph/count check is not a `verify`-clean result.
### Last holder maintenance pass
On the volume's host, `GET /status/durable?volume=V` reports
`Volumes[i].Chunk.Maintenance` when its maintenance loop is enabled. The listener
is loopback-only: an off-host checker reports "not checked here".
`passesOk` counts completed passes in this holder process. `inProgress` and
`currentStartNs` show a running pass (unix nanoseconds; zero start when idle).
`lastPass` is absent until a pass ends, then records `atNs` (unix nanosecond end),
`planned` and `removed` chunk-object counts, a one-line `error` (empty on success),
and `headGen`, the generation observed after opening the cleaning. Metadata
objects are excluded from the chunk counts. A pass that fails before entering
cleaning has zero counts and generation; these zeros do not prove a clean store.
A timed-out pass is recorded as an error and does not increment `passesOk`.
These are process-local observations, not authority or a safety decision.
+10
View File
@@ -218,6 +218,16 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`.
| `Volumes[].Chunk.CurrentCut.phase` | string | current pipeline phase |
| `Volumes[].Chunk.CurrentCut.started_at` | time (RFC 3339) | UTC start of the current phase visit |
| `Volumes[].Chunk.CurrentCut.attempt` | uint64 | attachment-local attempt identity, including failed attempts |
| `Volumes[].Chunk.Maintenance` | object | the holder maintenance loop; absent when disabled (omitted when empty) |
| `Volumes[].Chunk.Maintenance.passesOk` | int64 | completed passes since this holder process started |
| `Volumes[].Chunk.Maintenance.inProgress` | bool | a maintenance callback is running |
| `Volumes[].Chunk.Maintenance.currentStartNs` | int64 | unix ns start of the running pass; zero when idle |
| `Volumes[].Chunk.Maintenance.lastPass` | object | absent until a pass ends (omitted when empty) |
| `Volumes[].Chunk.Maintenance.lastPass.atNs` | int64 | unix ns when the pass ended |
| `Volumes[].Chunk.Maintenance.lastPass.planned` | int64 | chunk objects considered for removal |
| `Volumes[].Chunk.Maintenance.lastPass.removed` | int64 | chunk objects removed |
| `Volumes[].Chunk.Maintenance.lastPass.error` | string | one-line error; empty when completed |
| `Volumes[].Chunk.Maintenance.lastPass.headGen` | uint64 | observed cleaning HEAD generation; diagnostic only |
| `Volumes[].Chunk.Attached` | bool | the chunk layer is attached to the remote |
| `Volumes[].Chunk.AwaitingAuthority` | bool | recovered; the layer waits for master authority to attach |
| `Volumes[].Chunk.Fenced` | bool | a newer holder fenced this layer: it publishes nothing |