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: } } }