diff --git a/weed/worker/tasks/filer_ttl/handler_test.go b/weed/worker/tasks/filer_ttl/handler_test.go
index 1d6b9c37db..5b10b3fa2b 100644
--- a/weed/worker/tasks/filer_ttl/handler_test.go
+++ b/weed/worker/tasks/filer_ttl/handler_test.go
@@ -17,6 +17,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
@@ -71,8 +73,8 @@ func (f *ttlFiler) keepLogsFrom(start time.Time) {
// gone reports whether the filer, whose clock trails by clockLag, treats the
// entry as expired.
func (f *ttlFiler) 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().Add(-f.clockLag))
+ expiresAt, ok := filer.FromPbEntry("/", entry).ExpiresAt()
+ return ok && expiresAt.Before(time.Now().Add(-f.clockLag))
}
func (f *ttlFiler) put(fullPath string, entry *filer_pb.Entry) {
@@ -121,6 +123,40 @@ func (f *ttlFiler) writeAt(tsNs int64, fullPath string, crtime time.Time, ttlSec
return event
}
+// asS3Object turns the file an event wrote into an S3 object last modified
+// at mtime, with the expiry flag the filer puts on one it gives a TTL.
+func (f *ttlFiler) asS3Object(event *filer_pb.SubscribeMetadataResponse, mtime time.Time) *filer_pb.SubscribeMetadataResponse {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ written := event.EventNotification.NewEntry
+ for _, entry := range []*filer_pb.Entry{written, f.dirs[event.Directory][written.Name]} {
+ entry.Attributes.Mtime = mtime.Unix()
+ entry.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
+ }
+ return event
+}
+
+// addLifecycleRules gives a bucket an S3 lifecycle configuration whose rule
+// the fast path stamps on writes.
+func (f *ttlFiler) addLifecycleRules(bucket string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.put("/buckets/"+bucket, &filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}, Extended: map[string][]byte{
+ scheduler.BucketLifecycleConfigurationXMLKey: []byte(`expireEnabled365`),
+ s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
+ }})
+}
+
+// lifecycleSignature is what a cursor of the rule at prefix saved under the
+// buckets' current lifecycle rules carries.
+func (f *ttlFiler) lifecycleSignature(prefix string, buckets ...string) int64 {
+ l := &lifecycleBuckets{dir: "/buckets/", rules: map[string][]*s3lifecycle.Rule{}}
+ for _, bucket := range buckets {
+ l.rules[bucket] = stampingRules(f.row("/buckets/" + bucket).Extended[scheduler.BucketLifecycleConfigurationXMLKey])
+ }
+ return l.signature(prefix)
+}
+
func (f *ttlFiler) remove(fullPath string) *filer_pb.SubscribeMetadataResponse {
f.mu.Lock()
defer f.mu.Unlock()
@@ -173,7 +209,7 @@ func (f *ttlFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryReque
}
func (f *ttlFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
- return &filer_pb.GetFilerConfigurationResponse{Signature: f.signature}, nil
+ return &filer_pb.GetFilerConfigurationResponse{Signature: f.signature, DirBuckets: "/buckets"}, nil
}
func (f *ttlFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
@@ -219,7 +255,8 @@ func (f *ttlFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb
dir = "/"
}
f.mu.Lock()
- if req.StartFromFileName == "" && !strings.HasPrefix(dir, filer.SystemLogDir) {
+ // reading the log start and the buckets' lifecycle rules lists no TTL path
+ if req.StartFromFileName == "" && !strings.HasPrefix(dir, filer.SystemLogDir) && dir != "/buckets" {
f.lists[dir]++
}
var names []string
@@ -398,6 +435,21 @@ func TestTTLRulesOwnerAndOutermost(t *testing.T) {
}
}
+func TestLifecycleSignatureTellsRuleListsApart(t *testing.T) {
+ signature := func(rules ...*s3lifecycle.Rule) int64 {
+ l := &lifecycleBuckets{dir: "/buckets/", rules: map[string][]*s3lifecycle.Rule{"cam": rules}}
+ return l.signature("/buckets/")
+ }
+ two := signature(&s3lifecycle.Rule{Prefix: "x", ExpirationDays: 1}, &s3lifecycle.Rule{Prefix: "y", ExpirationDays: 2})
+ one := signature(&s3lifecycle.Rule{Prefix: "x\t1\t0\t0\ny", ExpirationDays: 2})
+ if two == one || two == 0 || one == 0 {
+ t.Fatalf("signatures %d and %d, want two different nonzero ones", two, one)
+ }
+ if got := (&lifecycleBuckets{dir: "/buckets/", rules: map[string][]*s3lifecycle.Rule{"cam": {{Prefix: "x", ExpirationDays: 1}}}}).signature("/data/"); got != 0 {
+ t.Fatalf("signature of a prefix covering no bucket = %d, want 0", got)
+ }
+}
+
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)
@@ -562,18 +614,11 @@ func TestExecuteLeavesS3LifecycleExpiryToTheLifecycleJob(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"})
- f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}})
- lifecycle := func(fullPath string, mtime time.Time, ttlSec int32) {
- event := f.write(fullPath, mtime, ttlSec)
- f.mu.Lock()
- defer f.mu.Unlock()
- for _, entry := range []*filer_pb.Entry{event.EventNotification.NewEntry, f.dirs[event.Directory][event.EventNotification.NewEntry.Name]} {
- entry.Attributes.Mtime = mtime.Unix()
- entry.Extended = map[string][]byte{s3_constants.SeaweedFSExpiresS3: []byte("true")}
- }
- }
- lifecycle("/buckets/cam/kept-a-year.mp4", now, 365*24*3600)
- lifecycle("/buckets/cam/lifecycle-expired.mp4", now.Add(-2*time.Hour), 3600)
+ f.addLifecycleRules("cam")
+ f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano(), Lifecycle: f.lifecycleSignature("/buckets/cam/", "cam")}})
+ f.asS3Object(f.write("/buckets/cam/kept-a-year.mp4", now, 365*24*3600), now)
+ yearAgo := now.Add(-366 * 24 * time.Hour)
+ f.asS3Object(f.write("/buckets/cam/lifecycle-expired.mp4", yearAgo, 365*24*3600), yearAgo)
last := f.write("/buckets/cam/path-ttl.mp4", now.Add(-2*time.Hour), 3600)
address := serveFiler(t, f)
@@ -583,14 +628,176 @@ func TestExecuteLeavesS3LifecycleExpiryToTheLifecycleJob(t *testing.T) {
if f.row("/buckets/cam/path-ttl.mp4") != nil {
t.Fatal("an entry past its path TTL is still stored")
}
- if n := f.lookups["/buckets/cam/kept-a-year.mp4"] + f.lookups["/buckets/cam/lifecycle-expired.mp4"]; n != 0 {
- t.Fatalf("entries with an S3 lifecycle expiry were looked up %d times", n)
+ if n := f.lookups["/buckets/cam/kept-a-year.mp4"] + f.lookups["/buckets/cam/lifecycle-expired.mp4"]; n != 0 || f.lists["/buckets/cam"] != 0 {
+ t.Fatalf("entries with an S3 lifecycle expiry were looked up %d times, rule listed %d times", n, f.lists["/buckets/cam"])
}
if got := f.cursors()["/buckets/cam/"].TsNs; got != last.TsNs {
t.Fatalf("cursor = %d, want the last event %d: an S3 lifecycle expiry held it", got, last.TsNs)
}
}
+// An object the replay left to s3_lifecycle is reached again by listing the
+// rule once the bucket's fast-path rules change.
+func TestExecuteListsARuleAgainWhenItsBucketsLifecycleRulesChange(t *testing.T) {
+ now := time.Now()
+ f := newTTLFiler(1)
+ f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"})
+ f.addLifecycleRules("cam")
+ f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano(), Lifecycle: f.lifecycleSignature("/buckets/cam/", "cam")}})
+ yearAgo := now.Add(-366 * 24 * time.Hour)
+ f.asS3Object(f.write("/buckets/cam/stamped.mp4", yearAgo, 365*24*3600), yearAgo)
+ address := serveFiler(t, f)
+
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("run: %s", c.ErrorMessage)
+ }
+ if f.row("/buckets/cam/stamped.mp4") == nil || f.lists["/buckets/cam"] != 0 {
+ t.Fatalf("lists=%v: the object the fast path stamped was not left to s3_lifecycle", f.lists)
+ }
+ f.mu.Lock()
+ f.put("/buckets/cam", &filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}, Extended: map[string][]byte{s3_constants.ExtLifecycleTtlFastPathKey: []byte("true")}})
+ f.mu.Unlock()
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("second run: %s", c.ErrorMessage)
+ }
+ if f.row("/buckets/cam/stamped.mp4") != nil || f.lists["/buckets/cam"] != 1 {
+ t.Fatalf("lists=%v: an expired object whose lifecycle rule was removed is still stored", f.lists)
+ }
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("third run: %s", c.ErrorMessage)
+ }
+ if f.lists["/buckets/cam"] != 1 {
+ t.Fatalf("rule listed %d times, want once", f.lists["/buckets/cam"])
+ }
+}
+
+// The filer flags every S3 object it gives a TTL, so in a bucket without
+// lifecycle rules the path TTL is all that expires one, counted from its mtime.
+func TestExecuteExpiresS3ObjectsOfABucketWithoutLifecycleRules(t *testing.T) {
+ now := time.Now()
+ f := newTTLFiler(1)
+ f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"})
+ f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}})
+ f.asS3Object(f.write("/buckets/cam/day1/expired.mp4", now.Add(-2*time.Hour), 3600), now.Add(-2*time.Hour))
+ rewritten := f.asS3Object(f.write("/buckets/cam/day1/rewritten.mp4", now.Add(-2*time.Hour), 3600), now.Add(-time.Minute))
+ address := serveFiler(t, f)
+
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("run: %s", c.ErrorMessage)
+ }
+ if f.row("/buckets/cam/day1/expired.mp4") != nil {
+ t.Fatal("an S3 object past its path TTL is still stored")
+ }
+ if f.lookups["/buckets/cam/day1/rewritten.mp4"] != 0 || f.row("/buckets/cam/day1/rewritten.mp4") == nil {
+ t.Fatal("an S3 object was looked up before its TTL, which counts from its mtime")
+ }
+ if got := f.cursors()["/buckets/cam/"].TsNs; got >= rewritten.TsNs {
+ t.Fatalf("cursor = %d, want it held below the waiting S3 object's event %d", got, rewritten.TsNs)
+ }
+}
+
+// A bucket's lifecycle rules stamp no TTL without the fast path, or on an
+// object no rule that expires after days matches, and a TTL other than the
+// matching rule's, on a multipart upload or an object written before the
+// rule, is the path rule's, so the path rule expires the flagged object.
+func TestExecuteExpiresS3ObjectsOfABucketWhoseLifecycleRulesStampNoTTL(t *testing.T) {
+ for name, bucket := range map[string]map[string][]byte{
+ "no fast path": {
+ scheduler.BucketLifecycleConfigurationXMLKey: []byte(`expireEnabled365`),
+ },
+ "no rules": {
+ s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
+ scheduler.BucketLifecycleConfigurationXMLKey: []byte(``),
+ },
+ "a rule for another prefix": {
+ s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
+ scheduler.BucketLifecycleConfigurationXMLKey: []byte(`logsEnabledlogs/365`),
+ },
+ "a rule stamping another TTL": {
+ s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
+ scheduler.BucketLifecycleConfigurationXMLKey: []byte(`expireEnabled365`),
+ },
+ "abort multipart uploads only": {
+ s3_constants.ExtLifecycleTtlFastPathKey: []byte("true"),
+ scheduler.BucketLifecycleConfigurationXMLKey: []byte(`mpuEnabled7`),
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ now := time.Now()
+ f := newTTLFiler(1)
+ f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"})
+ f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: now.Add(-time.Hour).UnixNano()}})
+ f.mu.Lock()
+ f.put("/buckets/cam", &filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}, Extended: bucket})
+ f.mu.Unlock()
+ f.asS3Object(f.write("/buckets/cam/day1/expired.mp4", now.Add(-2*time.Hour), 3600), now.Add(-2*time.Hour))
+ address := serveFiler(t, f)
+
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("run: %s", c.ErrorMessage)
+ }
+ if f.row("/buckets/cam/day1/expired.mp4") != nil {
+ t.Fatal("an S3 object past the path TTL no lifecycle rule stamped is still stored")
+ }
+ })
+ }
+}
+
+// The cursors an earlier version saved are past the S3 objects it skipped, so
+// they are not resumed: the rule is listed once more, which removes them.
+func TestExecuteListsARuleAgainWhoseCursorSkippedS3Objects(t *testing.T) {
+ now := time.Now()
+ f := newTTLFiler(1)
+ f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "1h"})
+ skipped := f.asS3Object(f.write("/buckets/cam/day1/skipped.mp4", now.Add(-2*time.Hour), 3600), now.Add(-2*time.Hour))
+ content, err := json.Marshal(savedCursors{Rules: map[string]ruleCursor{"/buckets/cam/": {TtlSec: 3600, TsNs: skipped.TsNs, ReadNs: skipped.TsNs}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.mu.Lock()
+ f.put(fmt.Sprintf("%s/cursors-%d.json", cursorDir, f.signature), &filer_pb.Entry{Content: content, Attributes: &filer_pb.FuseAttributes{}})
+ f.mu.Unlock()
+ address := serveFiler(t, f)
+
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("run: %s", c.ErrorMessage)
+ }
+ if f.row("/buckets/cam/day1/skipped.mp4") != nil {
+ t.Fatal("an S3 object the earlier cursor had passed is still stored")
+ }
+ if f.lists["/buckets/cam"] != 1 || f.cursors()["/buckets/cam/"].TtlSec != 3600 {
+ t.Fatalf("lists=%v cursors=%v, want the rule listed once and a new cursor saved", f.lists, f.cursors())
+ }
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("second run: %s", c.ErrorMessage)
+ }
+ if f.lists["/buckets/cam"] != 1 {
+ t.Fatalf("rule listed %d times, want once", f.lists["/buckets/cam"])
+ }
+}
+
+// A listing also schedules the next one for an S3 object the replay does not
+// reach, here one an enclosing rule stamped before the nested rule existed.
+func TestExecuteListsARuleAgainAtAnOlderS3ObjectsDeadline(t *testing.T) {
+ now := time.Now()
+ f := newTTLFiler(1)
+ f.conf = filerConf(t,
+ &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/", Ttl: "7d"},
+ &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/cam/debug/", Ttl: "1h"})
+ f.saveCursors(t, map[string]ruleCursor{"/buckets/cam/": {TtlSec: 7 * 86400, TsNs: now.Add(-7 * 24 * time.Hour).UnixNano()}})
+ written := now.Add(-3 * 24 * time.Hour)
+ f.asS3Object(f.writeAt(written.UnixNano(), "/buckets/cam/debug/trace.log", written, 7*86400), written)
+ address := serveFiler(t, f)
+
+ if c := executeOn(t, address); !c.Success {
+ t.Fatalf("run: %s", c.ErrorMessage)
+ }
+ deadline := time.Unix(written.Unix(), 0).Add(7 * 24 * time.Hour)
+ if got := f.cursors()["/buckets/cam/debug/"].WalkAtNs; got != deadline.UnixNano() {
+ t.Fatalf("nested rule lists again at %d, want the S3 object's deadline %d", got, deadline.UnixNano())
+ }
+}
+
func TestExecuteHoldsTheCursorBelowATieWithAWaitingEntry(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
diff --git a/weed/worker/tasks/filer_ttl/replay.go b/weed/worker/tasks/filer_ttl/replay.go
index 7b093c6344..7069e67390 100644
--- a/weed/worker/tasks/filer_ttl/replay.go
+++ b/weed/worker/tasks/filer_ttl/replay.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
+ "math"
"sort"
"strings"
"time"
@@ -14,6 +15,10 @@ import (
"github.com/seaweedfs/seaweedfs/weed/filer/treewalk"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/lifecycle_xml"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3lifecycle/scheduler"
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/util"
)
@@ -37,11 +42,14 @@ type ttlRule struct {
// the last replay read with no entry left waiting, so the events up to it
// are no longer needed. WalkAtNs, when set, is when the rule is listed again,
// for a live entry the last listing met whose event the replay does not reach.
+// Lifecycle is the signature of the fast-path rules the rule's events were
+// read under.
type ruleCursor struct {
- TtlSec int32 `json:"ttl_sec"`
- TsNs int64 `json:"ts_ns"`
- ReadNs int64 `json:"read_ns,omitempty"`
- WalkAtNs int64 `json:"walk_at_ns,omitempty"`
+ TtlSec int32 `json:"ttl_sec"`
+ TsNs int64 `json:"ts_ns"`
+ ReadNs int64 `json:"read_ns,omitempty"`
+ WalkAtNs int64 `json:"walk_at_ns,omitempty"`
+ Lifecycle int64 `json:"lifecycle,omitempty"`
}
type savedCursors struct {
@@ -94,20 +102,126 @@ func owner(rules []ttlRule, path string) string {
return found
}
+// lifecycleBuckets holds each bucket's lifecycle rules that stamp object TTLs
+// at write time, the opt-in fast path. Any other TTL came from a path rule.
+type lifecycleBuckets struct {
+ dir string // the buckets directory, ending in a slash
+ rules map[string][]*s3lifecycle.Rule
+}
+
+func loadLifecycleBuckets(ctx context.Context, client filer_pb.SeaweedFilerClient, dirBuckets string) (*lifecycleBuckets, error) {
+ found := &lifecycleBuckets{dir: strings.TrimSuffix(dirBuckets, "/") + "/", rules: map[string][]*s3lifecycle.Rule{}}
+ if dirBuckets == "" {
+ return found, nil
+ }
+ const pageSize = 1024
+ for startFrom := ""; ; {
+ count := 0
+ err := filer_pb.SeaweedList(ctx, client, dirBuckets, "", func(entry *filer_pb.Entry, isLast bool) error {
+ count++
+ startFrom = entry.Name
+ if entry.IsDirectory && string(entry.Extended[s3_constants.ExtLifecycleTtlFastPathKey]) == "true" {
+ if rules := stampingRules(entry.Extended[scheduler.BucketLifecycleConfigurationXMLKey]); len(rules) > 0 {
+ found.rules[entry.Name] = rules
+ }
+ }
+ return nil
+ }, startFrom, false, pageSize)
+ if err != nil {
+ return nil, fmt.Errorf("lifecycle buckets: %w", err)
+ }
+ if count < pageSize {
+ return found, nil
+ }
+ }
+}
+
+const secondsPerDay = 24 * 60 * 60
+
+// stampingRules are the rules of a lifecycle configuration the fast path
+// stamps on writes: enabled, expiring after days that fit a TTL, with no tag
+// filter.
+func stampingRules(lifecycleXML []byte) (stamping []*s3lifecycle.Rule) {
+ rules, err := lifecycle_xml.ParseCanonical(lifecycleXML)
+ if err != nil {
+ return nil
+ }
+ for _, r := range rules {
+ if r != nil && r.Status == s3lifecycle.StatusEnabled && r.ExpirationDays > 0 &&
+ int64(r.ExpirationDays)*secondsPerDay <= math.MaxInt32 && len(r.FilterTags) == 0 {
+ stamping = append(stamping, r)
+ }
+ }
+ return stamping
+}
+
+// expires reports whether entry is left to the s3_lifecycle job: its TTL is
+// the one the fast path stamps on its key and size, the shortest of the
+// matching rules. The filer puts the S3 expiry flag on every S3 object it
+// gives a TTL, and a path rule's TTL is also on the objects the fast path
+// leaves alone, multipart uploads and those written before the rule.
+func (l *lifecycleBuckets) expires(entry *filer.Entry) bool {
+ if !entry.IsExpireS3Enabled() {
+ return false
+ }
+ rest, under := strings.CutPrefix(string(entry.FullPath), l.dir)
+ if !under {
+ return false
+ }
+ bucket, key, _ := strings.Cut(rest, "/")
+ size := int64(entry.Size())
+ var days int64
+ for _, r := range l.rules[bucket] {
+ if strings.HasPrefix(key, r.Prefix) &&
+ (r.FilterSizeGreaterThan <= 0 || size > r.FilterSizeGreaterThan) &&
+ (r.FilterSizeLessThan <= 0 || size < r.FilterSizeLessThan) &&
+ (days == 0 || int64(r.ExpirationDays) < days) {
+ days = int64(r.ExpirationDays)
+ }
+ }
+ return days > 0 && int64(entry.TtlSec) == days*secondsPerDay
+}
+
+// signature identifies the fast-path rules of the buckets prefix covers, and
+// is 0 without any.
+func (l *lifecycleBuckets) signature(prefix string) int64 {
+ var buckets []string
+ for bucket := range l.rules {
+ dir := l.dir + bucket + "/"
+ if strings.HasPrefix(dir, prefix) || strings.HasPrefix(prefix, dir) {
+ buckets = append(buckets, bucket)
+ }
+ }
+ if len(buckets) == 0 {
+ return 0
+ }
+ sort.Strings(buckets)
+ var b strings.Builder
+ for _, bucket := range buckets {
+ fmt.Fprintf(&b, "%q\n", bucket)
+ for _, r := range l.rules[bucket] {
+ fmt.Fprintf(&b, "%q %d %d %d\n", r.Prefix, r.ExpirationDays, r.FilterSizeGreaterThan, r.FilterSizeLessThan)
+ }
+ }
+ return util.HashStringToLong(b.String())
+}
+
// expiresAt is when the filer's lookups and listings start treating entry as
-// gone; ok is false for an entry they never expire, and for one whose TTL an
-// S3 lifecycle rule set, which the s3_lifecycle job expires.
-func expiresAt(entry *filer.Entry) (deadline time.Time, ok bool) {
- if entry.IsDirectory() || entry.TtlSec <= 0 || entry.IsExpireS3Enabled() {
+// gone; ok is false for an entry they never expire, and for one the
+// s3_lifecycle job expires.
+func expiresAt(entry *filer.Entry, lifecycle *lifecycleBuckets) (deadline time.Time, ok bool) {
+ if lifecycle.expires(entry) {
return time.Time{}, false
}
- return entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second), true
+ return entry.ExpiresAt()
}
// cursorName is keyed by the store signature, so cursors that filer.sync
-// copies into another cluster's store are never read there.
+// copies into another cluster's store are never read there. The cursors
+// saved before v2 had moved past the S3 objects the replay then skipped;
+// under the new name every rule is listed once as new.
func cursorName(signature int32) string {
- return fmt.Sprintf("cursors-%d.json", signature)
+ return fmt.Sprintf("cursors-v2-%d.json", signature)
}
func loadCursors(ctx context.Context, client filer_pb.SeaweedFilerClient, name string) (map[string]ruleCursor, error) {
@@ -169,7 +283,8 @@ func saveCursors(client filer_pb.SeaweedFilerClient, rules []ttlRule, name strin
// whose unfinished events the filer no longer keeps. A live entry such a
// listing meets that was last written before the window, for example one an
// enclosing rule stamped with its longer TTL, has the rule listed again at
-// its deadline.
+// its deadline. A rule is also listed when the fast-path rules of the buckets
+// it covers change, for the objects its replay left to s3_lifecycle.
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 {
@@ -180,6 +295,10 @@ func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rul
if err != nil {
return err
}
+ lifecycle, err := loadLifecycleBuckets(ctx, client, conf.DirBuckets)
+ if err != nil {
+ return err
+ }
runNow := time.Now()
logStart, err := treewalk.LogStartTsNs(ctx, client)
@@ -194,6 +313,7 @@ func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rul
var walk []string
for _, rule := range rules {
c, found := saved[rule.prefix]
+ stamped := lifecycle.signature(rule.prefix)
switch {
case !found || c.TtlSec != rule.ttlSec:
window := time.Duration(max(rule.ttlSec, c.TtlSec)) * time.Second
@@ -202,10 +322,12 @@ func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rul
c = ruleCursor{TtlSec: c.TtlSec, TsNs: logStart - 1}
case c.WalkAtNs != 0 && c.WalkAtNs <= runNow.UnixNano():
c.WalkAtNs = 0
+ case c.Lifecycle != stamped:
default:
cursors[rule.prefix] = c
continue
}
+ c.Lifecycle = stamped
cursors[rule.prefix] = c
walk = append(walk, rule.prefix)
}
@@ -232,7 +354,7 @@ func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rul
if !walking[prefix] {
return
}
- deadline, ok := expiresAt(filer.FromPbEntry(string(dir), entry))
+ deadline, ok := expiresAt(filer.FromPbEntry(string(dir), entry), lifecycle)
if !ok || !deadline.After(runNow) {
return
}
@@ -278,7 +400,7 @@ func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rul
continue
}
c := cursors[rule.prefix]
- tsNs, readNs, err := replayRule(ctx, client, rules, rule.prefix, c.TsNs, runNow, stats)
+ tsNs, readNs, err := replayRule(ctx, client, rules, lifecycle, rule.prefix, c.TsNs, runNow, stats)
c.TsNs, c.ReadNs = tsNs, readNs
cursors[rule.prefix] = c
if err != nil {
@@ -301,7 +423,7 @@ func expireByEvents(ctx context.Context, client filer_pb.SeaweedFilerClient, rul
// done: the first entry not yet due holds the cursor, so a later run replays
// its event once the TTL has passed. readNs is runNow when the replay read
// to it with no entry left waiting, and 0 otherwise.
-func replayRule(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, prefix string, startTsNs int64, runNow time.Time, stats *runStats) (done, readNs int64, err error) {
+func replayRule(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, lifecycle *lifecycleBuckets, prefix string, startTsNs int64, runNow time.Time, stats *runStats) (done, readNs int64, err error) {
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
untilNs := runNow.UnixNano()
@@ -329,7 +451,7 @@ func replayRule(ctx context.Context, client filer_pb.SeaweedFilerClient, rules [
return nil
}
stats.events++
- waiting, err := expireEventEntry(streamCtx, client, rules, prefix, event, runNow, stats)
+ waiting, err := expireEventEntry(streamCtx, client, rules, lifecycle, prefix, event, runNow, stats)
if (waiting || err != nil) && !held {
held = true
if done == event.TsNs {
@@ -362,7 +484,7 @@ func replayRule(ctx context.Context, client filer_pb.SeaweedFilerClient, rules [
// 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) {
+func expireEventEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, rules []ttlRule, lifecycle *lifecycleBuckets, 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
@@ -374,7 +496,7 @@ func expireEventEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, r
if owner(rules, string(util.NewFullPath(dir, notification.NewEntry.Name))) != prefix {
return false, nil
}
- deadline, ok := expiresAt(filer.FromPbEntry(dir, notification.NewEntry))
+ deadline, ok := expiresAt(filer.FromPbEntry(dir, notification.NewEntry), lifecycle)
if !ok {
return false, nil
}
@@ -392,7 +514,7 @@ func expireEventEntry(ctx context.Context, client filer_pb.SeaweedFilerClient, r
}
// The filer, whose clock may trail this one, still serves it. A later
// write that moved its deadline has its own event.
- if live, ok := expiresAt(filer.FromPbEntry(dir, resp.Entry)); ok && !live.After(deadline) {
+ if live, ok := expiresAt(filer.FromPbEntry(dir, resp.Entry), lifecycle); ok && !live.After(deadline) {
stats.pending++
return true, nil
}