worker: add a filer_ttl job that walks filer.conf TTL paths

A filer store without native TTL keeps the rows of expired entries until
something looks them up or lists their directory. The job lists every
TTL path subtree once per filer store, so the filer drops the expired
rows it meets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 committed 2026-11-27 22:11:00 -08:00
1 parent 4cf028f683
commit 2a830cd8f8
3 files changed
+573

No files matched your search

+214
View File
@@ -0,0 +1,214 @@
package filer_ttl
import (
"context"
"fmt"
"math"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
)
const (
jobType = "filer_ttl"
filerAddressParam = "filer_address"
locationPrefixesParam = "location_prefixes"
defaultDetectionMinutes = 24 * 60
)
func init() {
pluginworker.RegisterHandler(pluginworker.HandlerFactory{
JobType: jobType,
Category: pluginworker.CategoryDefault,
Aliases: []string{"filer-ttl", "filer.ttl"},
Build: func(opts pluginworker.HandlerBuildOptions) (pluginworker.JobHandler, error) {
return NewHandler(opts.GrpcDialOption), nil
},
})
}
// Handler removes the filer rows of entries whose filer.conf path TTL has
// passed. A store without native TTL keeps such rows until something lists
// their directory, long after the TTL volumes holding the data are gone.
type Handler struct {
grpcDialOption grpc.DialOption
}
func NewHandler(grpcDialOption grpc.DialOption) *Handler {
return &Handler{grpcDialOption: grpcDialOption}
}
func (h *Handler) Capability() *plugin_pb.JobTypeCapability {
return &plugin_pb.JobTypeCapability{
JobType: jobType,
CanDetect: true,
CanExecute: true,
MaxDetectionConcurrency: 1,
MaxExecutionConcurrency: 1,
DisplayName: "Filer TTL",
Description: "Walk filer.conf TTL paths so the filer removes the rows of expired entries.",
Weight: 20,
}
}
func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
return &plugin_pb.JobTypeDescriptor{
JobType: jobType,
DisplayName: "Filer TTL",
Description: "Remove the filer rows of entries past their filer.conf path TTL, once per filer store.",
Icon: "bi bi-hourglass-split",
DescriptorVersion: 1,
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
Enabled: true,
DetectionIntervalMinutes: defaultDetectionMinutes,
DetectionTimeoutSeconds: 60,
ExecutionTimeoutSeconds: math.MaxInt32,
JobTypeMaxRuntimeSeconds: math.MaxInt32,
},
WorkerDefaultValues: map[string]*plugin_pb.ConfigValue{},
}
}
func (h *Handler) Detect(ctx context.Context, request *plugin_pb.RunDetectionRequest, sender pluginworker.DetectionSender) error {
if request == nil || sender == nil {
return fmt.Errorf("detect: nil request or sender")
}
if request.JobType != "" && request.JobType != jobType {
return fmt.Errorf("job type %q is not handled by filer ttl handler", request.JobType)
}
var filers []pb.ServerAddress
for _, address := range request.GetClusterContext().GetFilerAddresses() {
if address != "" {
filers = append(filers, pb.ServerAddress(address))
}
}
if len(filers) == 0 {
_ = sender.SendActivity(pluginworker.BuildDetectorActivity("skipped", "no filer addresses in cluster context", nil))
return sender.SendComplete(&plugin_pb.DetectionComplete{JobType: jobType, Success: true})
}
fc, err := filer.ReadFilerConfFromFilers(filers, h.grpcDialOption, nil, security.FilerAdminToken)
if err != nil {
return err
}
prefixes := ttlLocationPrefixes(fc)
if len(prefixes) == 0 {
_ = sender.SendActivity(pluginworker.BuildDetectorActivity("skipped", "no TTL path rules in filer.conf", nil))
return sender.SendComplete(&plugin_pb.DetectionComplete{JobType: jobType, Success: true})
}
var proposals []*plugin_pb.JobProposal
for _, address := range h.oneFilerPerStore(ctx, filers, sender) {
proposals = append(proposals, &plugin_pb.JobProposal{
JobType: jobType,
ProposalId: fmt.Sprintf("filer-ttl-%s-%d", address, time.Now().UnixNano()),
DedupeKey: fmt.Sprintf("%s:%s", jobType, address),
Priority: plugin_pb.JobPriority_JOB_PRIORITY_LOW,
Summary: fmt.Sprintf("Walk %d TTL path(s) on the store of filer %s", len(prefixes), address),
Parameters: map[string]*plugin_pb.ConfigValue{
filerAddressParam: {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: string(address)}},
locationPrefixesParam: {Kind: &plugin_pb.ConfigValue_StringList{StringList: &plugin_pb.StringList{Values: prefixes}}},
},
})
}
if len(proposals) > 0 {
if err := sender.SendProposals(&plugin_pb.DetectionProposals{JobType: jobType, Proposals: proposals}); err != nil {
return err
}
}
return sender.SendComplete(&plugin_pb.DetectionComplete{
JobType: jobType,
Success: true,
TotalProposals: int32(len(proposals)),
})
}
// oneFilerPerStore keeps the first reachable filer of each store signature:
// filers sharing a store share its rows, and a filer with its own store has
// rows no other filer's walk removes.
func (h *Handler) oneFilerPerStore(ctx context.Context, filers []pb.ServerAddress, sender pluginworker.DetectionSender) []pb.ServerAddress {
seen := make(map[int32]bool)
var picked []pb.ServerAddress
for _, address := range filers {
var signature int32
err := pb.WithGrpcFilerClient(false, 0, address, h.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return err
}
signature = resp.Signature
return nil
})
if err != nil {
_ = sender.SendActivity(pluginworker.BuildDetectorActivity("filer_unreachable", fmt.Sprintf("filer %s: %v", address, err), nil))
continue
}
if seen[signature] {
continue
}
seen[signature] = true
picked = append(picked, address)
}
return picked
}
func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender) error {
if request == nil || request.Job == nil || sender == nil {
return fmt.Errorf("execute: nil request/job/sender")
}
if request.Job.JobType != "" && request.Job.JobType != jobType {
return fmt.Errorf("job type %q is not handled by filer ttl handler", request.Job.JobType)
}
address := pluginworker.ReadStringConfig(request.Job.Parameters, filerAddressParam, "")
if address == "" {
return fmt.Errorf("execute: missing %s in job parameters", filerAddressParam)
}
prefixes := pluginworker.ReadStringListConfig(request.Job.Parameters, locationPrefixesParam)
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId, JobType: jobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "walking",
Message: fmt.Sprintf("filer %s: %s", address, strings.Join(prefixes, ", ")),
})
stats := &walkStats{}
var failed []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))
}
}
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)
completed := &plugin_pb.JobCompleted{
JobId: request.Job.JobId,
JobType: jobType,
Success: err == nil,
Result: &plugin_pb.JobResult{
Summary: summary,
OutputValues: map[string]*plugin_pb.ConfigValue{
"directories": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.directories}},
"entries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.entries}},
},
},
}
if err != nil {
completed.ErrorMessage = err.Error()
}
return sender.SendCompleted(completed)
}
+277
View File
@@ -0,0 +1,277 @@
package filer_ttl
import (
"context"
"fmt"
"net"
"sort"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// ttlFiler lists like a filer on a store without native TTL: an expired
// entry is skipped and its row deleted when a listing reaches it.
type ttlFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
signature int32
conf []byte
mu sync.Mutex
dirs map[string]map[string]*filer_pb.Entry
expired map[string]bool
}
func newTTLFiler(signature int32) *ttlFiler {
return &ttlFiler{signature: signature, dirs: map[string]map[string]*filer_pb.Entry{}, expired: map[string]bool{}}
}
func (f *ttlFiler) add(fullPath string, isDirectory, expired bool) {
f.mu.Lock()
defer f.mu.Unlock()
dir, name := util.FullPath(fullPath).DirAndName()
if f.dirs[dir] == nil {
f.dirs[dir] = map[string]*filer_pb.Entry{}
}
f.dirs[dir][name] = &filer_pb.Entry{Name: name, IsDirectory: isDirectory}
if expired {
f.expired[fullPath] = true
}
}
func (f *ttlFiler) rows() int {
f.mu.Lock()
defer f.mu.Unlock()
n := 0
for _, entries := range f.dirs {
n += len(entries)
}
return n
}
func (f *ttlFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
return &filer_pb.GetFilerConfigurationResponse{Signature: f.signature}, nil
}
func (f *ttlFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
if req.Directory != filer.DirectoryEtcSeaweedFS || req.Name != filer.FilerConfName || f.conf == nil {
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
}
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: req.Name, Content: f.conf}}, nil
}
func (f *ttlFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
dir := strings.TrimSuffix(req.Directory, "/")
if dir == "" {
dir = "/"
}
f.mu.Lock()
var names []string
for name := range f.dirs[dir] {
if strings.HasPrefix(name, req.Prefix) && name > req.StartFromFileName {
names = append(names, name)
}
}
sort.Strings(names)
var page []*filer_pb.Entry
for _, name := range names {
if uint32(len(page)) >= req.Limit {
break
}
fullPath := string(util.FullPath(dir).Child(name))
if f.expired[fullPath] {
delete(f.dirs[dir], name)
continue
}
page = append(page, proto.Clone(f.dirs[dir][name]).(*filer_pb.Entry))
}
f.mu.Unlock()
for _, entry := range page {
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
return err
}
}
return nil
}
func serveFiler(t *testing.T, f *ttlFiler) string {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
s := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(s, f)
go s.Serve(lis)
t.Cleanup(s.Stop)
host, port, _ := net.SplitHostPort(lis.Addr().String())
return fmt.Sprintf("%s:1.%s", host, port)
}
func filerConf(t *testing.T, rules ...*filer_pb.FilerConf_PathConf) []byte {
t.Helper()
fc := filer.NewFilerConf()
for _, rule := range rules {
if err := fc.SetLocationConf(rule); err != nil {
t.Fatal(err)
}
}
var buf strings.Builder
if err := fc.ToText(&buf); err != nil {
t.Fatal(err)
}
return []byte(buf.String())
}
type detectRecorder struct {
proposals []*plugin_pb.JobProposal
completes []*plugin_pb.DetectionComplete
}
func (r *detectRecorder) SendProposals(p *plugin_pb.DetectionProposals) error {
r.proposals = append(r.proposals, p.Proposals...)
return nil
}
func (r *detectRecorder) SendComplete(c *plugin_pb.DetectionComplete) error {
r.completes = append(r.completes, c)
return nil
}
func (r *detectRecorder) SendActivity(*plugin_pb.ActivityEvent) error { return nil }
type executeRecorder struct {
completed []*plugin_pb.JobCompleted
}
func (r *executeRecorder) SendProgress(*plugin_pb.JobProgressUpdate) error { return nil }
func (r *executeRecorder) SendCompleted(c *plugin_pb.JobCompleted) error {
r.completed = append(r.completed, c)
return nil
}
func newTestHandler() *Handler {
return NewHandler(grpc.WithTransportCredentials(insecure.NewCredentials()))
}
func TestTTLLocationPrefixesFoldsNestedRules(t *testing.T) {
fc := filer.NewFilerConf()
for _, rule := range []*filer_pb.FilerConf_PathConf{
{LocationPrefix: "/buckets/logs/", Ttl: "7d"},
{LocationPrefix: "/buckets/logs/debug/", Ttl: "1d"},
{LocationPrefix: "/buckets/archive/", Replication: "001"},
{LocationPrefix: "/tmp", Ttl: "1h"},
} {
if err := fc.SetLocationConf(rule); err != nil {
t.Fatal(err)
}
}
got := ttlLocationPrefixes(fc)
want := []string{"/buckets/logs/", "/tmp"}
if fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("prefixes = %v, want %v", got, want)
}
}
func TestDetectProposesOneJobPerStore(t *testing.T) {
conf := filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "11d"})
shared1, shared2, own := newTTLFiler(7), newTTLFiler(7), newTTLFiler(9)
for _, f := range []*ttlFiler{shared1, shared2, own} {
f.conf = conf
}
addresses := []string{serveFiler(t, shared1), serveFiler(t, shared2), serveFiler(t, own)}
sender := &detectRecorder{}
err := newTestHandler().Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{FilerAddresses: addresses},
}, sender)
if err != nil {
t.Fatal(err)
}
var got []string
for _, p := range sender.proposals {
got = append(got, p.Parameters[filerAddressParam].GetStringValue())
if prefixes := p.Parameters[locationPrefixesParam].GetStringList().GetValues(); fmt.Sprint(prefixes) != "[/buckets/cam/]" {
t.Fatalf("prefixes = %v", prefixes)
}
}
if want := []string{addresses[0], addresses[2]}; fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("proposed filers = %v, want %v", got, want)
}
}
func TestDetectWithoutTTLRulesProposesNothing(t *testing.T) {
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Replication: "001"})
sender := &detectRecorder{}
err := newTestHandler().Detect(context.Background(), &plugin_pb.RunDetectionRequest{
JobType: jobType,
ClusterContext: &plugin_pb.ClusterContext{FilerAddresses: []string{serveFiler(t, f)}},
}, sender)
if err != nil {
t.Fatal(err)
}
if len(sender.proposals) != 0 || len(sender.completes) != 1 || !sender.completes[0].Success {
t.Fatalf("proposals=%d completes=%v", len(sender.proposals), sender.completes)
}
}
func TestExecuteRemovesExpiredRowsNobodyVisits(t *testing.T) {
f := newTTLFiler(1)
f.add("/buckets/cam/2026-11-01", true, false)
for i := 0; i < 2*walkPageSize+10; i++ {
f.add(fmt.Sprintf("/buckets/cam/2026-11-01/clip-%05d.mp4", i), false, true)
}
f.add("/buckets/cam/2026-11-26", true, false)
for i := 0; i < walkPageSize+100; i++ {
f.add(fmt.Sprintf("/buckets/cam/2026-11-26/clip-%05d.mp4", i), false, false)
}
f.add("/buckets/cam/2026-11-26/zz-old.mp4", false, true)
f.add("/buckets/cam/2026-11-27", true, false)
f.add("/buckets/cam/2026-11-27/deep", true, false)
f.add("/buckets/cam/2026-11-27/deep/old.mp4", false, true)
f.add("/buckets/cam/2026-11-27/deep/new.mp4", false, false)
for _, dir := range []string{"/ttl-http-a", "/ttl-http-b", "/keep"} {
f.add(dir, true, false)
f.add(dir+"/old.bin", false, true)
}
address := serveFiler(t, f)
sender := &executeRecorder{}
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: []string{"/buckets/cam/", "/ttl-http-"}}}},
},
}}, sender)
if err != nil {
t.Fatal(err)
}
if len(sender.completed) != 1 || !sender.completed[0].Success {
t.Fatalf("completed = %v", sender.completed)
}
for _, expired := range []string{"/buckets/cam/2026-11-01/clip-02057.mp4", "/buckets/cam/2026-11-26/zz-old.mp4", "/buckets/cam/2026-11-27/deep/old.mp4", "/ttl-http-a/old.bin", "/ttl-http-b/old.bin"} {
dir, name := util.FullPath(expired).DirAndName()
if _, found := f.dirs[dir][name]; found {
t.Fatalf("%s is still stored", expired)
}
}
if _, found := f.dirs["/keep"]["old.bin"]; !found {
t.Fatal("an entry outside every TTL path was listed")
}
if _, found := f.dirs["/buckets/cam/2026-11-27/deep"]["new.mp4"]; !found {
t.Fatal("a live entry was removed")
}
if got := f.rows(); got != 8+1+walkPageSize+100 {
t.Fatalf("rows left = %d, want %d", got, 8+1+walkPageSize+100)
}
}
+82
View File
@@ -0,0 +1,82 @@
package filer_ttl
import (
"context"
"sort"
"strings"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/util"
)
const walkPageSize = 1024
type walkStats struct {
directories int64
entries int64
}
// ttlLocationPrefixes returns the TTL path rules that no other TTL rule
// encloses, so each subtree is walked once.
func ttlLocationPrefixes(fc *filer.FilerConf) []string {
var prefixes []string
for _, rule := range fc.ToProto().Locations {
ttl, err := needle.ReadTTL(rule.GetTtl())
if err != nil || ttl.ToSeconds() == 0 {
continue
}
prefixes = append(prefixes, rule.LocationPrefix)
}
sort.Strings(prefixes)
var outer []string
for _, prefix := range prefixes {
if n := len(outer); n > 0 && strings.HasPrefix(prefix, outer[n-1]) {
continue
}
outer = append(outer, prefix)
}
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)
}
func walkDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, dir util.FullPath, namePrefix string, stats *walkStats) error {
stats.directories++
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 {
listed++
startFrom = entry.Name
stats.entries++
if entry.IsDirectory {
subDirs = append(subDirs, dir.Child(entry.Name))
}
return nil
}, startFrom, false, walkPageSize)
if err != nil {
return err
}
for _, subDir := range subDirs {
if err := walkDirectory(ctx, client, subDir, "", stats); err != nil {
return err
}
}
if listed < walkPageSize {
return nil
}
}
}