diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 0d690740f8..8a8e00b32b 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "path" + "strconv" "strings" "time" @@ -21,8 +22,8 @@ import ( const ( defaultChunkPath = "/swblock/chunks" - // Periodic HEAD publication bounds the host-loss recovery point. Automatic - // named snapshots remain explicit catalog operations. + // Periodic HEAD publication bounds the host-loss recovery point. Scheduled + // named snapshots are set by --chunk-snapshot-schedule. defaultChunkCaptureInterval = 0 defaultChunkMaintenanceInterval = time.Hour defaultChunkCutTimeout = 5 * time.Minute @@ -40,6 +41,7 @@ type chunkFlags struct { replication string captureInterval time.Duration maintenanceInterval time.Duration + snapshotSchedule snapshotSchedule automaticGC bool uploadConcurrency int hydrationWorkers int @@ -59,7 +61,7 @@ func validateChunkFlags(f flags) error { } if f.durableImpl != "walstore-chunk" { if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath || - c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || + c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.snapshotSchedule != defaultSnapshotSchedule || c.automaticGC || c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" { return errors.New("--chunk-* flags require --durable-impl=walstore-chunk") } @@ -111,6 +113,43 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi // chunkWiring is what --durable-impl=walstore-chunk dials once: the // provider's per-volume remotes, the catalog under the same base (VOLUME // entries, snapshots) and the client's closer. +// snapshotSchedule is --chunk-snapshot-schedule: "daily:N", "weekly:N" +// (one scheduled snapshot per period at a per-volume offset, the newest N +// kept) or "off". +type snapshotSchedule struct { + period time.Duration + keep int +} + +var defaultSnapshotSchedule = snapshotSchedule{period: 24 * time.Hour, keep: 7} + +func (s *snapshotSchedule) String() string { + switch s.period { + case 0: + return "off" + case 24 * time.Hour: + return fmt.Sprintf("daily:%d", s.keep) + case 7 * 24 * time.Hour: + return fmt.Sprintf("weekly:%d", s.keep) + } + return fmt.Sprintf("%s:%d", s.period, s.keep) +} + +func (s *snapshotSchedule) Set(v string) error { + if v == "off" { + *s = snapshotSchedule{} + return nil + } + name, count, ok := strings.Cut(v, ":") + periods := map[string]time.Duration{"daily": 24 * time.Hour, "weekly": 7 * 24 * time.Hour} + keep, err := strconv.Atoi(count) + if !ok || periods[name] == 0 || err != nil || keep < 1 || keep > 1000 { + return fmt.Errorf("%q: want daily:N, weekly:N (N from 1 to 1000) or off", v) + } + *s = snapshotSchedule{period: periods[name], keep: keep} + return nil +} + type chunkWiring struct { remoteFor func(volumeID string) (storage.ChunkRemote, error) catalog *chunkstore.Catalog diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index df897f59b0..fd82212594 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -135,3 +135,40 @@ func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err) } } + +// --chunk-snapshot-schedule: daily:7 by default; daily:N, weekly:N and off +// are accepted; anything else is refused; setting it without walstore-chunk +// is refused like the other chunk flags. +func TestChunkSnapshotScheduleFlag(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + chunk := func(extra ...string) []string { + return base(append([]string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"}, extra...)...) + } + d, err := parseFlags(chunk()) + if err != nil || d.chunk.snapshotSchedule != (snapshotSchedule{period: 24 * time.Hour, keep: 7}) { + t.Fatalf("default schedule %+v %v; want daily, keep 7", d.chunk.snapshotSchedule, err) + } + for v, want := range map[string]snapshotSchedule{ + "daily:3": {period: 24 * time.Hour, keep: 3}, + "weekly:4": {period: 7 * 24 * time.Hour, keep: 4}, + "off": {}, + } { + f, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)) + if err != nil || f.chunk.snapshotSchedule != want { + t.Fatalf("%s: %+v %v; want %+v", v, f.chunk.snapshotSchedule, err, want) + } + if got := f.chunk.snapshotSchedule.String(); got != v { + t.Fatalf("%s prints as %q", v, got) + } + } + for _, v := range []string{"hourly:7", "daily", "daily:0", "daily:x", "weekly:-1", "daily:1001", ""} { + if _, err := parseFlags(chunk("--chunk-snapshot-schedule=" + v)); err == nil { + t.Fatalf("%q accepted", v) + } + } + if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-snapshot-schedule=weekly:4")); err == nil { + t.Fatal("--chunk-snapshot-schedule accepted without walstore-chunk") + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 6f17805b6b..45e4af41e5 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -204,6 +204,8 @@ func parseFlags(args []string) (flags, error) { fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit") fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)") + f.chunk.snapshotSchedule = defaultSnapshotSchedule + fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off") fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") @@ -665,6 +667,10 @@ func run(f flags) int { cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout cfg.ChunkMaintenance = chunk.maintenance + if chunk.catalog != nil && f.chunk.snapshotSchedule.period > 0 { + cfg.ChunkSnapshotPeriod = f.chunk.snapshotSchedule.period + cfg.ChunkScheduledSnapshot = volume.ScheduledSnapshot(chunk.catalog, f.chunk.snapshotSchedule.keep) + } cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index 561a5fd06e..e3f950a2b3 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -23,6 +23,11 @@ import ( // - "pinned": an explicit keep. It is never expired by count or age, // only by its own ExpiresAtNs or an explicit delete. A snapshot with // ExpiresAtNs set is pinned whatever its class. +// - "scheduled": a scheduled snapshot. Retention keeps the newest K of +// this class, where K is the LabelScheduleKeep of the newest one +// (DefaultScheduleKeep when absent). +// They are not counted against KeepNewest, and the age and log-spaced +// keeps do not apply to them, so other snapshots are unaffected. // - "" (snapshots made before classes existed): treated as unpinned. // // The policy is stored on the VOLUME entry. Retain keeps @@ -61,8 +66,16 @@ import ( // it and frees the name. const ( - SnapshotClassSemantic = "semantic" - SnapshotClassPinned = "pinned" + SnapshotClassSemantic = "semantic" + SnapshotClassPinned = "pinned" + SnapshotClassScheduled = "scheduled" + + // LabelScheduleKeep, on a scheduled snapshot, is how many scheduled + // snapshots its schedule keeps (a decimal count). + LabelScheduleKeep = "swb.schedule.keep" + // DefaultScheduleKeep is the count kept when the newest scheduled + // snapshot carries no valid LabelScheduleKeep. + DefaultScheduleKeep = 7 CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" @@ -74,14 +87,14 @@ const ( extRetentionRev = "retention_rev" ) -// ValidateSnapshotClass refuses a class other than "", "semantic" and -// "pinned" (invalid_class). +// ValidateSnapshotClass refuses a class other than "", "semantic", +// "pinned" and "scheduled" (invalid_class). func ValidateSnapshotClass(class string) error { switch class { - case "", SnapshotClassSemantic, SnapshotClassPinned: + case "", SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled: return nil } - return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned) + return catErr(CodeInvalidClass, false, nil, "snapshot class %q: want %q, %q or %q", class, SnapshotClassSemantic, SnapshotClassPinned, SnapshotClassScheduled) } // Pinned reports whether the snapshot is an explicit keep. @@ -198,6 +211,7 @@ const ( keepHourly = "hourly" keepDaily = "daily" keepWeekly = "weekly" + keepScheduled = "scheduled_newest" reasonExpired = "expired" ) @@ -215,11 +229,27 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret }) nowNs := now.UnixNano() out := make([]RetentionDecision, len(ordered)) - unpinned := 0 + unpinned, scheduled := 0, 0 + scheduleKeep := -1 // read from the newest scheduled snapshot windows := map[string]bool{} for i, s := range ordered { pinned := s.Pinned() && (s.ExpiresAtNs == 0 || nowNs < s.ExpiresAtNs) d := RetentionDecision{Name: s.Name, Attempt: s.attempt, CreatedNs: s.CreatedNs, Class: s.Class, Pinned: pinned} + if !pinned && s.Class == SnapshotClassScheduled { + if scheduleKeep < 0 { + scheduleKeep = scheduleKeepOf(s) + } + if scheduled < scheduleKeep { + d.Reasons = append(d.Reasons, keepScheduled) + } + scheduled++ + d.Keep = len(d.Reasons) > 0 + if !d.Keep { + d.Reasons = []string{reasonExpired} + } + out[i] = d + continue + } if pinned { d.Reasons = append(d.Reasons, keepPinned) } else { @@ -263,6 +293,14 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []Ret return out } +// scheduleKeepOf is the count a scheduled snapshot's schedule keeps. +func scheduleKeepOf(s SnapshotInfo) int { + if n, err := strconv.Atoi(s.Labels[LabelScheduleKeep]); err == nil && n > 0 { + return n + } + return DefaultScheduleKeep +} + // RetentionFailure is the deletion that stopped a Retain pass. type RetentionFailure struct { Name string `json:"name"` diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index f329ed96be..1b2d538af0 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -381,3 +381,33 @@ func TestChunkSizeClipsLastChunk(t *testing.T) { } } } + +// Scheduled snapshots form their own class: retention keeps the newest K +// of them, K from the newest one's LabelScheduleKeep, and they neither +// count against KeepNewest nor get the age keeps; other snapshots are +// planned as before. +func TestPlanRetention_ScheduledClassKeepsItsOwnNewest(t *testing.T) { + now := retBase.Add(30 * 24 * time.Hour) + keep3 := map[string]string{LabelScheduleKeep: "3"} + var snaps []SnapshotInfo + for d := 0; d < 6; d++ { // one scheduled snapshot a day, the newest first at now-1h + snaps = append(snaps, snapAt(fmt.Sprintf("sched-%d", d), now.Add(-time.Hour-time.Duration(d)*24*time.Hour), SnapshotClassScheduled, time.Time{}, keep3)) + } + snaps = append(snaps, + snapAt("manual-new", now.Add(-2*time.Hour), "", time.Time{}, nil), + snapAt("manual-old", now.Add(-20*24*time.Hour), "", time.Time{}, nil)) + k := kept(planRetention(RetentionPolicy{KeepNewest: 2, KeepYoungerNs: int64(30 * 24 * time.Hour)}, snaps, now)) + for _, name := range []string{"sched-0", "sched-1", "sched-2", "manual-new", "manual-old"} { + if k[name] == nil { + t.Fatalf("kept %v; %s missing", k, name) + } + } + if len(k) != 5 { + t.Fatalf("kept %v; want the 3 newest scheduled and both manual (KeepNewest 2 is theirs alone)", k) + } + // Without a valid label the default count applies. + snaps[0].Labels = nil + if k := kept(planRetention(RetentionPolicy{}, snaps[:6], now)); len(k) != 6 { + t.Fatalf("kept %v with no label on the newest; want min(6, DefaultScheduleKeep)", k) + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go new file mode 100644 index 0000000000..150113db64 --- /dev/null +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule.go @@ -0,0 +1,247 @@ +package durable + +import ( + "context" + "errors" + "log" + "sync" + "time" + + "github.com/seaweedfs/seaweed-block/core/hostlimit" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +const ( + // snapshotRetryMin and snapshotRetryMax bound the backoff after a + // failed scheduled snapshot: it doubles from the minimum up to the cap. + snapshotRetryMin = time.Minute + snapshotRetryMax = time.Hour +) + +// SnapshotSkipRestoring is the skip reason of a volume still fetching the +// chunks its HEAD names (a restore's hydration). +const SnapshotSkipRestoring = "restoring" + +// SnapshotSkip is returned by a scheduled snapshot that was not attempted +// (for example, the volume is restoring). It is counted by Reason and not +// treated as a failure. +type SnapshotSkip struct{ Reason string } + +func (s *SnapshotSkip) Error() string { return "durable: scheduled snapshot skipped: " + s.Reason } + +// SnapshotFailure is a failed scheduled snapshot with its typed code. +type SnapshotFailure struct { + Code string + Err error +} + +func (f *SnapshotFailure) Error() string { + if f.Err != nil { + return "durable: scheduled snapshot failed: " + f.Code + ": " + f.Err.Error() + } + return "durable: scheduled snapshot failed: " + f.Code +} + +func (f *SnapshotFailure) Unwrap() error { return f.Err } + +// ScheduledSnapshotFailure is the last failed attempt. +type ScheduledSnapshotFailure struct { + // Code is the failure's code, as the control endpoint reports it. + Code string `json:"code"` + // AtNs is when the attempt failed. + AtNs int64 `json:"atNs"` +} + +// ScheduledSnapshotStatus is one volume's scheduled-snapshot state. +type ScheduledSnapshotStatus struct { + // PeriodNs is the schedule period; zero means off. + PeriodNs int64 `json:"periodNs"` + // LastOkNs is when the last scheduled snapshot succeeded; zero: none + // since the schedule started. + LastOkNs int64 `json:"lastOkNs"` + // NextDueNs is when the next attempt is due. + NextDueNs int64 `json:"nextDueNs"` + // LastFailure is the last failed attempt since the last success. + LastFailure *ScheduledSnapshotFailure `json:"lastFailure,omitempty"` + // Attempts counts the failed attempts since the last success. + Attempts int `json:"attempts"` + // Skipped counts attempts not made, by reason. + Skipped map[string]int64 `json:"skipped,omitempty"` + // Overdue reports that no scheduled snapshot succeeded within one + // period plus the retry cap, counted from the last success or, before + // any, from the start of the schedule. + Overdue bool `json:"snapshot_overdue"` +} + +// snapshotSchedule decides when one volume's scheduled snapshot is due and +// records the outcome of each attempt. Each slot starts at a multiple of +// the period (from the Unix epoch) plus the volume's offset, spread over +// the whole period and stable across restarts: "daily" is once per 24 h +// at a per-volume offset, not at a wall-clock hour. It is not safe for +// concurrent use. +type snapshotSchedule struct { + period time.Duration + offset time.Duration + started time.Time + lastOK time.Time + next time.Time + failure *ScheduledSnapshotFailure + attempts int + skipped map[string]int64 +} + +// newSnapshotSchedule starts vol's schedule at now. +func newSnapshotSchedule(vol string, period time.Duration, now time.Time) *snapshotSchedule { + s := &snapshotSchedule{period: period, offset: hostlimit.Phase(vol+":snapshot", period), started: now, skipped: map[string]int64{}} + s.next = s.slotAfter(now) + return s +} + +// slotAfter returns the first slot start strictly after t. +func (s *snapshotSchedule) slotAfter(t time.Time) time.Time { + p := int64(s.period) + base := t.UnixNano() / p * p + slot := time.Unix(0, base).Add(s.offset) + if !slot.After(t) { + slot = slot.Add(s.period) + } + return slot +} + +// due returns when the next attempt is due. +func (s *snapshotSchedule) due() time.Time { return s.next } + +// record records the outcome of an attempt made at now: nil is a +// success (the next attempt is the next slot); a *SnapshotSkip is counted +// by reason and retried after the backoff cap; any other error is a +// failure, recorded with its code, and retried with a doubling backoff. +func (s *snapshotSchedule) record(now time.Time, err error) { + var skip *SnapshotSkip + switch { + case err == nil: + s.lastOK, s.failure, s.attempts = now, nil, 0 + s.next = s.slotAfter(now) + case errors.As(err, &skip): + s.skipped[skip.Reason]++ + s.next = earlier(now.Add(snapshotRetryMax), s.slotAfter(now)) + default: + s.attempts++ + s.failure = &ScheduledSnapshotFailure{Code: snapshotFailureCode(err), AtNs: now.UnixNano()} + backoff := snapshotRetryMin << min(s.attempts-1, 30) + if backoff > snapshotRetryMax || backoff <= 0 { + backoff = snapshotRetryMax + } + s.next = now.Add(backoff) + } +} + +// status returns the schedule's state at now. +func (s *snapshotSchedule) status(now time.Time) ScheduledSnapshotStatus { + from := s.started + if !s.lastOK.IsZero() { + from = s.lastOK + } + st := ScheduledSnapshotStatus{PeriodNs: int64(s.period), NextDueNs: s.next.UnixNano(), Attempts: s.attempts, + Overdue: now.Sub(from) > s.period+snapshotRetryMax} + if !s.lastOK.IsZero() { + st.LastOkNs = s.lastOK.UnixNano() + } + if s.failure != nil { + f := *s.failure + st.LastFailure = &f + } + if len(s.skipped) > 0 { + st.Skipped = make(map[string]int64, len(s.skipped)) + for k, v := range s.skipped { + st.Skipped[k] = v + } + } + return st +} + +// snapshotFailureCode is a failure's typed code: a SnapshotFailure's own +// code, else "unknown". +func snapshotFailureCode(err error) string { + var f *SnapshotFailure + if errors.As(err, &f) && f.Code != "" { + return f.Code + } + return "unknown" +} + +func earlier(a, b time.Time) time.Time { + if a.Before(b) { + return a + } + return b +} + +// snapshotSlot guards one running loop's schedule: the loop records +// outcomes, status readers read it. +type snapshotSlot struct { + mu sync.Mutex + s *snapshotSchedule +} + +func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus { + sl.mu.Lock() + defer sl.mu.Unlock() + return sl.s.status(now) +} + +func (sl *snapshotSlot) due() time.Time { + sl.mu.Lock() + defer sl.mu.Unlock() + return sl.s.due() +} + +func (sl *snapshotSlot) record(now time.Time, err error) { + sl.mu.Lock() + defer sl.mu.Unlock() + sl.s.record(now, err) +} + +// chunkSnapshotLoop takes volumeID's scheduled snapshots while the +// attachment is current. Each attempt is one bounded pass: one urgent cut +// and the snapshot record. An attempt cut short by the loop's own end is +// not recorded. +func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) { + timer := time.NewTimer(time.Until(slot.due())) + defer timer.Stop() + timeout := 2 * p.cfg.ChunkCutTimeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + cut := func(ctx context.Context) (storage.ChunkHead, error) { + r, err := p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) + return r.Head, err + } + for { + select { + case <-ctx.Done(): + return + case <-timer.C: + } + if ctx.Err() != nil || layer.Fenced() || !current() { + return + } + at := time.Now() + var err error + if layer.Stats().AbsentChunks > 0 { + // Restoring: HEAD names chunks this volume has not fetched yet. + err = &SnapshotSkip{Reason: SnapshotSkipRestoring} + } else { + err = boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error { + return p.cfg.ChunkScheduledSnapshot(passCtx, volumeID, at, cut) + }) + } + if ctx.Err() != nil { + return + } + slot.record(time.Now(), err) + if err != nil { + log.Printf("durable: scheduled snapshot volume=%s: %v (next attempt %s)", volumeID, err, slot.due().UTC().Format(time.RFC3339)) + } + timer.Reset(time.Until(slot.due())) + } +} diff --git a/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go new file mode 100644 index 0000000000..3bd787a3e3 --- /dev/null +++ b/seaweed-block/core/frontend/durable/chunk_snapshot_schedule_test.go @@ -0,0 +1,108 @@ +package durable + +import ( + "errors" + "testing" + "time" +) + +var schedT0 = time.Date(2026, 11, 21, 12, 0, 0, 0, time.UTC) + +// Each slot starts at a period boundary plus the volume's offset, spread +// over the whole period and stable across restarts; the first attempt is +// the first slot after the start, and consecutive slots are one period +// apart. +func TestSnapshotSchedule_SlotsAreOffsetPerVolume(t *testing.T) { + day := 24 * time.Hour + offsets := map[time.Duration]bool{} + for _, vol := range []string{"v1", "v2", "v3", "a-much-longer-volume-name"} { + s := newSnapshotSchedule(vol, day, schedT0) + due := s.due() + if !due.After(schedT0) || due.Sub(schedT0) > day { + t.Fatalf("%s: first slot %v, want within one period after %v", vol, due, schedT0) + } + off := time.Duration(due.UnixNano() % int64(day)) + offsets[off] = true + if again := newSnapshotSchedule(vol, day, schedT0.Add(5*time.Hour)); time.Duration(again.due().UnixNano()%int64(day)) != off { + t.Fatalf("%s: offset changed across restarts", vol) + } + s.record(due, nil) + if s.due().Sub(due) != day { + t.Fatalf("%s: after a success the next slot is %v later; want one period", vol, s.due().Sub(due)) + } + } + if len(offsets) < 2 { + t.Fatalf("every volume got the same offset %v", offsets) + } +} + +// A restoring volume is skipped, counted by reason, and not treated as a +// failure; it is retried within the backoff cap, not a whole period later. +func TestSnapshotSchedule_RestoringIsSkippedAndCounted(t *testing.T) { + s := newSnapshotSchedule("v1", 24*time.Hour, schedT0) + at := s.due() + s.record(at, &SnapshotSkip{Reason: "restoring"}) + s.record(s.due(), &SnapshotSkip{Reason: "restoring"}) + st := s.status(s.due()) + if st.Skipped["restoring"] != 2 || st.Attempts != 0 || st.LastFailure != nil { + t.Fatalf("status %+v; want 2 restoring skips, no failure", st) + } + if gap := s.due().Sub(at); gap > 2*snapshotRetryMax { + t.Fatalf("after two skips the next attempt is %v later; want within the backoff cap", gap) + } +} + +// A failure is recorded with its typed code and retried after a backoff +// that doubles from one minute up to one hour; a success clears it and +// schedules the next slot. +func TestSnapshotSchedule_FailureIsTypedAndBacksOff(t *testing.T) { + s := newSnapshotSchedule("v1", 24*time.Hour, schedT0) + now := s.due() + want := []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 16 * time.Minute, 32 * time.Minute, time.Hour, time.Hour} + for i, w := range want { + s.record(now, &SnapshotFailure{Code: "remote_unavailable", Err: errors.New("filer down")}) + if got := s.due().Sub(now); got != w { + t.Fatalf("after failure %d the retry is %v later; want %v", i+1, got, w) + } + now = s.due() + } + st := s.status(now) + if st.Attempts != len(want) || st.LastFailure == nil || st.LastFailure.Code != "remote_unavailable" { + t.Fatalf("status %+v; want %d attempts and code remote_unavailable", st, len(want)) + } + s.record(now, errors.New("untyped")) + if st := s.status(now); st.LastFailure.Code != "unknown" { + t.Fatalf("untyped failure code %q; want unknown", st.LastFailure.Code) + } + s.record(now, nil) + st = s.status(now) + if st.Attempts != 0 || st.LastFailure != nil || st.LastOkNs != now.UnixNano() { + t.Fatalf("after a success: %+v; want the failure cleared and lastOk set", st) + } + if next := s.due(); next.Sub(now) > 24*time.Hour || next.UnixNano()%int64(24*time.Hour) != int64(s.offset) { + t.Fatalf("after a success the next attempt is %v; want the next slot", next) + } +} + +// The schedule is overdue once no scheduled snapshot succeeded within one +// period plus the retry cap: counted from the start before any success, +// then from the last success; the failure stays visible. +func TestSnapshotSchedule_OverdueAfterPeriodPlusRetryCap(t *testing.T) { + day, grace := 24*time.Hour, snapshotRetryMax + s := newSnapshotSchedule("v1", day, schedT0) + if s.status(schedT0.Add(day + grace)).Overdue { + t.Fatal("overdue at exactly one period plus the retry cap") + } + if !s.status(schedT0.Add(day + grace + time.Second)).Overdue { + t.Fatal("not overdue past one period plus the retry cap with no success") + } + ok := schedT0.Add(day) + s.record(ok, nil) + if s.status(ok.Add(day + grace)).Overdue { + t.Fatal("overdue within one period plus the retry cap of a success") + } + s.record(ok.Add(day), &SnapshotFailure{Code: "outcome_unknown"}) + if st := s.status(ok.Add(day + grace + time.Second)); !st.Overdue || st.LastFailure.Code != "outcome_unknown" { + t.Fatalf("status %+v; want overdue with the failure visible", st) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 06dbe352ee..f004ad80f4 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -179,6 +179,14 @@ type ProviderConfig struct { ChunkMaintenanceInterval time.Duration ChunkMaintenanceTimeout time.Duration ChunkMaintenance func(context.Context, string) error + // ChunkSnapshotPeriod schedules a named snapshot of each attached + // healthy volume once per period, at a per-volume offset (zero + // disables it). ChunkScheduledSnapshot takes one: it cuts through cut + // (one urgent cut) and records the snapshot of the HEAD cut returns. A + // *SnapshotSkip skips the attempt, counted by reason; a + // *SnapshotFailure carries the failure's code. + ChunkSnapshotPeriod time.Duration + ChunkScheduledSnapshot func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest // I/O stopped before it resumes or settles: the drain and final cut get // three quarters of it, the settlement of a failed cut the rest (the @@ -278,6 +286,9 @@ type volHandle struct { chunkDetach bool chunkStop context.CancelFunc chunkDone chan struct{} + // snapshots is the scheduled-snapshot state of the running loop, nil + // when the schedule is off. + snapshots *snapshotSlot } // VolumeStatus is a read-only diagnostic snapshot of one durable volume @@ -315,12 +326,13 @@ type VolumeStatus struct { // AwaitingAuthority: recovered, the layer waits for master authority to // attach. Stats is zero until the layer is attached. type ChunkStatus struct { - 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 - RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) - Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached - HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir + 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 + RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) + Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached + 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 } // NewDurableProvider constructs a provider. view is the ONLY @@ -343,6 +355,9 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil { return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback") } + if cfg.ChunkSnapshotPeriod < 0 || (cfg.ChunkSnapshotPeriod > 0 && cfg.ChunkScheduledSnapshot == nil) { + return nil, fmt.Errorf("durable: a chunk snapshot period must not be negative and requires its callback") + } if cfg.ChunkBlocks == 0 { cfg.ChunkBlocks = defaultChunkBlocks } @@ -571,8 +586,9 @@ func durableIdentityConflict(got, want frontend.Identity) error { // durable lineage latching without scraping logs. func (p *DurableProvider) DurableStatuses() []VolumeStatus { type chunkView struct { - layer storage.ChunkLayer - awaiting bool + layer storage.ChunkLayer + awaiting bool + snapshots *snapshotSlot } p.mu.Lock() handles := make(map[string]*volHandle, len(p.volumes)) @@ -580,7 +596,7 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { for volumeID, h := range p.volumes { handles[volumeID] = h if p.cfg.Impl == ImplWALStoreChunk { - chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0} + chunks[volumeID] = chunkView{layer: h.chunk, awaiting: h.waitGen != 0, snapshots: h.snapshots} } } p.mu.Unlock() @@ -596,6 +612,10 @@ func (p *DurableProvider) DurableStatuses() []VolumeStatus { if budget, ok := p.cfg.ChunkBudget.(interface{ Snapshot() any }); ok { cs.HostBudget = budget.Snapshot() } + if cv.snapshots != nil { + ss := cv.snapshots.status(time.Now()) + cs.ScheduledSnapshot = &ss + } st.Chunk = cs } out = append(out, st) diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2c194a39e8..64431d4dcc 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -320,14 +320,19 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v // startChunkLoop starts the periodic cuts of an attached layer, if configured // and not already running. The caller holds h.attachMu and p.mu. func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { - if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil { + snapshotsOn := p.cfg.ChunkSnapshotPeriod > 0 && p.cfg.ChunkScheduledSnapshot != nil + if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil) && !snapshotsOn) || h.chunkStop != nil { return } loopCtx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + h.snapshots = nil + if snapshotsOn { + h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())} + } lin := h.chunkLineage current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) } - go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current) + go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current, h.snapshots) } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { @@ -800,7 +805,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer // chunkBackground owns both workers and their cancellation. A fence is observed // even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN: // done closes only after every admitted worker has returned. -func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool) { +func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot) { defer close(done) defer cancel() var workers sync.WaitGroup @@ -816,6 +821,10 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca workers.Add(1) go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }() } + if snapshots != nil { + workers.Add(1) + go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots) }() + } timer := time.NewTicker(chunkSchedulePoll) defer timer.Stop() for ctx.Err() == nil { @@ -864,29 +873,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str if timeout <= 0 { timeout = time.Minute } - passCtx, cancel := context.WithTimeout(ctx, timeout) - // The projection has no change channel. One bounded watcher belongs to - // this pass, never to an individual tick; cancellation is joined below. - watchDone := make(chan struct{}) - go func() { - defer close(watchDone) - tick := time.NewTicker(chunkSchedulePoll) - defer tick.Stop() - for { - select { - case <-passCtx.Done(): - return - case <-tick.C: - if layer.Fenced() || !current() { - cancel() - return - } - } - } - }() - err := p.cfg.ChunkMaintenance(passCtx, volumeID) - cancel() - <-watchDone + err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error { + return p.cfg.ChunkMaintenance(passCtx, volumeID) + }) if err != nil && ctx.Err() == nil { log.Printf("durable: maintenance volume=%s: %v", volumeID, err) } @@ -895,6 +884,35 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str } } +// boundedPass runs fn with a context that ends after timeout, or as soon +// as the layer is fenced or the attachment is no longer current. The +// projection has no change channel: one bounded watcher belongs to the +// pass, never to an individual tick, and is joined before return. +func boundedPass(ctx context.Context, layer storage.ChunkLayer, current func() bool, timeout time.Duration, fn func(context.Context) error) error { + passCtx, cancel := context.WithTimeout(ctx, timeout) + watchDone := make(chan struct{}) + go func() { + defer close(watchDone) + tick := time.NewTicker(chunkSchedulePoll) + defer tick.Stop() + for { + select { + case <-passCtx.Done(): + return + case <-tick.C: + if layer.Fenced() || !current() { + cancel() + return + } + } + } + }() + err := fn(passCtx) + cancel() + <-watchDone + return err +} + func (p *DurableProvider) stopChunkLoop(h *volHandle) { p.mu.Lock() stop, done := h.chunkStop, h.chunkDone diff --git a/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go b/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go new file mode 100644 index 0000000000..336c6ee039 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_snapshot_schedule_test.go @@ -0,0 +1,188 @@ +package durable_test + +// The scheduled-snapshot loop through the real provider. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +type snapCalls struct { + mu sync.Mutex + heads []storage.ChunkHead + fail error +} + +func (c *snapCalls) take(ctx context.Context, _ string, _ time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { + c.mu.Lock() + fail := c.fail + c.mu.Unlock() + if fail != nil { + return fail + } + h, err := cut(ctx) + if err != nil { + return err + } + c.mu.Lock() + c.heads = append(c.heads, h) + c.mu.Unlock() + return nil +} + +func (c *snapCalls) count() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.heads) +} + +func snapScheduleProvider(t *testing.T, remote storage.ChunkRemote, period time.Duration, calls *snapCalls) *durable.DurableProvider { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkSnapshotPeriod: period, + ChunkScheduledSnapshot: calls.take, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + return p +} + +func scheduledStatus(t *testing.T, p *durable.DurableProvider) *durable.ScheduledSnapshotStatus { + t.Helper() + for _, st := range p.DurableStatuses() { + if st.VolumeID == "v1" && st.Chunk != nil { + return st.Chunk.ScheduledSnapshot + } + } + return nil +} + +func waitFor(t *testing.T, d time.Duration, what string, ok func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for !ok() { + if time.Now().After(deadline) { + t.Fatalf("%s not reached within %v", what, d) + } + time.Sleep(20 * time.Millisecond) + } +} + +// With a schedule, the attached volume's snapshot is taken at its slot by +// one cut that publishes the dirty data, the snapshot callback gets that +// cut's HEAD, and the status shows the success and the next slot. A failure +// is visible in the status with its code. +func TestWALStoreChunk_ScheduledSnapshotCutsAndReports(t *testing.T) { + const period = 2 * time.Second + remote := storage.NewMemChunkRemote() + calls := &snapCalls{} + p := snapScheduleProvider(t, remote, period, calls) + s := openRecovered(t, p) + if _, err := s.Write(1, block(0x5A)); err != nil { + t.Fatal(err) + } + waitFor(t, 3*period, "the first scheduled snapshot", func() bool { return calls.count() >= 1 }) + calls.mu.Lock() + h := calls.heads[0] + calls.mu.Unlock() + if remoteHead := headGen(t, remote); h.Gen == 0 || h.Gen > remoteHead.Gen || len(h.Chunks) == 0 { + t.Fatalf("snapshot HEAD gen %d with %d chunks (remote gen %d); want the cut that published the write", h.Gen, len(h.Chunks), remoteHead.Gen) + } + waitFor(t, time.Second, "the success in the status", func() bool { + st := scheduledStatus(t, p) + return st != nil && st.LastOkNs > 0 + }) + st := scheduledStatus(t, p) + if st.PeriodNs != int64(period) || st.NextDueNs <= st.LastOkNs || st.Overdue || st.LastFailure != nil { + t.Fatalf("status %+v; want period %v, next slot after the success, not overdue, no failure", st, period) + } + + calls.mu.Lock() + calls.fail = &durable.SnapshotFailure{Code: "remote_unavailable", Err: errors.New("filer down")} + calls.mu.Unlock() + waitFor(t, 3*period, "the failure in the status", func() bool { + st := scheduledStatus(t, p) + return st != nil && st.LastFailure != nil + }) + if st := scheduledStatus(t, p); st.LastFailure.Code != "remote_unavailable" || st.Attempts < 1 { + t.Fatalf("status %+v; want the typed failure and its attempt count", st) + } +} + +// With the schedule off (period zero), no snapshot is attempted and the +// status has no scheduled-snapshot section. +func TestWALStoreChunk_ScheduledSnapshotOffTakesNone(t *testing.T) { + remote := storage.NewMemChunkRemote() + calls := &snapCalls{} + p := snapScheduleProvider(t, remote, 0, calls) + s := openRecovered(t, p) + if _, err := s.Write(1, block(0x01)); err != nil { + t.Fatal(err) + } + for i := 0; i < 10; i++ { + if calls.count() != 0 || scheduledStatus(t, p) != nil { + t.Fatal("a scheduled snapshot ran with the schedule off") + } + time.Sleep(100 * time.Millisecond) + } +} + +// A snapshot period without its callback is refused. +func TestWALStoreChunk_ScheduledSnapshotNeedsItsCallback(t *testing.T) { + _, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkSnapshotPeriod: time.Hour, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }, + }, v1View()) + if err == nil { + t.Fatal("a snapshot period without its callback was accepted") + } +} + +// A volume still fetching the chunks its HEAD names (a fresh host starting +// from the remote HEAD) is restoring: its scheduled attempts are skipped, +// counted by reason, and no snapshot is taken. +func TestWALStoreChunk_ScheduledSnapshotSkipsARestoringVolume(t *testing.T) { + const period = 2 * time.Second + remote := storage.NewMemChunkRemote() + view := v1View() + first := chunkProvider(t, t.TempDir(), remote, view, 0) + s := openRecovered(t, first) + if _, err := s.Write(33, block(0x33)); err != nil { + t.Fatal(err) + } + if err := first.MakeVolumeRemoteDurable(context.Background(), "v1", 1); err != nil { + t.Fatal(err) + } + _ = first.Close() + calls := &snapCalls{} + fresh, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, + NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + ChunkSnapshotPeriod: period, ChunkScheduledSnapshot: calls.take, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = fresh.Close() }) + openRecovered(t, fresh) + waitFor(t, 3*period, "a restoring skip", func() bool { + st := scheduledStatus(t, fresh) + return st != nil && st.Skipped[durable.SnapshotSkipRestoring] >= 1 + }) + if st := scheduledStatus(t, fresh); calls.count() != 0 || st.LastFailure != nil || st.Attempts != 0 { + t.Fatalf("restoring volume: %d snapshots, status %+v; want none taken and no failure", calls.count(), st) + } +} diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c6cd4f7525..89c386d3c4 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -634,16 +634,27 @@ func (c *chunkControl) Snapshot(ctx context.Context, volumeID string, req ChunkS } sreq := chunkstore.SnapshotRequest{Name: req.Name, RequestID: req.RequestID, Labels: req.Labels, Consistency: req.Consistency, ExpiresAtNs: req.ExpiresAtNs, CreatedBy: "blockvolume", Class: req.Class} - if info, replayed, err := c.cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { + return sealSnapshot(ctx, c.cat, volumeID, sreq, func(ctx context.Context) (storage.ChunkHead, error) { + // A named seal is urgent even without a minimum LSN. + r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) + return r.Head, err + }) +} + +// sealSnapshot resolves sreq against the catalog first: a retry of a +// recorded request returns that snapshot and another request for the name +// fails, both without cutting. Only a free name is cut, and the HEAD that +// cut installed is stored. +func sealSnapshot(ctx context.Context, cat *chunkstore.Catalog, volumeID string, sreq chunkstore.SnapshotRequest, cut func(context.Context) (storage.ChunkHead, error)) (chunkstore.SnapshotInfo, error) { + if info, replayed, err := cat.SnapshotReplay(ctx, volumeID, sreq); err != nil || replayed { return info, err } - // A named seal is urgent even without a minimum LSN. - r, err := c.p.CutVolume(hostlimit.WithClass(ctx, hostlimit.Urgent), volumeID, 0) + head, err := cut(ctx) if err != nil { return chunkstore.SnapshotInfo{}, err } sreq.SourceReadAt = time.Now() - return c.cat.CreateSnapshot(ctx, volumeID, sreq, r.Head) + return cat.CreateSnapshot(ctx, volumeID, sreq, head) } func (c *chunkControl) ListSnapshots(ctx context.Context, volumeID string, opts chunkstore.ListOptions) ([]chunkstore.SnapshotInfo, string, error) { diff --git a/seaweed-block/core/host/volume/chunk_control_adapter_test.go b/seaweed-block/core/host/volume/chunk_control_adapter_test.go index 51f9a57876..ce1ef835e7 100644 --- a/seaweed-block/core/host/volume/chunk_control_adapter_test.go +++ b/seaweed-block/core/host/volume/chunk_control_adapter_test.go @@ -67,6 +67,14 @@ func (f *fakeChunkProvider) DetachVolume(context.Context, string) (storage.Chunk } func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { + t.Helper() + fp, cat := adapterCatalog(t) + return fp, NewChunkControl(fp, cat) +} + +// adapterCatalog is a catalog holding volume v1 and a provider whose cut +// installs a published HEAD of v1. +func adapterCatalog(t *testing.T) (*fakeChunkProvider, *chunkstore.Catalog) { t.Helper() head := storage.ChunkHead{Gen: 3, Epoch: 2, Holder: "r1", RemoteLSN: 9, State: storage.ChunkHeadActive, Chunks: map[uint64]storage.ChunkRef{0: {Key: "chunks/e2/c0/k1"}, 5: {Key: "chunks/e2/c5/k2"}}} @@ -87,7 +95,7 @@ func adapterFixture(t *testing.T) (*fakeChunkProvider, ChunkControl) { if _, err := cat.EnsureVolume(context.Background(), "v1", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil { t.Fatal(err) } - return fp, NewChunkControl(fp, cat) + return fp, cat } // Snapshot validates before it cuts, then stores the HEAD its cut diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go new file mode 100644 index 0000000000..f75c995d00 --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot.go @@ -0,0 +1,38 @@ +package volume + +import ( + "context" + "strconv" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// ScheduledSnapshotName is the name of the scheduled snapshot attempted +// at at (UTC, to the second). +func ScheduledSnapshotName(at time.Time) string { + return "sched-" + at.UTC().Format("20060102T150405Z") +} + +// ScheduledSnapshot returns the provider's scheduled-snapshot callback +// (durable.ProviderConfig.ChunkScheduledSnapshot) over cat. Each attempt +// is one named snapshot of class "scheduled", labelled with keep (the +// count retention keeps), sealed through the same path as an explicit +// named snapshot: the request is resolved first, then one cut, then the +// record of that cut's HEAD. A failure carries the code the control +// endpoint would report. +func ScheduledSnapshot(cat *chunkstore.Catalog, keep int) func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error { + labels := map[string]string{chunkstore.LabelScheduleKeep: strconv.Itoa(keep)} + return func(ctx context.Context, volumeID string, at time.Time, cut func(context.Context) (storage.ChunkHead, error)) error { + name := ScheduledSnapshotName(at) + sreq := chunkstore.SnapshotRequest{Name: name, RequestID: name, Labels: labels, + CreatedBy: "blockvolume-schedule", Class: chunkstore.SnapshotClassScheduled} + if _, err := sealSnapshot(ctx, cat, volumeID, sreq, cut); err != nil { + _, code, _ := chunkErrorCode(err) + return &durable.SnapshotFailure{Code: code, Err: err} + } + return nil + } +} diff --git a/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go b/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go new file mode 100644 index 0000000000..4290703cee --- /dev/null +++ b/seaweed-block/core/host/volume/chunk_scheduled_snapshot_test.go @@ -0,0 +1,69 @@ +package volume + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A scheduled snapshot is one named snapshot of class "scheduled", named +// for its attempt time and labelled with the schedule's keep, recording +// exactly the HEAD its own cut installed. A retry of the same attempt +// replays without cutting again. +func TestScheduledSnapshot_SealsTheCutHeadAsScheduled(t *testing.T) { + ctx := context.Background() + fp, cat := adapterCatalog(t) + take := ScheduledSnapshot(cat, 7) + at := time.Date(2026, 11, 21, 3, 4, 5, 0, time.UTC) + cuts := 0 + cut := func(ctx context.Context) (storage.ChunkHead, error) { + cuts++ + r, err := fp.CutVolume(ctx, "v1", 0) + return r.Head, err + } + if err := take(ctx, "v1", at, cut); err != nil { + t.Fatal(err) + } + if err := take(ctx, "v1", at, cut); err != nil || cuts != 1 { + t.Fatalf("retry of the same attempt: %v, %d cuts; want a replay without a second cut", err, cuts) + } + list, _, err := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}) + if err != nil || len(list) != 1 { + t.Fatalf("list: %+v %v", list, err) + } + s := list[0] + if s.Name != "sched-20261121T030405Z" || s.Class != chunkstore.SnapshotClassScheduled || s.Labels[chunkstore.LabelScheduleKeep] != "7" || + s.HeadGen != fp.cut.Head.Gen || s.HeadEpoch != fp.cut.Head.Epoch || s.CutLSN != fp.cut.Head.RemoteLSN { + t.Fatalf("snapshot %+v; want sched-20261121T030405Z, class scheduled, keep 7, the cut's HEAD", s) + } +} + +// A failed cut is reported as a durable.SnapshotFailure with the code +// the control endpoint gives the same error, and records nothing. +func TestScheduledSnapshot_FailureCarriesTheEndpointCode(t *testing.T) { + ctx := context.Background() + _, cat := adapterCatalog(t) + take := ScheduledSnapshot(cat, 7) + for _, c := range []struct { + err error + code string + }{ + {storage.ErrChunkLayerFenced, codeFenced}, + {storage.ErrChunkRemoteUnavailable, chunkstore.CodeRemoteUnavailable}, + {context.DeadlineExceeded, chunkstore.CodeDeadlineExceeded}, + } { + err := take(ctx, "v1", time.Now(), func(context.Context) (storage.ChunkHead, error) { return storage.ChunkHead{}, c.err }) + var f *durable.SnapshotFailure + if !errors.As(err, &f) || f.Code != c.code || !errors.Is(err, c.err) { + t.Fatalf("cut error %v: got %v; want a SnapshotFailure with code %s", c.err, err, c.code) + } + } + if list, _, _ := cat.ListSnapshots(ctx, "v1", chunkstore.ListOptions{}); len(list) != 0 { + t.Fatalf("failed attempts recorded %+v", list) + } +} diff --git a/seaweed-block/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index a40f5f7c7f..5d0a211566 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -111,6 +111,10 @@ SWB_CHUNK_REPLICATION= # --chunk-capture-interval (default 0: no timer). Automatic cut once this long # has passed since the last successful cut, e.g. 15m as a host-loss safety net. SWB_CHUNK_CAPTURE_INTERVAL=0 +# --chunk-snapshot-schedule (default daily:7). Scheduled named snapshots: +# daily:N or weekly:N takes one snapshot per period at a per-volume offset +# (not at a wall-clock hour) and keeps the newest N; off disables them. +SWB_CHUNK_SNAPSHOT_SCHEDULE=daily:7 # --chunk-upload-concurrency (default 8; 1..64). Parallel dirty-chunk uploads. SWB_CHUNK_UPLOAD_CONCURRENCY=8 # --chunk-control-endpoint (default false). Expose /chunk/* (cut, snapshot, diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index c15dcbb0a2..50a3ca26f8 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -59,6 +59,7 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-collection=${SWB_CHUNK_COLLECTION} \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ + --chunk-snapshot-schedule=${SWB_CHUNK_SNAPSHOT_SCHEDULE} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index 28675f37ce..6cbcb6a6fa 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -58,6 +58,7 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-collection=${SWB_CHUNK_COLLECTION} \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ + --chunk-snapshot-schedule=${SWB_CHUNK_SNAPSHOT_SCHEDULE} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d5318a20df..a515c581d5 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -255,7 +255,11 @@ Snapshots of the target are refused in `Forking` and `Restoring`. ### Attached-volume scheduling Periodic HEAD capture is off by default (opt-in; when set, at least 5 -minutes), and retention runs every hour. Named snapshots remain explicit. +minutes), and retention runs every hour. Named snapshots are explicit, plus scheduled snapshots +(`--chunk-snapshot-schedule`, default `daily:7`): one snapshot per period at a +per-volume offset (not at a wall-clock hour), class `scheduled`, the newest N +kept by retention; a restoring volume is skipped and counted, and a failed +attempt is retried with backoff and visible in status (`snapshot_overdue`). A five-minute context covers the whole cut; completed immutable uploads survive an expired attempt only under matching version/HEAD generation. Automatic GC is opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0c69765881..6cdcff09a5 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -289,8 +289,10 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | +| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | | published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` | | published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 1e1f3e1d4f..1a4df0c0ff 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -123,6 +123,7 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_CHUNK_PATH` | `--chunk-path` | `/swblock/chunks` | Filer directory, one directory per volume | | `SWB_CHUNK_COLLECTION`, `SWB_CHUNK_REPLICATION` | `--chunk-collection`, `--chunk-replication` | empty (filer default) | Placement of chunk needles | | `SWB_CHUNK_CAPTURE_INTERVAL` | `--chunk-capture-interval` | `0` (no timer) | Automatic cut interval, e.g. `15m` | +| `SWB_CHUNK_SNAPSHOT_SCHEDULE` | `--chunk-snapshot-schedule` | `daily:7` | Scheduled named snapshots: `daily:N` or `weekly:N` (one per period at a per-volume offset, the newest N kept), or `off` | | `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) | | `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener | | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 02d7a1d468..33559866a3 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -276,6 +276,16 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | | `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot` | object | the scheduled-snapshot state; absent when the schedule is off or its loop has not started (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot.periodNs` | int64 | PeriodNs is the schedule period; zero means off. | +| `Volumes[].Chunk.ScheduledSnapshot.lastOkNs` | int64 | LastOkNs is when the last scheduled snapshot succeeded; zero: none since the schedule started. | +| `Volumes[].Chunk.ScheduledSnapshot.nextDueNs` | int64 | NextDueNs is when the next attempt is due. | +| `Volumes[].Chunk.ScheduledSnapshot.lastFailure` | object | LastFailure is the last failed attempt since the last success. (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot.lastFailure.code` | string | Code is the failure's code, as the control endpoint reports it. | +| `Volumes[].Chunk.ScheduledSnapshot.lastFailure.atNs` | int64 | AtNs is when the attempt failed. | +| `Volumes[].Chunk.ScheduledSnapshot.attempts` | int | Attempts counts the failed attempts since the last success. | +| `Volumes[].Chunk.ScheduledSnapshot.skipped{}` | int64 | Skipped counts attempts not made, by reason. (omitted when empty) | +| `Volumes[].Chunk.ScheduledSnapshot.snapshot_overdue` | bool | Overdue reports that no scheduled snapshot succeeded within one period plus the retry cap, counted from the last success or, before any, from the start of the schedule. | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) |