From c637d60dfc8bfb5441142fcf1e5d51d29301ceea Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Mon, 30 Nov 2026 13:09:23 -0800 Subject: [PATCH] filer.sync: keep an informational replay cursor on the source, and let the log purge honor it (#13176) * filer.sync: save the sync position on the source filer as a replay cursor The position stays authoritative on the target. The source copy holds the last position the target checkpoint stored (a fresh sync without one holds just before the first event it received) and is rewritten hourly while the sync runs, even when the position does not move. Co-Authored-By: Claude Opus 5.5 * filer.sync: do not replicate the sync cursors of the source A target never holds cursors that describe the source's log. A rename into or out of the cursor directory replicates the ordinary side. Co-Authored-By: Claude Opus 5.5 * metadata log purge: keep the logs a filer.sync still needs Co-Authored-By: Claude Opus 5.5 * filer.sync: describe the sync in its source cursor The source cursor is informational: besides the position it records the source and target filers and paths, exclusions, host, version, when the sync started, whether the position is a target checkpoint, and the processed and failed event times, for display in admin tools. The target checkpoint stays authoritative. Co-Authored-By: Claude Opus 5.5 * filer.sync: save the first sync cursor when the first event arrives and retry failed saves A fresh sync only saved its cursor on the next minute tick, and a failed save still pushed the next attempt out by an hour, leaving the purge without a cursor while the sync replayed old log days. Co-Authored-By: Claude Opus 5.5 * filer.backup: do not seed the source's sync cursors in the initial snapshot Co-Authored-By: Claude Opus 5.5 * metadata log purge: say that a position not saved for 7 days stops holding the log Co-Authored-By: Claude Opus 5.5 * filer.backup test: lock the recording sink for concurrent snapshot workers Co-Authored-By: Claude Opus 5.5 * filer.sync: leave the sync cursors out of the metadata log gap check Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- weed/command/filer_backup.go | 3 +- weed/command/filer_backup_snapshot_test.go | 74 ++++++++++++++++ weed/command/filer_backup_versions_test.go | 6 ++ weed/command/filer_sync.go | 50 ++++++++++- weed/command/filer_sync_cursor.go | 73 +++++++++++++++ weed/command/filer_sync_cursor_test.go | 88 +++++++++++++++++++ weed/command/filer_sync_log_gap.go | 2 +- weed/command/filer_sync_log_gap_test.go | 1 + weed/command/filer_sync_process_test.go | 56 ++++++++++++ weed/filer/filer_conf.go | 1 + weed/filer/filer_sync_cursor.go | 24 +++++ weed/shell/command_fs_log.go | 5 +- weed/worker/tasks/meta_log_purge/floor.go | 1 + .../worker/tasks/meta_log_purge/floor_test.go | 26 ++++++ weed/worker/tasks/meta_log_purge/handler.go | 2 +- 15 files changed, 404 insertions(+), 8 deletions(-) create mode 100644 weed/command/filer_backup_snapshot_test.go create mode 100644 weed/command/filer_sync_cursor.go create mode 100644 weed/command/filer_sync_cursor_test.go create mode 100644 weed/filer/filer_sync_cursor.go diff --git a/weed/command/filer_backup.go b/weed/command/filer_backup.go index b166f9e3fd..4ee1a47621 100644 --- a/weed/command/filer_backup.go +++ b/weed/command/filer_backup.go @@ -572,7 +572,8 @@ func runInitialSnapshot( // still gets seeded (only its children would be skipped by the parent // check). if parent == filer.SystemLogDir || strings.HasPrefix(parent, filer.SystemLogDir+"/") || - source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") { + source == filer.SystemLogDir || strings.HasPrefix(source, filer.SystemLogDir+"/") || + isSyncCursor(sourceKey) { return nil } if matchesExcludePath(parent, excludePaths) || matchesExcludePath(source, excludePaths) { diff --git a/weed/command/filer_backup_snapshot_test.go b/weed/command/filer_backup_snapshot_test.go new file mode 100644 index 0000000000..446352840d --- /dev/null +++ b/weed/command/filer_backup_snapshot_test.go @@ -0,0 +1,74 @@ +package command + +import ( + "net" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/replication/source" + "google.golang.org/grpc" +) + +type snapshotListFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + dirs map[string][]*filer_pb.Entry +} + +func (f *snapshotListFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error { + for _, entry := range f.dirs[req.Directory] { + if req.StartFromFileName != "" && (entry.Name < req.StartFromFileName || entry.Name == req.StartFromFileName && !req.InclusiveStartFrom) { + continue + } + if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil { + return err + } + } + return nil +} + +func TestInitialSnapshotSkipsSyncCursors(t *testing.T) { + dir := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + } + file := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{}} + } + fake := &snapshotListFiler{dirs: map[string][]*filer_pb.Entry{ + "/": {dir("data"), dir("etc")}, + "/data": {file("a.txt")}, + "/etc": {dir("seaweedfs")}, + "/etc/seaweedfs": {file("filer.conf"), dir("filer_sync")}, + filer.SyncCursorDir: {file("0000000a-0000000000000001.json")}, + }} + + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, fake) + go server.Serve(lis) + defer server.Stop() + + filerSource := &source.FilerSource{} + if err := filerSource.DoInitialize("localhost:1", lis.Addr().String(), "/", false); err != nil { + t.Fatal(err) + } + sink := &recordSink{created: map[string]*filer_pb.Entry{}} + if _, err := runInitialSnapshot(lis.Addr().String(), filerSource, "/", "/", nil, nil, nil, nil, sink, false, nil); err != nil { + t.Fatal(err) + } + + var created []string + for key := range sink.created { + created = append(created, key) + } + sort.Strings(created) + want := []string{"/data", "/data/a.txt", "/etc", "/etc/seaweedfs", "/etc/seaweedfs/filer.conf"} + if strings.Join(created, ",") != strings.Join(want, ",") { + t.Fatalf("seeded %v, want %v", created, want) + } +} diff --git a/weed/command/filer_backup_versions_test.go b/weed/command/filer_backup_versions_test.go index 1910f828ae..790bc54620 100644 --- a/weed/command/filer_backup_versions_test.go +++ b/weed/command/filer_backup_versions_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "sort" + "sync" "testing" "github.com/seaweedfs/seaweedfs/weed/filer" @@ -69,6 +70,7 @@ func (c *lookupEntrySeaweedClient) ListEntries(_ context.Context, in *filer_pb.L } type recordSink struct { + mu sync.Mutex created map[string]*filer_pb.Entry deleted []string } @@ -78,10 +80,14 @@ func (s *recordSink) Initialize(configuration util.Configuration, prefix string) return nil } func (s *recordSink) DeleteEntry(key string, isDirectory, deleteIncludeChunks bool, signatures []int32) error { + s.mu.Lock() + defer s.mu.Unlock() s.deleted = append(s.deleted, key) return nil } func (s *recordSink) CreateEntry(key string, entry *filer_pb.Entry, signatures []int32) error { + s.mu.Lock() + defer s.mu.Unlock() s.created[key] = entry return nil } diff --git a/weed/command/filer_sync.go b/weed/command/filer_sync.go index 99f078ca4d..c69f400992 100644 --- a/weed/command/filer_sync.go +++ b/weed/command/filer_sync.go @@ -25,6 +25,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/util/grace" util_http_client "github.com/seaweedfs/seaweedfs/weed/util/http/client" + "github.com/seaweedfs/seaweedfs/weed/util/version" "github.com/seaweedfs/seaweedfs/weed/util/wildcard" "google.golang.org/grpc" ) @@ -142,6 +143,9 @@ var cmdFilerSynchronize = &Command{ If restarted, the synchronization will resume from the previous checkpoints, persisted every minute. A fresh sync will start from the earliest metadata logs. + The position is also saved hourly on the source filer under /etc/seaweedfs/filer_sync, so fs.log.purge + there keeps the logs the sync still needs, until the sync has been stopped for 7 days. That copy also + describes the sync (paths, target, host, progress) for display; the checkpoint on the target stays authoritative. `, } @@ -420,6 +424,34 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi processor := NewMetadataProcessor(processEventFn, concurrency, sourceFilerOffsetTsNs) processor.SetMetrics(sourceFiler.String(), targetFiler.String(), clientName, sourcePath) + cursorName := syncCursorName(targetFilerSignature, signaturePrefix) + var storedOffsetTsNs, firstSeenTsNs atomic.Int64 + storedOffsetTsNs.Store(sourceFilerOffsetTsNs) + host, _ := os.Hostname() + cursor := filer.SyncCursor{ + SourceFiler: string(sourceFiler), + SourcePath: sourcePath, + ExcludePaths: sourceExcludePaths, + TargetFiler: string(targetFiler), + TargetPath: targetPath, + TargetSignature: targetFilerSignature, + Host: host, + Version: strings.TrimSpace(version.Version()), + SyncStartedNs: time.Now().UnixNano(), + } + stopCursorSaves := make(chan struct{}) + defer close(stopCursorSaves) + firstSeen := make(chan struct{}) + cursorTicker := time.NewTicker(time.Minute) + defer cursorTicker.Stop() + go keepSyncCursor(stopCursorSaves, firstSeen, cursorTicker.C, &storedOffsetTsNs, &firstSeenTsNs, func(tsNs int64, checkpointed bool) error { + cursor.TsNs = tsNs + cursor.Checkpointed = checkpointed + cursor.ProcessedTsNs = processor.processedTsWatermark.Load() + cursor.OldestFailedTsNs = processor.OldestFailedTsNs() + return saveSyncCursor(sourceGrpcDialOption, sourceFiler, sourceTokenSource, cursorName, cursor) + }) + // update sync state for graceful shutdown checkpoint saving if statePtr != nil { statePtr.Store(&syncState{ @@ -466,6 +498,9 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi var lastLogTsNs = time.Now().UnixNano() var lastProgressedTsNs int64 processEventFnWithOffset := pb.AddOffsetFunc(func(resp *filer_pb.SubscribeMetadataResponse) error { + if resp.TsNs > 0 && firstSeenTsNs.CompareAndSwap(0, resp.TsNs) { + close(firstSeen) + } processor.AddSyncJob(resp) return nil }, 3*time.Second, func(counter int64, lastTsNs int64) error { @@ -491,7 +526,12 @@ func doSubscribeFilerMetaChanges(clientId int32, clientEpoch int32, sourceGrpcDi lastProgressedTsNs = offsetTsNs // collect synchronous offset statsCollect.FilerSyncOffsetGauge.WithLabelValues(sourceFiler.String(), targetFiler.String(), clientName, sourcePath).Set(float64(offsetTsNs)) - return setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNsFor(processor)) + resumeTsNs := resumeTsNsFor(processor) + if err := setOffset(targetGrpcDialOption, targetFiler, sinkTokenSource, signaturePrefix, sourceFilerSignature, resumeTsNs); err != nil { + return err + } + storedOffsetTsNs.Store(resumeTsNs) + return nil }) prefix := sourcePath @@ -727,8 +767,8 @@ func genProcessFunction(sourcePath string, targetPath string, excludePaths []str // Compute per-side exclusion so that rename events crossing an // exclude boundary are handled as delete + create rather than // being entirely skipped. - oldExcluded := oldDirExcluded || isEntryExcluded(resp.Directory, message.OldEntry, reExcludeFileName, excludeFileNames, excludePathPatterns) - newExcluded := newDirExcluded || isEntryExcluded(targetDir, message.NewEntry, reExcludeFileName, excludeFileNames, excludePathPatterns) + oldExcluded := oldDirExcluded || isSyncCursor(sourceOldKey) || isEntryExcluded(resp.Directory, message.OldEntry, reExcludeFileName, excludeFileNames, excludePathPatterns) + newExcluded := newDirExcluded || isSyncCursor(sourceNewKey) || isEntryExcluded(targetDir, message.NewEntry, reExcludeFileName, excludeFileNames, excludePathPatterns) if oldExcluded && newExcluded { return nil @@ -897,6 +937,10 @@ func destKey(dataSink sink.ReplicationSink, targetPath, sourcePath string, sourc return util.Join(targetPath, dateKey, relative) } +func isSyncCursor(key util.FullPath) bool { + return key != "" && util.IsEqualOrUnder(string(key), filer.SyncCursorDir) +} + // isEntryExcluded checks whether a single side (old or new) of an event is excluded // by the deprecated filename regexp, the wildcard file-name matchers, or the // wildcard path-pattern matchers. diff --git a/weed/command/filer_sync_cursor.go b/weed/command/filer_sync_cursor.go new file mode 100644 index 0000000000..3931985b6d --- /dev/null +++ b/weed/command/filer_sync_cursor.go @@ -0,0 +1,73 @@ +package command + +import ( + "context" + "encoding/json" + "fmt" + "sync/atomic" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" +) + +const syncCursorSaveInterval = time.Hour + +func syncCursorName(targetFilerSignature int32, signaturePrefix string) string { + return fmt.Sprintf("%08x-%016x.json", uint32(targetFilerSignature), uint64(util.HashStringToLong(signaturePrefix))) +} + +// saveSyncCursor keeps the sync position on the source filer as a replay +// cursor, so a metadata log purge there keeps the logs the sync has yet to read. +func saveSyncCursor(sourceGrpcDialOption grpc.DialOption, sourceFiler pb.ServerAddress, sourceTokenSource security.FilerTokenSource, name string, cursor filer.SyncCursor) error { + if cursor.TsNs <= 0 { + return nil + } + cursor.SavedNs = time.Now().UnixNano() + content, err := json.Marshal(cursor) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err = pb.WithGrpcFilerClient(false, 0, sourceFiler, sourceGrpcDialOption, sourceTokenSource, func(client filer_pb.SeaweedFilerClient) error { + return filer.SaveInsideFiler(ctx, client, filer.SyncCursorDir, name, content) + }) + if err != nil { + glog.V(1).Infof("save sync position on %s: %v", sourceFiler, err) + } + return err +} + +// keepSyncCursor saves the cursor once the sync has a position, retries a +// failed save on the next tick, and then rewrites it hourly even when the +// position is stuck, so the purge keeps honoring a running sync and lets a +// stopped one expire. A fresh sync has no checkpoint until its oldest event +// finishes, and a restart replays everything it has received. +func keepSyncCursor(stop, firstSeen <-chan struct{}, tick <-chan time.Time, storedOffsetTsNs, firstSeenTsNs *atomic.Int64, save func(tsNs int64, checkpointed bool) error) { + var lastSaveTime time.Time + for { + tsNs := storedOffsetTsNs.Load() + checkpointed := tsNs > 0 + if !checkpointed { + tsNs = firstSeenTsNs.Load() - 1 + } + if tsNs > 0 && (lastSaveTime.IsZero() || time.Since(lastSaveTime) >= syncCursorSaveInterval) { + if save(tsNs, checkpointed) == nil { + lastSaveTime = time.Now() + } + } + select { + case <-stop: + return + case <-firstSeen: + firstSeen = nil + case <-tick: + } + } +} diff --git a/weed/command/filer_sync_cursor_test.go b/weed/command/filer_sync_cursor_test.go new file mode 100644 index 0000000000..d54d3130d4 --- /dev/null +++ b/weed/command/filer_sync_cursor_test.go @@ -0,0 +1,88 @@ +package command + +import ( + "errors" + "sync/atomic" + "testing" + "time" +) + +type cursorSave struct { + tsNs int64 + checkpointed bool +} + +func startKeepSyncCursor(t *testing.T, stored int64, failures int) (firstSeenTsNs *atomic.Int64, firstSeen chan struct{}, tick chan time.Time, saves chan cursorSave) { + var storedOffsetTsNs atomic.Int64 + storedOffsetTsNs.Store(stored) + firstSeenTsNs = &atomic.Int64{} + firstSeen = make(chan struct{}) + tick = make(chan time.Time) + saves = make(chan cursorSave, 16) + stop := make(chan struct{}) + done := make(chan struct{}) + t.Cleanup(func() { + close(stop) + <-done + }) + go func() { + defer close(done) + keepSyncCursor(stop, firstSeen, tick, &storedOffsetTsNs, firstSeenTsNs, func(tsNs int64, checkpointed bool) error { + saves <- cursorSave{tsNs, checkpointed} + if failures > 0 { + failures-- + return errors.New("filer unavailable") + } + return nil + }) + }() + return +} + +func expectCursorSave(t *testing.T, saves chan cursorSave, want cursorSave) { + t.Helper() + select { + case got := <-saves: + if got != want { + t.Fatalf("saved %+v, want %+v", got, want) + } + case <-time.After(5 * time.Second): + t.Fatalf("no cursor save, want %+v", want) + } +} + +func expectNoCursorSave(t *testing.T, saves chan cursorSave) { + t.Helper() + select { + case got := <-saves: + t.Fatalf("unexpected cursor save %+v", got) + default: + } +} + +func TestKeepSyncCursorSavesOnFirstEvent(t *testing.T) { + firstSeenTsNs, firstSeen, tick, saves := startKeepSyncCursor(t, 0, 0) + tick <- time.Now() + expectNoCursorSave(t, saves) + + firstSeenTsNs.Store(100) + close(firstSeen) + expectCursorSave(t, saves, cursorSave{99, false}) + + tick <- time.Now() + tick <- time.Now() + expectNoCursorSave(t, saves) +} + +func TestKeepSyncCursorRetriesFailedSave(t *testing.T) { + _, _, tick, saves := startKeepSyncCursor(t, 500, 2) + expectCursorSave(t, saves, cursorSave{500, true}) + tick <- time.Now() + expectCursorSave(t, saves, cursorSave{500, true}) + tick <- time.Now() + expectCursorSave(t, saves, cursorSave{500, true}) + + tick <- time.Now() + tick <- time.Now() + expectNoCursorSave(t, saves) +} diff --git a/weed/command/filer_sync_log_gap.go b/weed/command/filer_sync_log_gap.go index e59c786022..383fbac192 100644 --- a/weed/command/filer_sync_log_gap.go +++ b/weed/command/filer_sync_log_gap.go @@ -83,7 +83,7 @@ func entryLastChange(entry *filer_pb.Entry) time.Time { func isNotSynced(p string, excludePaths []string) bool { return util.IsEqualOrUnder(p, filer.SystemLogDir) || strings.HasPrefix(filer.SystemLogDir, p+"/") || - isMultipartUploadDir(p+"/") || matchesExcludePath(p, excludePaths) + isSyncCursor(util.FullPath(p)) || isMultipartUploadDir(p+"/") || matchesExcludePath(p, excludePaths) } // metadataLogGap describes what a sync starting at offsetTsNs cannot replay diff --git a/weed/command/filer_sync_log_gap_test.go b/weed/command/filer_sync_log_gap_test.go index bfcc50c416..62f41db73d 100644 --- a/weed/command/filer_sync_log_gap_test.go +++ b/weed/command/filer_sync_log_gap_test.go @@ -45,6 +45,7 @@ func TestMetadataLogGap(t *testing.T) { {name: "fresh sync, entry without commit time", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("historical", 0, before)}}, sourcePath: "/buckets", want: "/buckets/historical"}, {name: "fresh sync of the root skips the log directory", dirs: map[string][]*filer_pb.Entry{"/": {child("topics", before.UnixNano(), before)}}, sourcePath: "/"}, {name: "fresh sync skips excluded entries", dirs: map[string][]*filer_pb.Entry{"/buckets": {child("archive", before.UnixNano(), before), child("recent", after.UnixNano(), after)}}, sourcePath: "/buckets", exclude: []string{"/buckets/archive"}}, + {name: "fresh sync skips the sync cursors", dirs: map[string][]*filer_pb.Entry{"/etc/seaweedfs": {child("filer_sync", before.UnixNano(), before)}}, sourcePath: "/etc/seaweedfs"}, {name: "fresh sync skips multipart uploads", dirs: map[string][]*filer_pb.Entry{"/buckets/b": {child(".uploads", before.UnixNano(), before)}}, sourcePath: "/buckets/b"}, } for _, tt := range tests { diff --git a/weed/command/filer_sync_process_test.go b/weed/command/filer_sync_process_test.go index 3e81e0d914..31945eac7a 100644 --- a/weed/command/filer_sync_process_test.go +++ b/weed/command/filer_sync_process_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/replication/sink" "github.com/seaweedfs/seaweedfs/weed/replication/sink/localsink" @@ -378,3 +379,58 @@ func TestGenProcessFunctionLocalSinkStaysInsideTarget(t *testing.T) { t.Fatalf("local sink wrote outside %s: %v", target, err) } } + +func TestGenProcessFunctionSkipsSyncCursors(t *testing.T) { + dataSink := &recordingSyncSink{} + processFn := genProcessFunction("/", "/", nil, nil, nil, nil, dataSink, true, false) + for _, key := range []util.FullPath{util.FullPath(filer.SyncCursorDir), util.FullPath(filer.SyncCursorDir).Child("cursor.json"), util.FullPath(filer.DirectoryEtcSeaweedFS).Child("cursor.json")} { + dir, name := key.DirAndName() + err := processFn(&filer_pb.SubscribeMetadataResponse{ + Directory: dir, + EventNotification: &filer_pb.EventNotification{ + NewEntry: &filer_pb.Entry{Name: name}, + NewParentPath: dir, + }, + }) + if err != nil { + t.Fatalf("processFn %s: %v", key, err) + } + } + if want := []string{filer.DirectoryEtcSeaweedFS + "/cursor.json"}; !equalSyncStrings(dataSink.createKeys, want) { + t.Fatalf("create keys = %v, want %v", dataSink.createKeys, want) + } +} + +func TestGenProcessFunctionSyncCursorRenames(t *testing.T) { + event := func(oldDir, oldName, newDir, newName string) *filer_pb.SubscribeMetadataResponse { + resp := &filer_pb.SubscribeMetadataResponse{Directory: oldDir, EventNotification: &filer_pb.EventNotification{NewParentPath: newDir}} + if oldName != "" { + resp.EventNotification.OldEntry = &filer_pb.Entry{Name: oldName} + } + if newName != "" { + resp.EventNotification.NewEntry = &filer_pb.Entry{Name: newName} + } + return resp + } + tests := []struct { + name string + resp *filer_pb.SubscribeMetadataResponse + wantCreate, wantDelete []string + }{ + {name: "into the cursor directory", resp: event("/data", "file", filer.SyncCursorDir, "file"), wantDelete: []string{"/data/file"}}, + {name: "out of the cursor directory", resp: event(filer.SyncCursorDir, "file", "/data", "file"), wantCreate: []string{"/data/file"}}, + {name: "inside the cursor directory", resp: event(filer.SyncCursorDir, "a.json", filer.SyncCursorDir, "b.json")}, + {name: "cursor deleted", resp: event(filer.SyncCursorDir, "a.json", "", "")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dataSink := &recordingSyncSink{} + if err := genProcessFunction("/", "/", nil, nil, nil, nil, dataSink, true, false)(tt.resp); err != nil { + t.Fatalf("processFn: %v", err) + } + if !equalSyncStrings(dataSink.createKeys, tt.wantCreate) || !equalSyncStrings(dataSink.deleteKeys, tt.wantDelete) || len(dataSink.updateKeys) > 0 { + t.Fatalf("create %v delete %v update %v, want create %v delete %v", dataSink.createKeys, dataSink.deleteKeys, dataSink.updateKeys, tt.wantCreate, tt.wantDelete) + } + }) + } +} diff --git a/weed/filer/filer_conf.go b/weed/filer/filer_conf.go index edc82c433a..1974ca62f1 100644 --- a/weed/filer/filer_conf.go +++ b/weed/filer/filer_conf.go @@ -26,6 +26,7 @@ const ( DirectoryEtcRoot = "/etc/" DirectoryEtcSeaweedFS = "/etc/seaweedfs" DirectoryEtcRemote = "/etc/remote" + SyncCursorDir = DirectoryEtcSeaweedFS + "/filer_sync" FilerConfName = "filer.conf" IamConfigDirectory = "/etc/iam" IamIdentityFile = "identity.json" diff --git a/weed/filer/filer_sync_cursor.go b/weed/filer/filer_sync_cursor.go new file mode 100644 index 0000000000..6a3e6cee8e --- /dev/null +++ b/weed/filer/filer_sync_cursor.go @@ -0,0 +1,24 @@ +package filer + +// SyncCursor is what a filer.sync keeps on its source filer under +// SyncCursorDir. TsNs holds back the metadata log purge there; the other +// fields describe the sync for display. The checkpoint stored on the target +// filer stays the authoritative sync position. +type SyncCursor struct { + TsNs int64 `json:"ts_ns"` + SavedNs int64 `json:"saved_ns"` + // Checkpointed is false while a fresh sync has no target checkpoint yet + // and TsNs is held just before the first event it received. + Checkpointed bool `json:"checkpointed"` + ProcessedTsNs int64 `json:"processed_ts_ns,omitempty"` + OldestFailedTsNs int64 `json:"oldest_failed_ts_ns,omitempty"` + SourceFiler string `json:"source_filer"` + SourcePath string `json:"source_path"` + ExcludePaths []string `json:"exclude_paths,omitempty"` + TargetFiler string `json:"target_filer"` + TargetPath string `json:"target_path"` + TargetSignature int32 `json:"target_signature"` + Host string `json:"host,omitempty"` + Version string `json:"version,omitempty"` + SyncStartedNs int64 `json:"sync_started_ns"` +} diff --git a/weed/shell/command_fs_log.go b/weed/shell/command_fs_log.go index d62f2042bc..c0b7eefee3 100644 --- a/weed/shell/command_fs_log.go +++ b/weed/shell/command_fs_log.go @@ -44,8 +44,9 @@ func (c *commandFsLogPurge) Help() string { registered with the master by default. Use -filer to restrict it to a subset of the cluster. - Logs still needed by a filer.conf TTL, an S3 lifecycle rule or a running - replay job are kept even when older than -daysAgo, and a filer whose + Logs still needed by a filer.conf TTL, an S3 lifecycle rule, a running + replay job or a filer.sync reading from the filer (until it has been + stopped for 7 days) are kept even when older than -daysAgo, and a filer whose needs cannot be read is not purged. Pass -force to purge them anyway. ` } diff --git a/weed/worker/tasks/meta_log_purge/floor.go b/weed/worker/tasks/meta_log_purge/floor.go index 67f95cd242..185c8827d1 100644 --- a/weed/worker/tasks/meta_log_purge/floor.go +++ b/weed/worker/tasks/meta_log_purge/floor.go @@ -33,6 +33,7 @@ const ( var cursorDirs = []string{ filer.DirectoryEtcSeaweedFS + "/filer_ttl", dailyrun.CursorDir, + filer.SyncCursorDir, } // RetentionFloor reports how long the metadata log of the store behind client diff --git a/weed/worker/tasks/meta_log_purge/floor_test.go b/weed/worker/tasks/meta_log_purge/floor_test.go index 291c20a068..33ad59cd83 100644 --- a/weed/worker/tasks/meta_log_purge/floor_test.go +++ b/weed/worker/tasks/meta_log_purge/floor_test.go @@ -2,6 +2,7 @@ package meta_log_purge import ( "context" + "encoding/json" "errors" "fmt" "math" @@ -119,6 +120,31 @@ func TestOldestLiveCursorIgnoresStaleFiles(t *testing.T) { }) } +func TestOldestLiveCursorCountsSyncPositions(t *testing.T) { + runNow := time.Date(2026, 3, 20, 0, 0, 0, 0, time.UTC) + f := newFakeFiler(t) + synced := time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC).UnixNano() + cursor, err := json.Marshal(filer.SyncCursor{ + TsNs: synced, + SavedNs: runNow.Add(-time.Hour).UnixNano(), + Checkpointed: true, + ProcessedTsNs: synced + int64(time.Hour), + SourcePath: "/buckets", + SyncStartedNs: runNow.Add(-2 * time.Hour).UnixNano(), + }) + if err != nil { + t.Fatal(err) + } + f.put(filer.SyncCursorDir, "0000000a-0000000000000001.json", runNow.Add(-time.Hour), string(cursor)) + f.put(filer.SyncCursorDir, "0000000b-0000000000000001.json", runNow.Add(-8*day), `{"ts_ns":1}`) + f.withClient(t, func(client filer_pb.SeaweedFilerClient) { + got, err := oldestLiveCursorNs(context.Background(), client, runNow, 30*day) + if err != nil || got != synced { + t.Fatalf("oldestLiveCursorNs = %d, %v, want %d", got, err, synced) + } + }) +} + func shardCursor(id int, tsNs int64) string { zero := `"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="` return fmt.Sprintf(`{"version":1,"shard_id":%d,"ts_ns":%d,"rule_set_hash":%s,"promoted_hash":%s}`, id, tsNs, zero, zero) diff --git a/weed/worker/tasks/meta_log_purge/handler.go b/weed/worker/tasks/meta_log_purge/handler.go index f2b1c91957..c4d22efc9c 100644 --- a/weed/worker/tasks/meta_log_purge/handler.go +++ b/weed/worker/tasks/meta_log_purge/handler.go @@ -79,7 +79,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor { { SectionId: "retention", Title: "Retention", - Description: "The log is kept longer when a filer.conf TTL, an S3 lifecycle rule or a replay job that has fallen behind needs it.", + Description: "The log is kept longer when a filer.conf TTL, an S3 lifecycle rule, a replay job or a filer.sync that has fallen behind needs it. A replay or sync position not saved for 7 days no longer holds the log, even if its job is still running.", Fields: []*plugin_pb.ConfigField{ { Name: minRetentionDaysKey,