diff --git a/weed/worker/tasks/filer_ttl/handler.go b/weed/worker/tasks/filer_ttl/handler.go index be77017e2b..3868076346 100644 --- a/weed/worker/tasks/filer_ttl/handler.go +++ b/weed/worker/tasks/filer_ttl/handler.go @@ -200,23 +200,20 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ }) stats := &walkStats{} - var failed []string + var resumed string err := pb.WithGrpcFilerClient(true, 0, pb.ServerAddress(address), h.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { - for _, prefix := range prefixes { - if err := ctx.Err(); err != nil { - return err - } - if err := walkLocationPrefix(ctx, client, prefix, stats); err != nil { - failed = append(failed, fmt.Sprintf("%s: %v", prefix, err)) - } + var walkErr error + resumed, walkErr = walkLocationPrefixes(ctx, client, prefixes, stats) + if walkErr != nil { + return fmt.Errorf("walk %w", walkErr) } return nil }) - if err == nil && len(failed) > 0 { - err = fmt.Errorf("walk %s", strings.Join(failed, "; ")) - } summary := fmt.Sprintf("filer %s: walked %d TTL path(s), %d directories, %d live entries", address, len(prefixes), stats.directories, stats.entries) + if resumed != "" { + summary += fmt.Sprintf(", resumed from %s", resumed) + } completed := &plugin_pb.JobCompleted{ JobId: request.Job.JobId, JobType: jobType, diff --git a/weed/worker/tasks/filer_ttl/handler_test.go b/weed/worker/tasks/filer_ttl/handler_test.go index 59637c3db0..731736ec95 100644 --- a/weed/worker/tasks/filer_ttl/handler_test.go +++ b/weed/worker/tasks/filer_ttl/handler_test.go @@ -2,14 +2,17 @@ package filer_ttl import ( "context" + "encoding/json" "fmt" "net" "net/http" "net/http/httptest" + "slices" "sort" "strings" "sync" "testing" + "time" "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" @@ -32,10 +35,48 @@ type ttlFiler struct { mu sync.Mutex dirs map[string]map[string]*filer_pb.Entry expired map[string]bool + files map[string]*filer_pb.Entry + lists map[string]int + failList func(*filer_pb.ListEntriesRequest) bool } func newTTLFiler(signature int32) *ttlFiler { - return &ttlFiler{signature: signature, dirs: map[string]map[string]*filer_pb.Entry{}, expired: map[string]bool{}} + return &ttlFiler{signature: signature, dirs: map[string]map[string]*filer_pb.Entry{}, expired: map[string]bool{}, files: map[string]*filer_pb.Entry{}, lists: map[string]int{}} +} + +func (f *ttlFiler) checkpoint() *walkCheckpoint { + f.mu.Lock() + defer f.mu.Unlock() + entry := f.files[checkpointDir+"/"+checkpointName(f.signature)] + if entry == nil { + return nil + } + var cp walkCheckpoint + if err := json.Unmarshal(entry.Content, &cp); err != nil { + return nil + } + return &cp +} + +func (f *ttlFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.files[req.Directory+"/"+req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry) + return &filer_pb.CreateEntryResponse{}, nil +} + +func (f *ttlFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.files[req.Directory+"/"+req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry) + return &filer_pb.UpdateEntryResponse{}, nil +} + +func (f *ttlFiler) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) { + f.mu.Lock() + defer f.mu.Unlock() + delete(f.files, req.Directory+"/"+req.Name) + return &filer_pb.DeleteEntryResponse{}, nil } func (f *ttlFiler) add(fullPath string, isDirectory, expired bool) { @@ -66,6 +107,12 @@ func (f *ttlFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConf } func (f *ttlFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + f.mu.Lock() + file := f.files[req.Directory+"/"+req.Name] + f.mu.Unlock() + if file != nil { + return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(file).(*filer_pb.Entry)}, nil + } if req.Directory != filer.DirectoryEtcSeaweedFS || req.Name != filer.FilerConfName || f.conf == nil { return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error()) } @@ -93,6 +140,14 @@ func (f *ttlFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb dir = "/" } f.mu.Lock() + if f.failList != nil && f.failList(req) { + f.failList = nil + f.mu.Unlock() + return status.Error(codes.Unavailable, "listing interrupted") + } + if req.StartFromFileName == "" { + f.lists[dir]++ + } var names []string for name := range f.dirs[dir] { if strings.HasPrefix(name, req.Prefix) && name > req.StartFromFileName { @@ -324,3 +379,106 @@ func TestExecuteRemovesExpiredRowsNobodyVisits(t *testing.T) { t.Fatalf("rows left = %d, want %d", got, 8+1+walkPageSize+100) } } + +func executeOn(t *testing.T, address string, prefixes ...string) *plugin_pb.JobCompleted { + t.Helper() + sender := &executeRecorder{} + if err := newTestHandler().Execute(context.Background(), &plugin_pb.ExecuteJobRequest{Job: &plugin_pb.JobSpec{ + JobType: jobType, + Parameters: map[string]*plugin_pb.ConfigValue{ + filerAddressParam: {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: address}}, + locationPrefixesParam: {Kind: &plugin_pb.ConfigValue_StringList{StringList: &plugin_pb.StringList{Values: prefixes}}}, + }, + }}, sender); err != nil { + t.Fatal(err) + } + if len(sender.completed) != 1 { + t.Fatalf("completed = %v", sender.completed) + } + return sender.completed[0] +} + +func resumeTree() *ttlFiler { + f := newTTLFiler(1) + for _, dir := range []string{"/a/d1", "/a/d2", "/a/d3", "/b"} { + f.add(dir, true, false) + f.add(dir+"/zz-old.bin", false, true) + } + for i := 0; i < 2*walkPageSize+5; i++ { + f.add(fmt.Sprintf("/a/d2/f-%05d", i), false, false) + } + return f +} + +func TestExecuteResumesWhereAFailedWalkStopped(t *testing.T) { + saved := checkpointInterval + checkpointInterval = 0 + t.Cleanup(func() { checkpointInterval = saved }) + + f := resumeTree() + f.failList = func(req *filer_pb.ListEntriesRequest) bool { + return req.Directory == "/a/d2" && req.StartFromFileName != "" + } + address := serveFiler(t, f) + + if first := executeOn(t, address, "/b/", "/a/"); first.Success { + t.Fatal("the interrupted walk reported success") + } + cp := f.checkpoint() + if cp == nil || cp.Prefix != "/a/" || cp.Cursor != fmt.Sprintf("/a/d2/f-%05d", walkPageSize-1) { + t.Fatalf("checkpoint = %+v", cp) + } + if _, found := f.dirs["/b"]["zz-old.bin"]; found { + t.Fatal("a prefix after the failure was not walked") + } + + second := executeOn(t, address, "/a/", "/b/") + if !second.Success || !strings.Contains(second.Result.Summary, "resumed from /a/d2/") { + t.Fatalf("second run = %+v", second) + } + if f.lists["/a/d1"] != 1 || f.lists["/a/d2"] != 1 || f.lists["/a/d3"] != 1 || f.lists["/b"] != 2 { + t.Fatalf("listings from the start: %v", f.lists) + } + for _, dir := range []string{"/a/d1", "/a/d2", "/a/d3"} { + if _, found := f.dirs[dir]["zz-old.bin"]; found { + t.Fatalf("%s/zz-old.bin is still stored", dir) + } + } + if f.checkpoint() != nil { + t.Fatal("a finished pass left its checkpoint") + } +} + +func TestExecuteStartsOverWhenTheTTLPathsChanged(t *testing.T) { + f := resumeTree() + content, _ := json.Marshal(walkCheckpoint{Prefixes: []string{"/a/"}, Prefix: "/a/", Cursor: "/a/d2", StartedNs: time.Now().UnixNano()}) + f.files[checkpointDir+"/"+checkpointName(f.signature)] = &filer_pb.Entry{Name: checkpointName(f.signature), Content: content} + address := serveFiler(t, f) + + if done := executeOn(t, address, "/a/", "/b/"); !done.Success || strings.Contains(done.Result.Summary, "resumed") { + t.Fatalf("run = %+v", done) + } + if f.lists["/a/d1"] != 1 { + t.Fatalf("listings from the start: %v", f.lists) + } + if f.checkpoint() != nil { + t.Fatal("a finished pass left the stale checkpoint") + } +} + +func TestCursorPathBelowTheWalkRoot(t *testing.T) { + for _, tc := range []struct { + root, cursor string + want []string + }{ + {"/", "/ttl-http-a/old.bin", []string{"ttl-http-a", "old.bin"}}, + {"/buckets/cam/", "/buckets/cam/2026-11-01", []string{"2026-11-01"}}, + {"/buckets/cam/", "/buckets/cam/", nil}, + {"/buckets/cam/", "/buckets/camera/x", nil}, + {"/buckets/cam/", "", nil}, + } { + if got := cursorPath(util.FullPath(tc.root), tc.cursor); !slices.Equal(got, tc.want) { + t.Errorf("cursorPath(%q, %q) = %q, want %q", tc.root, tc.cursor, got, tc.want) + } + } +} diff --git a/weed/worker/tasks/filer_ttl/walk.go b/weed/worker/tasks/filer_ttl/walk.go index 3ae252207b..f9793aa0fa 100644 --- a/weed/worker/tasks/filer_ttl/walk.go +++ b/weed/worker/tasks/filer_ttl/walk.go @@ -2,22 +2,45 @@ package filer_ttl import ( "context" + "encoding/json" + "errors" + "fmt" + "slices" "sort" "strings" + "time" "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/storage/needle" "github.com/seaweedfs/seaweedfs/weed/util" ) -const walkPageSize = 1024 +const ( + walkPageSize = 1024 + checkpointDir = filer.DirectoryEtcSeaweedFS + "/filer_ttl" + checkpointMaxAge = 7 * 24 * time.Hour + checkpointSaveWait = 5 * time.Second +) + +var checkpointInterval = 30 * time.Second type walkStats struct { directories int64 entries int64 } +// walkCheckpoint is where an unfinished pass over Prefixes stopped: every +// prefix before Prefix is done, and inside Prefix every entry up to and +// including Cursor, with its subtree, is done. +type walkCheckpoint struct { + Prefixes []string `json:"prefixes"` + Prefix string `json:"prefix"` + Cursor string `json:"cursor,omitempty"` + StartedNs int64 `json:"started_ns"` +} + // ttlLocationPrefixes returns the TTL path rules that no other TTL rule // encloses, so each subtree is walked once. func ttlLocationPrefixes(fc *filer.FilerConf) []string { @@ -40,28 +63,188 @@ func ttlLocationPrefixes(fc *filer.FilerConf) []string { return outer } -// walkLocationPrefix lists every entry under a filer.conf location prefix. -// Listing is what removes expired rows: the filer drops each expired entry -// it meets and deletes the directories that leaves empty. -func walkLocationPrefix(ctx context.Context, client filer_pb.SeaweedFilerClient, locationPrefix string, stats *walkStats) error { - ctx = filer_pb.WithChunksOmitted(ctx) - if strings.HasSuffix(locationPrefix, "/") { - return walkDirectory(ctx, client, util.FullPath(locationPrefix), "", stats) - } - dir, name := util.FullPath(locationPrefix).DirAndName() - return walkDirectory(ctx, client, util.FullPath(dir), name, stats) +// checkpointName is keyed by the store signature, so a record that +// filer.sync copies into another cluster's store is never read there. +func checkpointName(signature int32) string { + return fmt.Sprintf("walk-%d.json", signature) } -func walkDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, dir util.FullPath, namePrefix string, stats *walkStats) error { - stats.directories++ +type walker struct { + client filer_pb.SeaweedFilerClient + name string + stats *walkStats + cp walkCheckpoint + onDisk bool + frozen bool + savedAt time.Time +} + +// walkLocationPrefixes lists every entry under the filer.conf location +// prefixes, continuing a pass an earlier run left unfinished. Listing is +// what removes expired rows: the filer drops each expired entry it meets +// and deletes the directories that leaves empty. +func walkLocationPrefixes(ctx context.Context, client filer_pb.SeaweedFilerClient, prefixes []string, stats *walkStats) (resumed string, err error) { + prefixes = slices.Clone(prefixes) + sort.Strings(prefixes) + conf, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) + if err != nil { + return "", fmt.Errorf("filer configuration: %w", err) + } + w := &walker{client: client, name: checkpointName(conf.Signature), stats: stats, savedAt: time.Now()} + saved := w.load(ctx, prefixes) + w.cp = walkCheckpoint{Prefixes: prefixes, StartedNs: time.Now().UnixNano()} + if saved != nil { + w.cp.StartedNs = saved.StartedNs + resumed = saved.Prefix + if saved.Cursor != "" { + resumed = saved.Cursor + } + } + + listCtx := filer_pb.WithChunksOmitted(ctx) + var failed []string + for _, prefix := range prefixes { + cursor := "" + if saved != nil { + if prefix < saved.Prefix { + continue + } + if prefix == saved.Prefix { + cursor = saved.Cursor + } + } + if err := ctx.Err(); err != nil { + failed = append(failed, fmt.Sprintf("%s: %v", prefix, err)) + w.stop(prefix, cursor) + break + } + if !w.frozen { + w.cp.Prefix, w.cp.Cursor = prefix, cursor + } + if err := w.walkLocationPrefix(listCtx, prefix, cursor); err != nil { + failed = append(failed, fmt.Sprintf("%s: %v", prefix, err)) + w.stop(w.cp.Prefix, w.cp.Cursor) + } + } + if len(failed) > 0 { + w.persist() + return resumed, errors.New(strings.Join(failed, "; ")) + } + return resumed, w.clear(ctx) +} + +func (w *walker) load(ctx context.Context, prefixes []string) *walkCheckpoint { + content, err := filer.ReadInsideFiler(ctx, w.client, checkpointDir, w.name) + if err != nil { + if !errors.Is(err, filer_pb.ErrNotFound) { + glog.Warningf("filer_ttl: read checkpoint: %v; walking every prefix", err) + w.onDisk = true + } + return nil + } + w.onDisk = true + var cp walkCheckpoint + if err := json.Unmarshal(content, &cp); err != nil { + glog.Warningf("filer_ttl: decode checkpoint: %v; walking every prefix", err) + return nil + } + if !slices.Equal(cp.Prefixes, prefixes) || !slices.Contains(prefixes, cp.Prefix) || time.Since(time.Unix(0, cp.StartedNs)) > checkpointMaxAge { + return nil + } + return &cp +} + +// stop keeps the checkpoint at the first place this run failed; later +// prefixes still get walked but are not recorded as done. +func (w *walker) stop(prefix, cursor string) { + if w.frozen { + return + } + w.cp.Prefix, w.cp.Cursor = prefix, cursor + w.frozen = true +} + +func (w *walker) advance(ctx context.Context, done util.FullPath) { + if w.frozen { + return + } + w.cp.Cursor = string(done) + if time.Since(w.savedAt) < checkpointInterval { + return + } + w.savedAt = time.Now() + if err := w.save(ctx); err != nil { + glog.Warningf("filer_ttl: save checkpoint: %v", err) + } +} + +func (w *walker) persist() { + ctx, cancel := context.WithTimeout(context.Background(), checkpointSaveWait) + defer cancel() + if err := w.save(ctx); err != nil { + glog.Warningf("filer_ttl: save checkpoint: %v", err) + } +} + +func (w *walker) save(ctx context.Context) error { + content, err := json.Marshal(w.cp) + if err != nil { + return err + } + w.onDisk = true + return filer.SaveInsideFiler(ctx, w.client, checkpointDir, w.name, content) +} + +func (w *walker) clear(ctx context.Context) error { + if !w.onDisk { + return nil + } + if err := filer_pb.DoRemove(ctx, w.client, checkpointDir, w.name, false, false, false, false, nil); err != nil { + return fmt.Errorf("clear checkpoint: %w", err) + } + return nil +} + +func (w *walker) walkLocationPrefix(ctx context.Context, locationPrefix, cursor string) error { + root, namePrefix := util.FullPath(locationPrefix), "" + if !strings.HasSuffix(locationPrefix, "/") { + dir, name := root.DirAndName() + root, namePrefix = util.FullPath(dir), name + } + return w.walkDirectory(ctx, root, namePrefix, cursorPath(root, cursor)) +} + +// cursorPath splits a checkpoint cursor into its path below root. +func cursorPath(root util.FullPath, cursor string) []string { + base := strings.TrimSuffix(string(root), "/") + "/" + if cursor == "" || !strings.HasPrefix(cursor, base) || cursor == base { + return nil + } + return strings.Split(strings.TrimPrefix(cursor, base), "/") +} + +// walkDirectory lists dir depth first in name order. A non-empty resume +// path names the last finished entry: the walk descends into its +// unfinished ancestors and continues each one after them. +func (w *walker) walkDirectory(ctx context.Context, dir util.FullPath, namePrefix string, resume []string) error { + w.stats.directories++ startFrom := "" + if len(resume) > 0 { + startFrom = resume[0] + if len(resume) > 1 { + if err := w.walkDirectory(ctx, dir.Child(startFrom), "", resume[1:]); err != nil { + return err + } + w.advance(ctx, dir.Child(startFrom)) + } + } for { var subDirs []util.FullPath listed := 0 - err := filer_pb.SeaweedList(ctx, client, string(dir), namePrefix, func(entry *filer_pb.Entry, isLast bool) error { + err := filer_pb.SeaweedList(ctx, w.client, string(dir), namePrefix, func(entry *filer_pb.Entry, isLast bool) error { listed++ startFrom = entry.Name - stats.entries++ + w.stats.entries++ if entry.IsDirectory { subDirs = append(subDirs, dir.Child(entry.Name)) } @@ -71,9 +254,13 @@ func walkDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, dir return err } for _, subDir := range subDirs { - if err := walkDirectory(ctx, client, subDir, "", stats); err != nil { + if err := w.walkDirectory(ctx, subDir, "", nil); err != nil { return err } + w.advance(ctx, subDir) + } + if listed > 0 { + w.advance(ctx, dir.Child(startFrom)) } if listed < walkPageSize { return nil