package filer_ttl
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"sort"
"strings"
"sync"
"testing"
"time"
"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/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"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// 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
events []*filer_pb.SubscribeMetadataResponse
lastTsNs int64
lists map[string]int
lookups map[string]int
failLookup string
clockLag time.Duration
subscriptions []*filer_pb.SubscribeMetadataRequest
}
// newTTLFiler keeps metadata logs from 2000 on.
func newTTLFiler(signature int32) *ttlFiler {
f := &ttlFiler{signature: signature, dirs: map[string]map[string]*filer_pb.Entry{}, lists: map[string]int{}, lookups: map[string]int{}}
f.keepLogsFrom(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC))
return f
}
// keepLogsFrom stands for the persisted metadata logs, the oldest one
// starting at the minute of start.
func (f *ttlFiler) keepLogsFrom(start time.Time) {
f.mu.Lock()
defer f.mu.Unlock()
delete(f.dirs, filer.SystemLogDir)
for dir := range f.dirs {
if strings.HasPrefix(dir, filer.SystemLogDir+"/") {
delete(f.dirs, dir)
}
}
start = start.UTC()
day := filer.SystemLogDir + "/" + start.Format("2006-01-02")
f.put(day, &filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}})
f.put(day+"/"+start.Format("15-04")+".0000000a", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
f.put(day+"/23-59.0000000a", &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
}
// gone reports whether the filer, whose clock trails by clockLag, treats the
// entry as expired.
func (f *ttlFiler) gone(entry *filer_pb.Entry) bool {
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) {
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()
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
}
// 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()
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 saved savedCursors
if err := json.Unmarshal(entry.Content, &saved); err != nil {
return nil
}
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()
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.put(req.Directory+"/"+req.Entry.Name, proto.Clone(req.Entry).(*filer_pb.Entry))
return &filer_pb.UpdateEntryResponse{}, nil
}
func (f *ttlFiler) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
return &filer_pb.GetFilerConfigurationResponse{Signature: f.signature, DirBuckets: "/buckets"}, nil
}
func (f *ttlFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
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
}
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.gone(entry) {
delete(f.dirs[req.Directory], req.Name)
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
}
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) {
resp := &filer_pb.LookupVolumeResponse{LocationsMap: map[string]*filer_pb.Locations{}}
for _, vid := range req.VolumeIds {
resp.LocationsMap[vid] = &filer_pb.Locations{Locations: []*filer_pb.Location{{Url: f.volumeUrl}}}
}
return resp, 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()
// 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
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
}
if f.gone(f.dirs[dir][name]) {
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
}
// 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")
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 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"},
{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)
}
}
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)
}
}
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)
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 want := []string{addresses[0], addresses[2]}; fmt.Sprint(got) != fmt.Sprint(want) {
t.Fatalf("proposed filers = %v, want %v", got, want)
}
}
func TestDetectReadsEachStoresOwnFilerConf(t *testing.T) {
plain, clips := newTTLFiler(1), newTTLFiler(2)
plain.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/buckets/a/", Replication: "001"})
clips.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/clips/", Ttl: "1d"})
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write(clips.conf)
}))
t.Cleanup(volume.Close)
clips.volumeUrl = strings.TrimPrefix(volume.URL, "http://")
addresses := []string{serveFiler(t, plain), serveFiler(t, clips)}
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)
}
if len(sender.proposals) != 1 {
t.Fatalf("proposals = %d, want 1", len(sender.proposals))
}
if got := sender.proposals[0].Parameters[filerAddressParam].GetStringValue(); got != addresses[1] {
t.Fatalf("proposed filer = %s, want %s", got, addresses[1])
}
}
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 TestExecuteListsANewRuleOnceThenReplaysItsEvents(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
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, 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)
if c := executeOn(t, address); !c.Success {
t.Fatalf("first run: %s", c.ErrorMessage)
}
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)
}
if f.row("/keep/old.bin") == nil {
t.Fatal("an entry outside every TTL path was removed")
}
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)
}
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.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 TestExecuteHoldsTheCursorAtTheFirstEntryNotYetDue(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)
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 c := executeOn(t, address); !c.Success {
t.Fatalf("first run: %s", c.ErrorMessage)
}
if f.row("/logs/a.log") != nil || f.row("/logs/c.log") != nil {
t.Fatal("an entry whose TTL passed is still stored")
}
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)
}
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.row("/logs/b.log") != nil {
t.Fatal("the held entry was not removed once its TTL passed")
}
if got := f.subscriptions[1].SinceNs; got != a.TsNs {
t.Fatalf("second run subscribed from %d, want %d", got, a.TsNs)
}
if got := f.cursors()["/logs/"].TsNs; got != last.TsNs {
t.Fatalf("cursor = %d, want the last event %d", got, last.TsNs)
}
}
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.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)
if c := executeOn(t, address); !c.Success {
t.Fatalf("run: %s", c.ErrorMessage)
}
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 || 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)
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)
if c := executeOn(t, serveFiler(t, f)); !c.Success {
t.Fatal(c.ErrorMessage)
}
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 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 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()
f.failLookup = ""
f.mu.Unlock()
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
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")
}
if got := f.cursors()["/logs/"].TsNs; got != c.TsNs {
t.Fatalf("cursor = %d, want %d", got, c.TsNs)
}
}
func TestExecuteKeepsAFailedLookupThatTiesADoneEvent(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.Add(-2*time.Hour), 3600)
f.failLookup = "/logs/b.log"
address := serveFiler(t, f)
if completed := executeOn(t, address); completed.Success {
t.Fatal("a failed lookup reported success")
}
if got := f.cursors()["/logs/"].TsNs; got != tsNs-1 {
t.Fatalf("cursor = %d, want %d so the failed event is replayed", got, tsNs-1)
}
f.mu.Lock()
f.failLookup = ""
f.mu.Unlock()
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.row("/logs/b.log") != nil {
t.Fatal("the entry of the failed lookup was not removed on the next run")
}
}
func TestExecuteHoldsAnEntryTheFilerStillServes(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(-2 * time.Hour).UnixNano()}})
first := f.write("/logs/a.log", now.Add(-2*time.Hour), 3600)
f.write("/logs/b.log", now.Add(-61*time.Minute), 3600)
f.clockLag = 5 * time.Minute
address := serveFiler(t, f)
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.row("/logs/a.log") != nil || f.row("/logs/b.log") == nil {
t.Fatal("want the entry due on both clocks removed and the other one kept")
}
if got := f.cursors()["/logs/"].TsNs; got != first.TsNs {
t.Fatalf("cursor = %d, want %d before the entry the filer still serves", got, first.TsNs)
}
f.mu.Lock()
f.clockLag = 0
f.mu.Unlock()
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.row("/logs/b.log") != nil {
t.Fatal("the held entry was not removed once the filer saw it expire")
}
}
func TestExecuteKeepsAPathTTLOffTheCursors(t *testing.T) {
for _, covered := range []bool{false, true} {
f := newTTLFiler(1)
rules := []*filer_pb.FilerConf_PathConf{{LocationPrefix: "/logs/", Ttl: "1h"}}
if covered {
rules = append(rules, &filer_pb.FilerConf_PathConf{LocationPrefix: "/etc/", Ttl: "1h"})
}
f.conf = filerConf(t, rules...)
if completed := executeOn(t, serveFiler(t, f)); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
row := f.row(cursorDir + "/" + cursorName(1))
if row == nil {
t.Fatal("cursors not saved")
}
want := int32(0)
if covered {
want = int32(cursorTTL / time.Second)
}
if got := row.Attributes.TtlSec; got != want {
t.Fatalf("covered=%v: cursor TTL = %d, want %d", covered, got, want)
}
}
}
func TestExecuteListsANewNestedRuleAgainAtAnOlderEntrysDeadline(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t,
&filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "7d"},
&filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/debug/", Ttl: "1h"})
f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 7 * 86400, TsNs: now.Add(-7 * 24 * time.Hour).UnixNano()}})
written := now.Add(-3 * 24 * time.Hour)
f.writeAt(written.UnixNano(), "/logs/debug/trace.log", written, 7*86400)
address := serveFiler(t, f)
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
deadline := written.Add(7 * 24 * time.Hour)
if got := f.cursors()["/logs/debug/"].WalkAtNs; got != time.Unix(deadline.Unix(), 0).UnixNano() {
t.Fatalf("nested rule lists again at %d, want the entry's deadline %d", got, deadline.UnixNano())
}
if got := f.cursors()["/logs/"].WalkAtNs; got != 0 {
t.Fatalf("enclosing rule lists again at %d, want never", got)
}
cursors := f.cursors()
c := cursors["/logs/debug/"]
c.WalkAtNs = now.UnixNano()
cursors["/logs/debug/"] = c
f.saveCursors(t, cursors)
f.mu.Lock()
f.dirs["/logs/debug"]["trace.log"].Attributes.Crtime = now.Add(-8 * 24 * time.Hour).Unix()
f.mu.Unlock()
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.row("/logs/debug/trace.log") != nil || f.lists["/logs/debug"] != 2 {
t.Fatalf("stored=%v lists=%v, want the nested rule listed again and the entry removed", f.row("/logs/debug/trace.log") != nil, f.lists)
}
if got := f.cursors()["/logs/debug/"].WalkAtNs; got != 0 {
t.Fatalf("nested rule lists again at %d after the entry went", got)
}
}
func TestExecuteHandsARemovedNestedRulesReplayToTheEnclosingRule(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1d"})
f.saveCursors(t, map[string]ruleCursor{
"/logs/": {TtlSec: 86400, TsNs: now.Add(-time.Minute).UnixNano()},
"/logs/debug/": {TtlSec: 3600, TsNs: now.Add(-2 * time.Hour).UnixNano()},
})
f.writeAt(now.Add(-90*time.Minute).UnixNano(), "/logs/debug/trace.log", now.Add(-90*time.Minute), 3600)
if completed := executeOn(t, serveFiler(t, f)); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.row("/logs/debug/trace.log") != nil {
t.Fatal("an expired entry of the removed rule was left behind the enclosing rule's cursor")
}
if _, found := f.cursors()["/logs/debug/"]; found {
t.Fatal("the cursor of the removed rule was kept")
}
}
func TestExecuteListsARuleWhoseUnfinishedEventsAreNoLongerLogged(t *testing.T) {
now := time.Now()
week := int32(7 * 86400)
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "7d"})
held := now.Add(-3 * 24 * time.Hour)
f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: week, TsNs: held.UnixNano()}})
f.add("/logs/expired.log", false, now.Add(-8*24*time.Hour), week)
f.add("/logs/live.log", false, held, week)
logStart := now.Add(-24 * time.Hour)
f.keepLogsFrom(logStart)
address := serveFiler(t, f)
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.lists["/logs"] != 1 || f.row("/logs/expired.log") != nil || f.row("/logs/live.log") == nil {
t.Fatalf("lists=%v, want the rule listed once, the expired row removed and the live one kept", f.lists)
}
c := f.cursors()["/logs/"]
if oldest := logStart.UTC().Truncate(time.Minute); c.TsNs != oldest.UnixNano()-1 {
t.Fatalf("cursor = %d, want just before the oldest log %d", c.TsNs, oldest.UnixNano())
}
if want := time.Unix(held.Unix(), 0).Add(7 * 24 * time.Hour).UnixNano(); c.WalkAtNs != want {
t.Fatalf("lists again at %d, want the live entry's deadline %d", c.WalkAtNs, want)
}
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if f.lists["/logs"] != 1 {
t.Fatalf("lists=%v, want no second listing before that deadline", f.lists)
}
}
func TestExecuteDoesNotListAQuietRuleAfterOldLogsArePurged(t *testing.T) {
now := time.Now()
f := newTTLFiler(1)
f.conf = filerConf(t, &filer_pb.FilerConf_PathConf{LocationPrefix: "/logs/", Ttl: "1d"})
f.saveCursors(t, map[string]ruleCursor{"/logs/": {TtlSec: 86400, TsNs: now.Add(-30 * 24 * time.Hour).UnixNano()}})
address := serveFiler(t, f)
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if c := f.cursors()["/logs/"]; c.ReadNs < now.UnixNano() {
t.Fatalf("cursor = %+v, want the replay read up to the run", c)
}
f.keepLogsFrom(now.Add(-time.Hour))
if completed := executeOn(t, address); !completed.Success {
t.Fatal(completed.ErrorMessage)
}
if len(f.lists) != 0 {
t.Fatalf("lists=%v, want none: nothing the replay left waiting was purged", f.lists)
}
}