mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
* worker: add a filer_ttl job that walks filer.conf TTL paths A filer store without native TTL keeps the rows of expired entries until something looks them up or lists their directory. The job lists every TTL path subtree once per filer store, so the filer drops the expired rows it meets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: register the filer_ttl job in the lifecycle lane Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: re-check an expired entry under its path lock before a listing deletes it A listing deleted the expired entries it collected by path after the page was read, so a write that replaced one in between lost its new row. The delete now re-reads the row under the lock writers take, and in one conflict-checked transaction on stores that refuse a commit over another writer's change; anything but a still-expired row is kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: read each filer store's own filer.conf, chunk-backed included Filers with separate stores keep separate filer.conf files, so one filer's rules could hide another store's TTL paths. A config stored in chunks read as empty. An unreadable config now fails the detection instead of reading as no rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * command: count filer_ttl among the mini default job types Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: resume an unfinished filer_ttl walk from its checkpoint The walk position is saved in the job's filer store every 30s and at the first failure, keyed by store signature, and cleared when a pass completes. The next run skips the prefixes and subtrees already walked, unless the TTL prefix set changed or the pass is over 7 days old. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: save the filer_ttl checkpoint as soon as a walk fails The first failure froze the checkpoint but only the end of the run saved it, so a worker killed while walking later prefixes lost it. stop now saves it at once; the end of the run saves again only if that save failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep a path TTL rule from expiring the filer_ttl checkpoint A filer.conf TTL rule over /etc/ gave the checkpoint that rule's TTL, so an interrupted pass could lose its record long before checkpointMaxAge. The checkpoint is now written with its own TTL of checkpointMaxAge, which the filer keeps instead of the rule's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: remove a filer_ttl checkpoint the new pass will not resume from An overwrite keeps the stored entry's Crtime, and the checkpoint's TTL counts from it, so a pass that replaced a rejected record could lose its own record before checkpointMaxAge. load now deletes a record it rejects, and the new pass creates a fresh one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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> * filer: re-check an S3-expired entry under its path lock before a listing deletes it A listing deleted an S3-expired object by the row it had read, so an upload that replaced it after the page was read was removed. The delete now re-reads the row under the path lock and removes it only if it is still S3-expired. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer: remove an expired row a lookup meets in a conflict-checked transaction A lookup that met an expired row deleted it by path, so a replacement written through another filer between the read and the delete was lost, even on stores that refuse conflicting commits; a failed delete was hidden behind not found. The lookup now re-reads and deletes through deleteIfExpired and returns the delete error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep a failed filer_ttl lookup that ties a done event When the first event at a timestamp was done and the second one's lookup failed, the cursor already stood at that timestamp, so the retry subscribed after it and skipped the failed event. A failed lookup now holds the cursor below a tie, as a waiting entry does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: hold a filer_ttl event whose entry the filer still serves A lookup that returned the live entry counted as done, so when the worker's clock ran ahead of the filer's near the deadline the event was skipped and the row stayed. An entry the filer still serves with the same deadline now holds the cursor like one not yet due. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: keep a path TTL rule from expiring the filer_ttl cursors The cursors were written without a TTL, so a filer.conf TTL rule covering /etc/seaweedfs/filer_ttl gave them the rule's TTL and every rule was listed again once they expired. When a rule covers them they are now written with a TTL of their own, which the filer keeps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: list a filer_ttl rule again for a live entry its replay cannot reach A new rule nested under a longer one started its replay one TTL back, so a live entry the enclosing rule had stamped with its longer TTL, written before that, was in neither rule's replay: the nested rule now owns it and the enclosing rule skips it. The listing of a new rule now records the earliest deadline of such entries, and the rule is listed again then. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: hand a removed filer_ttl rule's replay to the rule enclosing it When a nested rule was removed, its entries became the enclosing rule's, but that rule's cursor could already be past their events, so they were never replayed. The enclosing rule now replays from the earlier of both cursors. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: list a filer_ttl rule whose unfinished events the filer no longer keeps When fs.log.purge removed the event of an entry still waiting for its TTL, the rule's cursor matched, so the rule was never listed and the replay never met the entry again. A rule whose cursor is older than the oldest kept metadata log is now listed, and its cursor moves to that log. The cursor also records how far a replay read with nothing left waiting, so a quiet rule is not listed just because old logs were purged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: leave S3 lifecycle expiry to the s3_lifecycle job in filer_ttl An entry whose TTL an S3 lifecycle rule set carries the S3 expiry flag; s3_lifecycle evaluates and removes it. filer_ttl no longer looks such entries up, and their deadline no longer holds a TTL rule's cursor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
900 lines
32 KiB
Go
900 lines
32 KiB
Go
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/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 {
|
|
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))
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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}, 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()
|
|
if req.StartFromFileName == "" && !strings.HasPrefix(dir, filer.SystemLogDir) {
|
|
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 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.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)
|
|
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 {
|
|
t.Fatalf("entries with an S3 lifecycle expiry were looked up %d times", n)
|
|
}
|
|
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)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|