worker: expire filer_ttl entries from metadata events per TTL rule

Each run replays every filer.conf TTL rule's metadata events from that
rule's cursor up to the run start, and looks up each entry whose TTL has
passed so the filer removes its row. The first entry not yet due holds the
rule's cursor, so a later run replays it. A rule without a cursor, or
whose TTL changed, is listed once to reach rows older than its replay
window. The periodic full walk and its checkpoint are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 committed 2026-11-28 10:10:02 -08:00
1 parent 62b0d26741
commit e2af17fc72
4 files changed
+687 -547

No files matched your search

+26 -26
View File
@@ -20,7 +20,6 @@ import (
const (
jobType = "filer_ttl"
filerAddressParam = "filer_address"
locationPrefixesParam = "location_prefixes"
defaultDetectionMinutes = 24 * 60
)
@@ -36,8 +35,8 @@ func init() {
}
// 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.
// passed. A store without native TTL keeps such rows until something looks
// them up, long after the TTL volumes holding the data are gone.
type Handler struct {
grpcDialOption grpc.DialOption
}
@@ -54,7 +53,7 @@ func (h *Handler) Capability() *plugin_pb.JobTypeCapability {
MaxDetectionConcurrency: 1,
MaxExecutionConcurrency: 1,
DisplayName: "Filer TTL",
Description: "Walk filer.conf TTL paths so the filer removes the rows of expired entries.",
Description: "Replay filer metadata events under filer.conf TTL paths so the filer removes the rows of expired entries.",
Weight: 20,
}
}
@@ -103,8 +102,8 @@ func (h *Handler) Detect(ctx context.Context, request *plugin_pb.RunDetectionReq
readErrors = append(readErrors, fmt.Sprintf("filer %s: %v", address, err))
continue
}
prefixes := ttlLocationPrefixes(fc)
if len(prefixes) == 0 {
rules := ttlRules(fc)
if len(rules) == 0 {
continue
}
proposals = append(proposals, &plugin_pb.JobProposal{
@@ -112,10 +111,9 @@ func (h *Handler) Detect(ctx context.Context, request *plugin_pb.RunDetectionReq
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),
Summary: fmt.Sprintf("Expire entries under %d TTL path(s) on the store of filer %s", len(rules), 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}}},
filerAddressParam: {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: string(address)}},
},
})
}
@@ -153,7 +151,7 @@ func (c *adminFilerClient) GetLookupFileIdFunction() wdclient.LookupFileIdFuncti
// 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.
// rows no other filer's job 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
@@ -191,28 +189,27 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
if address == "" {
return fmt.Errorf("execute: missing %s in job parameters", filerAddressParam)
}
prefixes := pluginworker.ReadStringListConfig(request.Job.Parameters, locationPrefixesParam)
client := &adminFilerClient{address: pb.ServerAddress(address), grpcDialOption: h.grpcDialOption}
_ = 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, ", ")),
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "replaying",
Message: fmt.Sprintf("filer %s", address),
})
stats := &walkStats{}
var resumed string
err := pb.WithGrpcFilerClient(true, 0, pb.ServerAddress(address), h.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error {
var walkErr error
resumed, walkErr = walkLocationPrefixes(ctx, client, prefixes, stats)
if walkErr != nil {
return fmt.Errorf("walk %w", walkErr)
}
return nil
})
stats := &runStats{}
var rules []ttlRule
fc, err := filer.ReadFilerConfFromClient(ctx, client, client)
if err == nil {
rules = ttlRules(fc)
err = client.WithFilerClient(true, func(c filer_pb.SeaweedFilerClient) error {
return expireByEvents(ctx, c, rules, stats)
})
}
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)
summary := fmt.Sprintf("filer %s: %d TTL path(s), %d events, %d expired entries looked up, %d still waiting", address, len(rules), stats.events, stats.expired, stats.pending)
if stats.directories > 0 {
summary += fmt.Sprintf(", listed %d directories and %d live entries", stats.directories, stats.entries)
}
completed := &plugin_pb.JobCompleted{
JobId: request.Job.JobId,
@@ -221,6 +218,9 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
Result: &plugin_pb.JobResult{
Summary: summary,
OutputValues: map[string]*plugin_pb.ConfigValue{
"events": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.events}},
"expired": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.expired}},
"pending": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.pending}},
"directories": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.directories}},
"entries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.entries}},
},
+351 -265
View File
@@ -7,7 +7,6 @@ import (
"net"
"net/http"
"net/http/httptest"
"slices"
"sort"
"strings"
"sync"
@@ -25,111 +24,160 @@ import (
"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.
// ttlFiler behaves like a filer on a store without native TTL: an expired
// row stays until a lookup or a listing reaches it, and then it is deleted.
type ttlFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
signature int32
conf []byte
volumeUrl string
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
onList func(dir string)
signature int32
conf []byte
volumeUrl string
mu sync.Mutex
dirs map[string]map[string]*filer_pb.Entry
events []*filer_pb.SubscribeMetadataResponse
lastTsNs int64
lists map[string]int
lookups map[string]int
failLookup string
subscriptions []*filer_pb.SubscribeMetadataRequest
}
func newTTLFiler(signature int32) *ttlFiler {
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{}}
return &ttlFiler{signature: signature, dirs: map[string]map[string]*filer_pb.Entry{}, lists: map[string]int{}, lookups: map[string]int{}}
}
func (f *ttlFiler) checkpoint() *walkCheckpoint {
func gone(entry *filer_pb.Entry) bool {
attr := entry.GetAttributes()
return !entry.IsDirectory && attr.GetTtlSec() > 0 && time.Unix(attr.Crtime, 0).Add(time.Duration(attr.TtlSec)*time.Second).Before(time.Now())
}
func (f *ttlFiler) put(fullPath string, entry *filer_pb.Entry) {
dir, name := util.FullPath(fullPath).DirAndName()
entry.Name = name
if f.dirs[dir] == nil {
f.dirs[dir] = map[string]*filer_pb.Entry{}
}
f.dirs[dir][name] = entry
}
func (f *ttlFiler) row(fullPath string) *filer_pb.Entry {
f.mu.Lock()
defer f.mu.Unlock()
entry := f.files[checkpointDir+"/"+checkpointName(f.signature)]
dir, name := util.FullPath(fullPath).DirAndName()
return f.dirs[dir][name]
}
// add stores a row that no replayed event names.
func (f *ttlFiler) add(fullPath string, isDirectory bool, crtime time.Time, ttlSec int32) {
f.mu.Lock()
defer f.mu.Unlock()
f.put(fullPath, &filer_pb.Entry{IsDirectory: isDirectory, Attributes: &filer_pb.FuseAttributes{Crtime: crtime.Unix(), TtlSec: ttlSec}})
}
// write stores a file and logs its create event.
func (f *ttlFiler) write(fullPath string, crtime time.Time, ttlSec int32) *filer_pb.SubscribeMetadataResponse {
tsNs := time.Now().UnixNano()
f.mu.Lock()
if tsNs <= f.lastTsNs {
tsNs = f.lastTsNs + 1
}
f.mu.Unlock()
return f.writeAt(tsNs, fullPath, crtime, ttlSec)
}
func (f *ttlFiler) writeAt(tsNs int64, fullPath string, crtime time.Time, ttlSec int32) *filer_pb.SubscribeMetadataResponse {
f.mu.Lock()
defer f.mu.Unlock()
entry := &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{Crtime: crtime.Unix(), TtlSec: ttlSec}}
f.put(fullPath, entry)
dir, _ := util.FullPath(fullPath).DirAndName()
event := &filer_pb.SubscribeMetadataResponse{Directory: dir, TsNs: tsNs, EventNotification: &filer_pb.EventNotification{NewEntry: proto.Clone(entry).(*filer_pb.Entry)}}
f.events = append(f.events, event)
f.lastTsNs = tsNs
return event
}
func (f *ttlFiler) remove(fullPath string) *filer_pb.SubscribeMetadataResponse {
f.mu.Lock()
defer f.mu.Unlock()
dir, name := util.FullPath(fullPath).DirAndName()
old := f.dirs[dir][name]
delete(f.dirs[dir], name)
f.lastTsNs = max(f.lastTsNs+1, time.Now().UnixNano())
event := &filer_pb.SubscribeMetadataResponse{Directory: dir, TsNs: f.lastTsNs, EventNotification: &filer_pb.EventNotification{OldEntry: old}}
f.events = append(f.events, event)
return event
}
func (f *ttlFiler) cursors() map[string]ruleCursor {
f.mu.Lock()
defer f.mu.Unlock()
entry := f.dirs[cursorDir][cursorName(f.signature)]
if entry == nil {
return nil
}
var cp walkCheckpoint
if err := json.Unmarshal(entry.Content, &cp); err != nil {
var saved savedCursors
if err := json.Unmarshal(entry.Content, &saved); err != nil {
return nil
}
return &cp
return saved.Rules
}
func (f *ttlFiler) saveCursors(t *testing.T, cursors map[string]ruleCursor) {
t.Helper()
content, err := json.Marshal(savedCursors{Rules: cursors})
if err != nil {
t.Fatal(err)
}
f.mu.Lock()
defer f.mu.Unlock()
f.put(cursorDir+"/"+cursorName(f.signature), &filer_pb.Entry{Content: content, Attributes: &filer_pb.FuseAttributes{}})
}
func (f *ttlFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
key := req.Directory + "/" + req.Entry.Name
entry := proto.Clone(req.Entry).(*filer_pb.Entry)
if old := f.files[key]; old != nil && old.Attributes != nil && entry.Attributes != nil {
entry.Attributes.Crtime = old.Attributes.Crtime
}
f.files[key] = entry
f.put(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)
f.put(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) {
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) {
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
fullPath := req.Directory + "/" + req.Name
if req.Directory == filer.DirectoryEtcSeaweedFS && req.Name == filer.FilerConfName && f.conf != nil {
if f.volumeUrl != "" {
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{
Name: req.Name,
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(f.conf))},
Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: uint64(len(f.conf))}},
}}, nil
}
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: req.Name, Content: f.conf}}, nil
}
if req.Directory != filer.DirectoryEtcSeaweedFS || req.Name != filer.FilerConfName || f.conf == nil {
f.mu.Lock()
defer f.mu.Unlock()
f.lookups[fullPath]++
if fullPath == f.failLookup {
return nil, status.Error(codes.Unavailable, "store unavailable")
}
entry := f.dirs[req.Directory][req.Name]
if entry == nil {
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
}
if f.volumeUrl != "" {
return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{
Name: req.Name,
Attributes: &filer_pb.FuseAttributes{FileSize: uint64(len(f.conf))},
Chunks: []*filer_pb.FileChunk{{FileId: "3,01637037d6", Size: uint64(len(f.conf))}},
}}, nil
if gone(entry) {
delete(f.dirs[req.Directory], req.Name)
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
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
}
func (f *ttlFiler) LookupVolume(_ context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
@@ -146,17 +194,9 @@ 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]++
}
if f.onList != nil {
f.onList(dir)
}
var names []string
for name := range f.dirs[dir] {
if strings.HasPrefix(name, req.Prefix) && name > req.StartFromFileName {
@@ -169,8 +209,7 @@ func (f *ttlFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb
if uint32(len(page)) >= req.Limit {
break
}
fullPath := string(util.FullPath(dir).Child(name))
if f.expired[fullPath] {
if gone(f.dirs[dir][name]) {
delete(f.dirs[dir], name)
continue
}
@@ -185,6 +224,48 @@ func (f *ttlFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb
return nil
}
// SubscribeMetadata sends the logged events of a bounded subscription two
// per response, the second one batched.
func (f *ttlFiler) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error {
f.mu.Lock()
f.subscriptions = append(f.subscriptions, req)
var matched []*filer_pb.SubscribeMetadataResponse
for _, event := range f.events {
if event.TsNs <= req.SinceNs || (req.UntilNs != 0 && event.TsNs > req.UntilNs) {
continue
}
n := event.EventNotification
var paths []string
if n.OldEntry != nil {
paths = append(paths, event.Directory+"/"+n.OldEntry.Name)
}
if n.NewEntry != nil {
dir := n.NewParentPath
if dir == "" {
dir = event.Directory
}
paths = append(paths, dir+"/"+n.NewEntry.Name)
}
for _, p := range paths {
if strings.HasPrefix(p, req.PathPrefix) {
matched = append(matched, proto.Clone(event).(*filer_pb.SubscribeMetadataResponse))
break
}
}
}
f.mu.Unlock()
for i := 0; i < len(matched); i += 2 {
resp := matched[i]
if i+1 < len(matched) {
resp.Events = matched[i+1 : i+2]
}
if err := stream.Send(resp); 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")
@@ -243,7 +324,24 @@ func newTestHandler() *Handler {
return NewHandler(grpc.WithTransportCredentials(insecure.NewCredentials()))
}
func TestTTLLocationPrefixesFoldsNestedRules(t *testing.T) {
func executeOn(t *testing.T, address 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}},
},
}}, sender); err != nil {
t.Fatal(err)
}
if len(sender.completed) != 1 {
t.Fatalf("completed = %v", sender.completed)
}
return sender.completed[0]
}
func TestTTLRulesOwnerAndOutermost(t *testing.T) {
fc := filer.NewFilerConf()
for _, rule := range []*filer_pb.FilerConf_PathConf{
{LocationPrefix: "/buckets/logs/", Ttl: "7d"},
@@ -255,10 +353,23 @@ func TestTTLLocationPrefixesFoldsNestedRules(t *testing.T) {
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)
rules := ttlRules(fc)
if got := fmt.Sprint(rules); got != "[{/buckets/logs/ 604800} {/buckets/logs/debug/ 86400} {/tmp 3600}]" {
t.Fatalf("rules = %s", got)
}
for path, want := range map[string]string{
"/buckets/logs/a.log": "/buckets/logs/",
"/buckets/logs/debug/a.log": "/buckets/logs/debug/",
"/buckets/logs/debugging.log": "/buckets/logs/",
"/tmp-cache/x": "/tmp",
"/buckets/archive/x": "",
} {
if got := owner(rules, path); got != want {
t.Fatalf("owner(%s) = %q, want %q", path, got, want)
}
}
if got := fmt.Sprint(outermost([]string{"/buckets/logs/", "/buckets/logs/debug/", "/tmp"})); got != "[/buckets/logs/ /tmp]" {
t.Fatalf("outermost = %s", got)
}
}
@@ -281,9 +392,6 @@ func TestDetectProposesOneJobPerStore(t *testing.T) {
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)
@@ -312,13 +420,9 @@ func TestDetectReadsEachStoresOwnFilerConf(t *testing.T) {
if len(sender.proposals) != 1 {
t.Fatalf("proposals = %d, want 1", len(sender.proposals))
}
p := sender.proposals[0]
if got := p.Parameters[filerAddressParam].GetStringValue(); got != addresses[1] {
if got := sender.proposals[0].Parameters[filerAddressParam].GetStringValue(); got != addresses[1] {
t.Fatalf("proposed filer = %s, want %s", got, addresses[1])
}
if prefixes := p.Parameters[locationPrefixesParam].GetStringList().GetValues(); fmt.Sprint(prefixes) != "[/clips/]" {
t.Fatalf("prefixes = %v", prefixes)
}
}
func TestDetectWithoutTTLRulesProposesNothing(t *testing.T) {
@@ -337,217 +441,199 @@ func TestDetectWithoutTTLRulesProposesNothing(t *testing.T) {
}
}
func TestExecuteRemovesExpiredRowsNobodyVisits(t *testing.T) {
func TestExecuteListsANewRuleOnceThenReplaysItsEvents(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.add("/buckets/cam/2026-11-01", true, false)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"})
f.add("/buckets/cam/2026-11-01", true, now, 0)
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)
f.add(fmt.Sprintf("/buckets/cam/2026-11-01/clip-%05d.mp4", i), false, now.Add(-2*time.Hour), 3600)
}
f.add("/buckets/cam/2026-11-01/live.mp4", false, now, 3600)
f.add("/keep", true, now, 0)
f.add("/keep/old.bin", false, now.Add(-2*time.Hour), 3600)
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 c := executeOn(t, address); !c.Success {
t.Fatalf("first run: %s", c.ErrorMessage)
}
if len(sender.completed) != 1 || !sender.completed[0].Success {
t.Fatalf("completed = %v", sender.completed)
if n := len(f.dirs["/buckets/cam/2026-11-01"]); n != 1 || f.row("/buckets/cam/2026-11-01/live.mp4") == nil {
t.Fatalf("rows left under the TTL path = %d, want only the live one", n)
}
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 f.row("/keep/old.bin") == nil {
t.Fatal("an entry outside every TTL path was removed")
}
if _, found := f.dirs["/keep"]["old.bin"]; !found {
t.Fatal("an entry outside every TTL path was listed")
c := f.cursors()["/buckets/cam/"]
if c.TtlSec != 3600 || c.TsNs < now.Add(-time.Hour-time.Minute).UnixNano() || c.TsNs > now.Add(-time.Hour+time.Minute).UnixNano() {
t.Fatalf("cursor = %+v, want ttl 3600 at about an hour ago", c)
}
if _, found := f.dirs["/buckets/cam/2026-11-27/deep"]["new.mp4"]; !found {
t.Fatal("a live entry was removed")
old := f.write("/buckets/cam/2026-11-02/rewritten.mp4", now.Add(-2*time.Hour), 3600)
if c := executeOn(t, address); !c.Success {
t.Fatalf("second run: %s", c.ErrorMessage)
}
if got := f.rows(); got != 8+1+walkPageSize+100 {
t.Fatalf("rows left = %d, want %d", got, 8+1+walkPageSize+100)
if got := f.lists["/buckets/cam"]; got != 1 {
t.Fatalf("TTL path listed %d times, want once", got)
}
if f.row("/buckets/cam/2026-11-02/rewritten.mp4") != nil {
t.Fatal("the expired entry of a replayed event is still stored")
}
if got := f.cursors()["/buckets/cam/"].TsNs; got != old.TsNs {
t.Fatalf("cursor = %d, want the last event %d", got, old.TsNs)
}
}
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 {
func TestExecuteHoldsTheCursorAtTheFirstEntryNotYetDue(t *testing.T) {
now := time.Now()
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 != ""
}
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"})
f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}})
a := f.write("/logs/a.log", now.Add(-2*time.Hour), 3600)
b := f.write("/logs/b.log", now, 3600)
f.write("/logs/c.log", now.Add(-3*time.Hour), 3600)
f.write("/logs/outside-ttl.log", now.Add(-3*time.Hour), 0)
f.write("/logs/d.log", now.Add(-3*time.Hour), 3600)
last := f.remove("/logs/d.log")
address := serveFiler(t, f)
if first := executeOn(t, address, "/b/", "/a/"); first.Success {
t.Fatal("the interrupted walk reported success")
if c := executeOn(t, address); !c.Success {
t.Fatalf("first run: %s", c.ErrorMessage)
}
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 f.row("/logs/a.log") != nil || f.row("/logs/c.log") != nil {
t.Fatal("an entry whose TTL passed is still stored")
}
if _, found := f.dirs["/b"]["zz-old.bin"]; found {
t.Fatal("a prefix after the failure was not walked")
if f.row("/logs/b.log") == nil || f.lookups["/logs/b.log"] != 0 {
t.Fatal("an entry not yet due was looked up")
}
if f.row("/logs/outside-ttl.log") == nil {
t.Fatal("an entry without a TTL was removed")
}
if len(f.lists) != 0 {
t.Fatalf("a rule with a cursor was listed: %v", f.lists)
}
if got := f.cursors()["/logs/"].TsNs; got != a.TsNs {
t.Fatalf("cursor = %d, want the event before the waiting entry %d", got, a.TsNs)
}
second := executeOn(t, address, "/a/", "/b/")
if !second.Success || !strings.Contains(second.Result.Summary, "resumed from /a/d2/") {
t.Fatalf("second run = %+v", second)
f.mu.Lock()
b.EventNotification.NewEntry.Attributes.Crtime = now.Add(-2 * time.Hour).Unix()
f.dirs["/logs"]["b.log"].Attributes.Crtime = now.Add(-2 * time.Hour).Unix()
f.mu.Unlock()
if c := executeOn(t, address); !c.Success {
t.Fatalf("second run: %s", c.ErrorMessage)
}
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)
if f.row("/logs/b.log") != nil {
t.Fatal("the held entry was not removed once its TTL passed")
}
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 got := f.subscriptions[1].SinceNs; got != a.TsNs {
t.Fatalf("second run subscribed from %d, want %d", got, a.TsNs)
}
if f.checkpoint() != nil {
t.Fatal("a finished pass left its checkpoint")
if got := f.cursors()["/logs/"].TsNs; got != last.TsNs {
t.Fatalf("cursor = %d, want the last event %d", got, last.TsNs)
}
}
func TestExecuteSavesTheFailurePointBeforeWalkingOn(t *testing.T) {
saved := checkpointInterval
checkpointInterval = time.Hour
t.Cleanup(func() { checkpointInterval = saved })
func TestExecuteHoldsTheCursorBelowATieWithAWaitingEntry(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"})
f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}})
tsNs := now.UnixNano()
f.writeAt(tsNs, "/logs/a.log", now.Add(-2*time.Hour), 3600)
f.writeAt(tsNs, "/logs/b.log", now, 3600)
f := resumeTree()
f.failList = func(req *filer_pb.ListEntriesRequest) bool {
return req.Directory == "/a/d2" && req.StartFromFileName != ""
if c := executeOn(t, serveFiler(t, f)); !c.Success {
t.Fatal(c.ErrorMessage)
}
var duringLaterPrefix *filer_pb.Entry
f.onList = func(dir string) {
if entry := f.files[checkpointDir+"/"+checkpointName(f.signature)]; dir == "/b" && entry != nil {
duringLaterPrefix = proto.Clone(entry).(*filer_pb.Entry)
}
}
address := serveFiler(t, f)
if done := executeOn(t, address, "/a/", "/b/"); done.Success {
t.Fatal("the interrupted walk reported success")
}
if duringLaterPrefix == nil {
t.Fatal("no checkpoint was stored while a later prefix was walked")
}
var cp walkCheckpoint
if err := json.Unmarshal(duringLaterPrefix.Content, &cp); err != nil {
t.Fatal(err)
}
if cp.Prefix != "/a/" || cp.Cursor != fmt.Sprintf("/a/d2/f-%05d", walkPageSize-1) {
t.Fatalf("checkpoint while walking /b/ = %+v", cp)
}
if ttl := time.Duration(duringLaterPrefix.GetAttributes().GetTtlSec()) * time.Second; ttl != checkpointMaxAge {
t.Fatalf("checkpoint ttl = %v, want %v so a path TTL rule cannot shorten it", ttl, checkpointMaxAge)
if got := f.cursors()["/logs/"].TsNs; got != tsNs-1 {
t.Fatalf("cursor = %d, want %d so the waiting event is replayed", got, tsNs-1)
}
}
func TestExecuteReplacesARejectedCheckpointWithAFreshRecord(t *testing.T) {
f := resumeTree()
key := checkpointDir + "/" + checkpointName(f.signature)
old := time.Now().Add(-6 * 24 * time.Hour)
content, _ := json.Marshal(walkCheckpoint{Prefixes: []string{"/a/"}, Prefix: "/a/", Cursor: "/a/d2", StartedNs: old.UnixNano()})
f.files[key] = &filer_pb.Entry{Name: checkpointName(f.signature), Content: content, Attributes: &filer_pb.FuseAttributes{Crtime: old.Unix(), TtlSec: int32(checkpointMaxAge / time.Second)}}
f.failList = func(req *filer_pb.ListEntriesRequest) bool {
return req.Directory == "/a/d2" && req.StartFromFileName != ""
func TestExecuteLeavesANestedRulesEntriesToThatRule(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t,
&filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1d"},
&filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/debug/", Ttl: "1h"})
f.saveCursors(t, map[string]ruleCursor{
"/logs/": {TtlSec: 86400, TsNs: now.Add(-24 * time.Hour).UnixNano()},
"/logs/debug/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()},
})
f.write("/logs/debug/trace.log", now.Add(-2*time.Hour), 3600)
f.write("/logs/app.log", now.Add(-2*time.Hour), 86400)
if c := executeOn(t, serveFiler(t, f)); !c.Success {
t.Fatal(c.ErrorMessage)
}
if f.row("/logs/debug/trace.log") != nil || f.lookups["/logs/debug/trace.log"] != 1 {
t.Fatalf("nested rule entry: stored=%v lookups=%d, want removed by one lookup", f.row("/logs/debug/trace.log") != nil, f.lookups["/logs/debug/trace.log"])
}
if f.row("/logs/app.log") == nil {
t.Fatal("an entry not yet due was removed")
}
var prefixes []string
for _, s := range f.subscriptions {
prefixes = append(prefixes, s.PathPrefix)
}
if fmt.Sprint(prefixes) != "[/logs/ /logs/debug/]" {
t.Fatalf("subscriptions = %v, want one per TTL rule", prefixes)
}
}
func TestExecuteListsARuleAgainWhenItsTTLChanged(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"})
f.saveCursors(t, map[string]ruleCursor{
"/logs/": {TtlSec: 7200, TsNs: now.Add(-time.Hour).UnixNano()},
"/old/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()},
})
f.add("/logs/stale.log", false, now.Add(-90*time.Minute), 3600)
if c := executeOn(t, serveFiler(t, f)); !c.Success {
t.Fatal(c.ErrorMessage)
}
if f.lists["/logs"] != 1 || f.row("/logs/stale.log") != nil {
t.Fatalf("lists=%v stale stored=%v, want the TTL path listed once", f.lists, f.row("/logs/stale.log") != nil)
}
cursors := f.cursors()
if _, found := cursors["/old/"]; found {
t.Fatal("the cursor of a removed rule was kept")
}
c := cursors["/logs/"]
if c.TtlSec != 3600 || c.TsNs > now.Add(-2*time.Hour+time.Minute).UnixNano() {
t.Fatalf("cursor = %+v, want ttl 3600 starting two hours back, the longer of both TTLs", c)
}
}
func TestExecuteStopsAtAFailedLookupAndKeepsItsEvent(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1h"})
f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}})
a := f.write("/logs/a.log", now.Add(-2*time.Hour), 3600)
f.write("/logs/b.log", now.Add(-2*time.Hour), 3600)
c := f.write("/logs/c.log", now.Add(-2*time.Hour), 3600)
f.failLookup = "/logs/b.log"
address := serveFiler(t, f)
if done := executeOn(t, address, "/a/", "/b/"); done.Success {
t.Fatal("the interrupted walk reported success")
if completed := executeOn(t, address); completed.Success || !strings.Contains(completed.ErrorMessage, "/logs/b.log") {
t.Fatalf("completed = %+v, want a failure naming the lookup", completed)
}
if got := f.cursors()["/logs/"].TsNs; got != a.TsNs {
t.Fatalf("cursor = %d, want %d before the failed lookup", got, a.TsNs)
}
f.mu.Lock()
entry := f.files[key]
f.failLookup = ""
f.mu.Unlock()
if entry == nil {
t.Fatal("the interrupted walk stored no checkpoint")
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if created := time.Unix(entry.GetAttributes().GetCrtime(), 0); time.Since(created) > time.Minute {
t.Fatalf("checkpoint created at %v, so its TTL counts from the rejected record", created)
if f.row("/logs/b.log") != nil || f.row("/logs/c.log") != nil {
t.Fatal("entries after the failed lookup were not removed on the next run")
}
}
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)
}
if got := f.cursors()["/logs/"].TsNs; got != c.TsNs {
t.Fatalf("cursor = %d, want %d", got, c.TsNs)
}
}
+299
View File
@@ -0,0 +1,299 @@
package filer_ttl
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"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 (
cursorDir = filer.DirectoryEtcSeaweedFS + "/filer_ttl"
cursorSaveWait = 5 * time.Second
)
type ttlRule struct {
prefix string
ttlSec int32
}
// ruleCursor is how far a TTL rule's events are done: no event at or before
// TsNs names an entry that is still waiting for its TTL.
type ruleCursor struct {
TtlSec int32 `json:"ttl_sec"`
TsNs int64 `json:"ts_ns"`
}
type savedCursors struct {
Rules map[string]ruleCursor `json:"rules"`
}
type runStats struct {
directories int64
entries int64
events int64
expired int64
pending int64
}
// ttlRules returns the filer.conf location rules that set a TTL.
func ttlRules(fc *filer.FilerConf) []ttlRule {
var rules []ttlRule
for _, location := range fc.ToProto().Locations {
ttl, err := needle.ReadTTL(location.GetTtl())
if err != nil || ttl.ToSeconds() == 0 {
continue
}
rules = append(rules, ttlRule{prefix: location.LocationPrefix, ttlSec: int32(ttl.ToSeconds())})
}
sort.Slice(rules, func(i, j int) bool { return rules[i].prefix < rules[j].prefix })
return rules
}
// outermost drops the prefixes another one in the sorted list encloses.
func outermost(prefixes []string) []string {
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
}
// owner is the longest TTL rule prefix of path, the rule whose TTL the filer
// stamps on entries written there.
func owner(rules []ttlRule, path string) string {
found := ""
for _, rule := range rules {
if len(rule.prefix) > len(found) && strings.HasPrefix(path, rule.prefix) {
found = rule.prefix
}
}
return found
}
// expiresAt is when the filer's lookups and listings start treating entry as
// gone; ok is false for an entry they never expire.
func expiresAt(entry *filer.Entry) (deadline time.Time, ok bool) {
if entry.IsDirectory() || entry.TtlSec <= 0 {
return time.Time{}, false
}
if entry.IsExpireS3Enabled() {
if entry.IsS3Versioning() {
return time.Time{}, false
}
return entry.GetS3ExpireTime(), true
}
return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second), true
}
// cursorName is keyed by the store signature, so cursors that filer.sync
// copies into another cluster's store are never read there.
func cursorName(signature int32) string {
return fmt.Sprintf("cursors-%d.json", signature)
}
func loadCursors(ctx context.Context, client filer_pb.SeaweedFilerClient, name string) (map[string]ruleCursor, error) {
content, err := filer.ReadInsideFiler(ctx, client, cursorDir, name)
if errors.Is(err, filer_pb.ErrNotFound) {
return map[string]ruleCursor{}, nil
}
if err != nil {
return nil, fmt.Errorf("read cursors: %w", err)
}
var saved savedCursors
if err := json.Unmarshal(content, &saved); err != nil {
glog.Warningf("filer_ttl: decode cursors: %v; starting every rule over", err)
}
if saved.Rules == nil {
saved.Rules = map[string]ruleCursor{}
}
return saved.Rules, nil
}
// saveCursors runs on its own context, so a run its deadline stopped still
// keeps what it finished.
func saveCursors(client filer_pb.SeaweedFilerClient, name string, cursors map[string]ruleCursor) error {
content, err := json.Marshal(savedCursors{Rules: cursors})
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), cursorSaveWait)
defer cancel()
if err := filer.SaveInsideFiler(ctx, client, cursorDir, name, content); err != nil {
return fmt.Errorf("save cursors: %w", err)
}
return nil
}
// expireByEvents replays each TTL rule's metadata events from its cursor and
// has the filer remove every entry whose TTL has passed. A rule without a
// cursor, or whose TTL changed, is listed first: rows written before its
// replay window are only reached that way.
func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, stats *runStats) error {
conf, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("filer configuration: %w", err)
}
name := cursorName(conf.Signature)
saved, err := loadCursors(ctx, client, name)
if err != nil {
return err
}
runNow := time.Now()
cursors := make(map[string]ruleCursor, len(rules))
var walk []string
for _, rule := range rules {
c, found := saved[rule.prefix]
if found && c.TtlSec == rule.ttlSec {
cursors[rule.prefix] = c
continue
}
window := time.Duration(max(rule.ttlSec, c.TtlSec)) * time.Second
cursors[rule.prefix] = ruleCursor{TtlSec: rule.ttlSec, TsNs: runNow.Add(-window).UnixNano()}
walk = append(walk, rule.prefix)
}
var failed []string
unwalked := map[string]bool{}
for _, prefix := range outermost(walk) {
if err := walkLocationPrefix(ctx, client, prefix, stats); err != nil {
failed = append(failed, fmt.Sprintf("walk %s: %v", prefix, err))
for _, p := range walk {
if strings.HasPrefix(p, prefix) {
unwalked[p] = true
}
}
}
}
for _, rule := range rules {
if unwalked[rule.prefix] {
if c, found := saved[rule.prefix]; found {
cursors[rule.prefix] = c
} else {
delete(cursors, rule.prefix)
}
continue
}
c := cursors[rule.prefix]
tsNs, err := replayRule(ctx, client, rules, rule.prefix, c.TsNs, runNow, stats)
c.TsNs = tsNs
cursors[rule.prefix] = c
if err != nil {
failed = append(failed, fmt.Sprintf("replay %s: %v", rule.prefix, err))
}
}
if err := saveCursors(client, name, cursors); err != nil {
failed = append(failed, err.Error())
}
if len(failed) > 0 {
return errors.New(strings.Join(failed, "; "))
}
return nil
}
// replayRule reads the events under prefix after startTsNs up to runNow and
// looks up every entry the rule owns whose TTL has passed; the lookup is what
// makes the filer remove the expired row. It returns how far the events are
// done: the first entry not yet due holds the cursor, so a later run replays
// its event once the TTL has passed.
func replayRule(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, prefix string, startTsNs int64, runNow time.Time, stats *runStats) (int64, error) {
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
untilNs := runNow.UnixNano()
stream, err := client.SubscribeMetadata(streamCtx, &filer_pb.SubscribeMetadataRequest{
ClientName: "filer_ttl",
PathPrefix: prefix,
SinceNs: startTsNs,
UntilNs: untilNs,
ClientId: util.RandomInt32(),
ClientSupportsBatching: true,
})
if err != nil {
return startTsNs, fmt.Errorf("subscribe: %w", err)
}
done, held := startTsNs, false
handle := func(event *filer_pb.SubscribeMetadataResponse) error {
if event.EventNotification == nil || event.TsNs <= startTsNs {
return nil
}
stats.events++
waiting, err := expireEventEntry(streamCtx, client, rules, prefix, event, runNow, stats)
if err != nil {
return err
}
if waiting && !held {
held = true
if done == event.TsNs {
done--
}
}
if !held {
done = event.TsNs
}
return nil
}
for {
resp, err := stream.Recv()
if err == io.EOF {
return done, nil
}
if err != nil {
return done, err
}
for _, event := range append([]*filer_pb.SubscribeMetadataResponse{resp}, resp.Events...) {
if event.TsNs > untilNs {
return done, nil
}
if err := handle(event); err != nil {
return done, err
}
}
}
}
// expireEventEntry reports whether the entry an event wrote is still waiting
// for its TTL, after looking it up if the TTL has passed.
func expireEventEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, prefix string, event *filer_pb.SubscribeMetadataResponse, runNow time.Time, stats *runStats) (waiting bool, err error) {
notification := event.EventNotification
if notification.NewEntry == nil {
return false, nil
}
dir := notification.NewParentPath
if dir == "" {
dir = event.Directory
}
if owner(rules, string(util.NewFullPath(dir, notification.NewEntry.Name))) != prefix {
return false, nil
}
deadline, ok := expiresAt(filer.FromPbEntry(dir, notification.NewEntry))
if !ok {
return false, nil
}
if deadline.After(runNow) {
stats.pending++
return true, nil
}
_, err = filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: notification.NewEntry.Name})
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
return false, fmt.Errorf("lookup %s/%s: %w", dir, notification.NewEntry.Name, err)
}
stats.expired++
return false, nil
}
+11 -256
View File
@@ -2,277 +2,36 @@ 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
checkpointDir = filer.DirectoryEtcSeaweedFS + "/filer_ttl"
checkpointMaxAge = 7 * 24 * time.Hour
checkpointSaveWait = 5 * time.Second
)
const walkPageSize = 1024
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 {
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
}
// 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)
}
type walker struct {
client filer_pb.SeaweedFilerClient
name string
stats *walkStats
cp walkCheckpoint
onDisk bool
frozen bool
stored 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 {
if !w.stored {
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)
} else if slices.Equal(cp.Prefixes, prefixes) && slices.Contains(prefixes, cp.Prefix) && time.Since(time.Unix(0, cp.StartedNs)) <= checkpointMaxAge {
return &cp
}
// An overwrite keeps the old Crtime, which the record's TTL counts from,
// so a record this pass does not resume from is removed first.
if err := w.clear(ctx); err != nil {
glog.Warningf("filer_ttl: %v", err)
} else {
w.onDisk = false
}
return nil
}
// stop saves 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
w.persist()
}
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()
err := w.save(ctx)
w.stored = err == nil
if 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
// An explicit TTL stops a filer.conf TTL rule over /etc/ from expiring
// the record before load would stop using it.
now := time.Now().Unix()
return filer_pb.CreateEntry(ctx, w.client, &filer_pb.CreateEntryRequest{
Directory: checkpointDir,
Entry: &filer_pb.Entry{
Name: w.name,
Content: content,
Attributes: &filer_pb.FuseAttributes{
Mtime: now,
Crtime: now,
FileMode: 0644,
FileSize: uint64(len(content)),
Md5: util.Md5(content),
TtlSec: int32(checkpointMaxAge / time.Second),
},
},
})
}
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 {
// 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 *runStats) 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))
return walkDirectory(filer_pb.WithChunksOmitted(ctx), client, root, namePrefix, stats)
}
// 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++
func walkDirectory(ctx context.Context, client filer_pb.SeaweedFilerClient, dir util.FullPath, namePrefix string, stats *runStats) error {
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, w.client, string(dir), namePrefix, func(entry *filer_pb.Entry, isLast bool) error {
err := filer_pb.SeaweedList(ctx, client, string(dir), namePrefix, func(entry *filer_pb.Entry, isLast bool) error {
listed++
startFrom = entry.Name
w.stats.entries++
stats.entries++
if entry.IsDirectory {
subDirs = append(subDirs, dir.Child(entry.Name))
}
@@ -282,13 +41,9 @@ func (w *walker) walkDirectory(ctx context.Context, dir util.FullPath, namePrefi
return err
}
for _, subDir := range subDirs {
if err := w.walkDirectory(ctx, subDir, "", nil); err != nil {
if err := walkDirectory(ctx, client, subDir, "", stats); err != nil {
return err
}
w.advance(ctx, subDir)
}
if listed > 0 {
w.advance(ctx, dir.Child(startFrom))
}
if listed < walkPageSize {
return nil