Files
seaweedfs/weed/s3api/s3lifecycle/dailyrun/walk_checkpoint.go
T
Chris LuandClaude Opus 5.5 a963c1309c worker: purge the filer metadata log from a lifecycle job that keeps it past every TTL (#13101)
* worker: share the one-filer-per-store selection with other filer jobs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: add a meta_log_purge job that keeps the log past every TTL

The job deletes whole metadata log days once per filer store, keeping
every day that the longest filer.conf TTL, the longest S3 lifecycle rule,
a registered retention floor or a running replay job's cursor still
needs. A floor input that cannot be read stops the run before anything
is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: register meta_log_purge in the lifecycle lane

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* maintenance: stop purging the metadata log from the default scripts

The meta_log_purge job now deletes old log days, keeping what TTLs,
lifecycle rules and replay jobs still need. fs.log.purge stays for
manual use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: let an idle filer_ttl rule's read position release the log

filer_ttl no longer needs events up to read_ns, and an idle rule keeps an
old ts_ns while read_ns advances, so the floor follows the later of the
two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: cap min_retention_days so a huge value cannot overflow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: show the min_retention_days limit in the admin form

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: give a registered retention floor the store's filer client

A floor that only gets a context cannot tell which cluster or store it
answers for, so it cannot ask that cluster's master or read the store's
own settings. Pass the filer client the job already holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: keep the log an unfinished lifecycle walk will replay

A cold-start or recovery walk that resumes across runs rewinds its
shard cursor to the walk's start minus the longest lifecycle TTL once it
completes. Until then only its walk checkpoint records that start, so a
walk running for more than a day let the purge delete the creation
events the rewound replay reads. A checkpoint with buckets done or
partly walked now holds the floor at started_ns minus that TTL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: hold the walk start until the checkpoint goes stale

A walk clears its checkpoint in finish() before each of its shards saves
the rewound cursor, so a purge scan that read the old shard cursor and
then the cleared checkpoint saw neither. A cleared checkpoint keeps
started_ns, so every live checkpoint now holds the floor at its start
minus the longest lifecycle TTL. A finished one stops holding once it
has not been saved for cursorStaleAfter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: read walk checkpoints before the shard cursors they rewind

A purge scan that read a shard cursor, then a checkpoint that a later
walk had already replaced, saw neither the earlier walk's hold nor the
rewind its shards saved. A walk replaces its checkpoint only after the
previous walk's rewind is on disk, so reading the checkpoints first
always sees one of the two.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lifecycle: save a fresh walk's checkpoint at its first progress

A walk that progressed during its first save interval and then stalled
for more than a day had no checkpoint on disk, so the metadata log purge
saw nothing holding the days its completion replays. A fresh walk now
saves on its first finished entry or bucket; a resumed walk already has
its record on disk and keeps the interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* lifecycle: rewrite an unchanged shard cursor so its mtime stays fresh

A shard stuck on RETRY_LATER saved identical bytes each pass, and
SaveInsideFiler skips identical content, so the file's mtime aged past
the meta log purge's staleness cutoff while the shard still needed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: keep the log day a reader from the cursor lists first

Log files are named for their flush start, so a file from just before
midnight holds events after a cursor just past it. The reader backs off
one flush interval before choosing its first day; the purge now does too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: stop the meta log purge on an unreadable lifecycle policy

LoadCompileInputs reports a bucket whose lifecycle XML does not parse
separately from its error, so the purge used the shorter floors and
deleted days that bucket's rules may need once the policy is fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: read shard cursors with the replay's loader in the meta log purge

A shard cursor the replay refuses, such as an empty object, decoded as
a zero position and released the purge; it now stops the run instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: saturate the meta log purge's TTL plus a day

A lifecycle TTL near the largest duration wrapped negative once a day
was added, so the purge fell back to the shorter floors; the walk hold
at started_ns minus that TTL likewise dropped below zero and was lost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: leave disabled lifecycle rules out of the meta log purge floor

AllActivePriorStates activates every compiled rule, so a disabled rule
still held the log for its TTL, and disabling it could not release it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* worker: compute the meta log purge floor in SafeKeepFrom

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: fs.log.purge keeps the logs the meta log purge floor needs unless -force

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* shell: run the fs.log.purge floor test without a master client

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:33:26 -08:00

287 lines
9.1 KiB
Go

package dailyrun
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"sync/atomic"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/bootstrap"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/engine"
)
// WalkCheckpoint is the saved progress of an unfinished WalkBuckets
// call. ViewHash (engine.WalkContentHash) and Shards identify the walk;
// a walk with another identity starts over.
type WalkCheckpoint struct {
ViewHash [32]byte
Shards []int
// Done lists finished buckets; Resume maps a partly walked bucket
// to its bootstrap.Checkpoint.LastScannedPath.
Done []string
Resume map[string]string
// When the walk that began this record started; every bucket in it
// was listed after that.
StartedAt time.Time
// Set by LoadWalk; SaveWalk stamps the current time.
SavedAt time.Time
}
// WalkCheckpointPersister keeps one WalkCheckpoint per shard set.
type WalkCheckpointPersister interface {
LoadWalk(ctx context.Context, shards []int) (WalkCheckpoint, bool, error)
SaveWalk(ctx context.Context, cp WalkCheckpoint) error
}
type walkCheckpointFile struct {
Version int `json:"version"`
Shards []int `json:"shards"`
ViewHash []byte `json:"view_hash,omitempty"`
Done []string `json:"done,omitempty"`
Resume map[string]string `json:"resume,omitempty"`
StartedNs int64 `json:"started_ns,omitempty"`
SavedNs int64 `json:"saved_ns,omitempty"`
}
// WalkCheckpointPrefix starts the name of every walk checkpoint in CursorDir.
const WalkCheckpointPrefix = "walk-"
func walkCheckpointFileName(shards []int) string {
contiguous := len(shards) > 1
for i := 1; i < len(shards); i++ {
contiguous = contiguous && shards[i] == shards[i-1]+1
}
if contiguous {
return fmt.Sprintf(WalkCheckpointPrefix+"%02d-%02d.json", shards[0], shards[len(shards)-1])
}
parts := make([]string, len(shards))
for i, sh := range shards {
parts[i] = fmt.Sprintf("%02d", sh)
}
return WalkCheckpointPrefix + strings.Join(parts, "_") + ".json"
}
func (p *FilerCursorPersister) LoadWalk(ctx context.Context, shards []int) (WalkCheckpoint, bool, error) {
if p.Store == nil {
return WalkCheckpoint{}, false, errors.New("FilerCursorPersister: nil Store")
}
content, err := p.Store.Read(ctx, CursorDir, walkCheckpointFileName(shards))
if err != nil {
if errors.Is(err, filer_pb.ErrNotFound) {
return WalkCheckpoint{}, false, nil
}
return WalkCheckpoint{}, false, fmt.Errorf("walk checkpoint read: %w", err)
}
var f walkCheckpointFile
if err := json.Unmarshal(content, &f); err != nil {
return WalkCheckpoint{}, false, fmt.Errorf("walk checkpoint decode: %w", err)
}
if f.Version != cursorFileVersion {
return WalkCheckpoint{}, false, fmt.Errorf("walk checkpoint version: got %d, want %d", f.Version, cursorFileVersion)
}
if len(f.ViewHash) != 0 && len(f.ViewHash) != 32 {
return WalkCheckpoint{}, false, fmt.Errorf("walk checkpoint view_hash: got %d bytes, want 32", len(f.ViewHash))
}
cp := WalkCheckpoint{Shards: f.Shards, Done: f.Done, Resume: f.Resume, SavedAt: time.Unix(0, f.SavedNs)}
if f.StartedNs != 0 {
cp.StartedAt = time.Unix(0, f.StartedNs)
}
copy(cp.ViewHash[:], f.ViewHash)
return cp, true, nil
}
func (p *FilerCursorPersister) SaveWalk(ctx context.Context, cp WalkCheckpoint) error {
if p.Store == nil {
return errors.New("FilerCursorPersister: nil Store")
}
f := walkCheckpointFile{Version: cursorFileVersion, Shards: cp.Shards, Done: cp.Done, Resume: cp.Resume, SavedNs: time.Now().UnixNano()}
if !cp.StartedAt.IsZero() {
f.StartedNs = cp.StartedAt.UnixNano()
}
if cp.ViewHash != ([32]byte{}) {
f.ViewHash = cp.ViewHash[:]
}
content, err := json.Marshal(f)
if err != nil {
return fmt.Errorf("walk checkpoint encode: %w", err)
}
if err := p.Store.Save(ctx, CursorDir, walkCheckpointFileName(cp.Shards), content); err != nil {
return fmt.Errorf("walk checkpoint save: %w", err)
}
return nil
}
// walkCheckpointInterval spaces the saves of a running walk, in ns.
var walkCheckpointInterval atomic.Int64
// A walk that keeps failing saves on every attempt; a record this old
// belongs to a shard set that stopped walking, and resuming it would
// skip buckets walked long ago.
const walkCheckpointMaxAge = 7 * 24 * time.Hour
// A resumed walk that keeps failing without progress is treated as stuck
// once its record has not advanced for this long.
const walkCheckpointStallLimit = 24 * time.Hour
func init() { walkCheckpointInterval.Store(int64(30 * time.Second)) }
// walkProgress tracks one WalkBuckets call against its checkpoint.
type walkProgress struct {
store WalkCheckpointPersister
cp WalkCheckpoint
done map[string]bool
onDisk bool // a saved record a finished walk must clear
resumed bool
progressed bool
savedAt time.Time
}
func loadWalkProgress(ctx context.Context, store WalkCheckpointPersister, view *engine.Snapshot, shards []int, buckets []string) *walkProgress {
sorted := slices.Clone(shards)
slices.Sort(sorted)
now := time.Now()
// A fresh walk saves at its first progress: until then no record holds
// the metadata log its completion will replay.
w := &walkProgress{
store: store,
cp: WalkCheckpoint{ViewHash: engine.WalkContentHash(view), Shards: sorted, Resume: map[string]string{}, StartedAt: now},
done: map[string]bool{},
}
if store == nil {
return w
}
saved, found, err := store.LoadWalk(ctx, sorted)
if err != nil {
glog.Warningf("walker: shards %v: %v; walking every bucket", sorted, err)
w.onDisk = true
return w
}
if !found {
return w
}
w.onDisk = len(saved.Done) > 0 || len(saved.Resume) > 0
if saved.ViewHash != w.cp.ViewHash || !slices.Equal(saved.Shards, sorted) || saved.StartedAt.IsZero() || time.Since(saved.SavedAt) > walkCheckpointMaxAge {
return w
}
listed := make(map[string]bool, len(buckets))
for _, b := range buckets {
listed[b] = true
}
for _, b := range saved.Done {
if listed[b] {
w.done[b] = true
}
}
for b, pos := range saved.Resume {
if listed[b] && !w.done[b] {
w.cp.Resume[b] = pos
}
}
w.cp.SavedAt = saved.SavedAt
w.resumed = len(w.done) > 0 || len(w.cp.Resume) > 0
if w.resumed {
w.savedAt = now
w.cp.StartedAt = saved.StartedAt
glog.V(0).Infof("walker: shards %v resume with %d bucket(s) done and %d partly walked", sorted, len(w.done), len(w.cp.Resume))
}
return w
}
// track records each finished entry's position as the bucket's resume
// point, saving it every walkCheckpointInterval.
func (w *walkProgress) track(bucket string, list bootstrap.ListFunc) bootstrap.ListFunc {
if w.store == nil {
return list
}
return func(ctx context.Context, b, start string, cb func(*bootstrap.Entry) error) error {
return list(ctx, b, start, func(e *bootstrap.Entry) error {
if err := cb(e); err != nil {
return err
}
if e != nil && e.Resume != "" {
w.cp.Resume[bucket] = e.Resume
w.progressed = true
w.maybeSave(ctx)
}
return nil
})
}
}
func (w *walkProgress) bucketDone(ctx context.Context, bucket string) {
w.done[bucket] = true
delete(w.cp.Resume, bucket)
w.progressed = true
w.maybeSave(ctx)
}
func (w *walkProgress) maybeSave(ctx context.Context) {
if w.store == nil || time.Since(w.savedAt) < time.Duration(walkCheckpointInterval.Load()) {
return
}
w.savedAt = time.Now()
if err := w.save(ctx); err != nil {
glog.Warningf("walker: shards %v: %v", w.cp.Shards, err)
}
}
func (w *walkProgress) save(ctx context.Context) error {
cp := w.cp
cp.Done = make([]string, 0, len(w.done))
for b := range w.done {
cp.Done = append(cp.Done, b)
}
slices.Sort(cp.Done)
kept := len(cp.Done) > 0 || len(cp.Resume) > 0
// A save that reports an error may still have been written.
w.onDisk = w.onDisk || kept
if err := w.store.SaveWalk(ctx, cp); err != nil {
return err
}
w.onDisk = kept
return nil
}
// finish saves where the walk stopped, or clears the checkpoint when it
// completed. A resumed walk that failed without progress on a record
// older than walkCheckpointStallLimit is cleared too, so one stuck
// bucket cannot keep the finished ones from ever being walked again.
// Any other failed walk without progress has nothing new to record and
// leaves the file, read or not, alone.
func (w *walkProgress) finish(ctx context.Context, walkErr error) error {
if w.store == nil {
return nil
}
reset := walkErr == nil
if walkErr != nil && !w.progressed {
if ctx.Err() != nil || !w.resumed || time.Since(w.cp.SavedAt) < walkCheckpointStallLimit {
return nil
}
glog.Warningf("walker: shards %v made no progress since %v; the next walk starts over", w.cp.Shards, w.cp.SavedAt.Format(time.RFC3339))
reset = true
}
if reset {
clear(w.done)
clear(w.cp.Resume)
}
if !w.onDisk && len(w.done) == 0 && len(w.cp.Resume) == 0 {
return nil
}
saveCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := w.save(saveCtx); err != nil {
if walkErr == nil {
// Left in place, the record would skip buckets next walk.
return fmt.Errorf("walker: shards %v: %w", w.cp.Shards, err)
}
glog.Warningf("walker: shards %v: %v", w.cp.Shards, err)
}
return nil
}