Files
seaweedfs/weed/worker/tasks/meta_log_purge/handler.go
T
Chris LuandClaude Opus 5.5 c637d60dfc 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* metadata log purge: keep the logs a filer.sync still needs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

* filer.backup: do not seed the source's sync cursors in the initial snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* metadata log purge: say that a position not saved for 7 days stops holding the log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.backup test: lock the recording sink for concurrent snapshot workers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* filer.sync: leave the sync cursors out of the metadata log gap check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:09:23 -08:00

261 lines
9.7 KiB
Go

package meta_log_purge
import (
"context"
"errors"
"fmt"
"math"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/plugin_pb"
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
"github.com/seaweedfs/seaweedfs/weed/shell"
"github.com/seaweedfs/seaweedfs/weed/wdclient"
"google.golang.org/grpc"
)
const (
jobType = "meta_log_purge"
filerAddressParam = "filer_address"
minRetentionDaysKey = "min_retention_days"
defaultMinRetentionDays = 7
maxMinRetentionDays = 100 * 365
defaultDetectionMinutes = 24 * 60
)
func init() {
shell.LogPurgeKeepFrom = func(ctx context.Context, client filer_pb.FilerClient, lookup wdclient.HasLookupFileIdFunction, runNow time.Time) (time.Time, string, error) {
return SafeKeepFrom(ctx, client, lookup, 0, runNow)
}
pluginworker.RegisterHandler(pluginworker.HandlerFactory{
JobType: jobType,
Category: pluginworker.CategoryDefault,
Aliases: []string{"meta-log-purge", "meta.log.purge"},
Build: func(opts pluginworker.HandlerBuildOptions) (pluginworker.JobHandler, error) {
return NewHandler(opts.GrpcDialOption), nil
},
})
}
// Handler deletes the filer metadata log days that no TTL, lifecycle rule,
// registered floor or running replay job still needs.
type Handler struct {
grpcDialOption grpc.DialOption
}
func NewHandler(grpcDialOption grpc.DialOption) *Handler {
return &Handler{grpcDialOption: grpcDialOption}
}
func (h *Handler) Capability() *plugin_pb.JobTypeCapability {
return &plugin_pb.JobTypeCapability{
JobType: jobType,
CanDetect: true,
CanExecute: true,
MaxDetectionConcurrency: 1,
MaxExecutionConcurrency: 1,
DisplayName: "Metadata Log Purge",
Description: "Delete filer metadata log days older than every TTL, lifecycle rule and replay cursor needs.",
Weight: 10,
}
}
func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
return &plugin_pb.JobTypeDescriptor{
JobType: jobType,
DisplayName: "Metadata Log Purge",
Description: "Delete old filer metadata log days, once per filer store, keeping more than the longest TTL.",
Icon: "bi bi-journal-x",
DescriptorVersion: 1,
AdminConfigForm: &plugin_pb.ConfigForm{
FormId: "meta-log-purge-admin",
Title: "Metadata Log Purge",
Description: "How long the filer metadata log is kept at least.",
Sections: []*plugin_pb.ConfigSection{
{
SectionId: "retention",
Title: "Retention",
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,
Label: "Minimum Retention (days)",
Description: "Log days younger than this are never deleted.",
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_INT64,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_NUMBER,
MinValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 1}},
MaxValue: &plugin_pb.ConfigValue{Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: maxMinRetentionDays}},
},
},
},
},
DefaultValues: map[string]*plugin_pb.ConfigValue{
minRetentionDaysKey: {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMinRetentionDays}},
},
},
AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{
Enabled: true,
DetectionIntervalMinutes: defaultDetectionMinutes,
DetectionTimeoutSeconds: 60,
ExecutionTimeoutSeconds: 3600,
JobTypeMaxRuntimeSeconds: math.MaxInt32,
},
WorkerDefaultValues: map[string]*plugin_pb.ConfigValue{},
}
}
func minRetention(values map[string]*plugin_pb.ConfigValue) time.Duration {
days := pluginworker.ReadInt64Config(values, minRetentionDaysKey, defaultMinRetentionDays)
if days < 1 {
days = defaultMinRetentionDays
}
return time.Duration(min(days, maxMinRetentionDays)) * day
}
func (h *Handler) Detect(ctx context.Context, request *plugin_pb.RunDetectionRequest, sender pluginworker.DetectionSender) error {
if request == nil || sender == nil {
return fmt.Errorf("detect: nil request or sender")
}
if request.JobType != "" && request.JobType != jobType {
return fmt.Errorf("job type %q is not handled by meta log purge handler", request.JobType)
}
filers := pluginworker.ClusterFilerAddresses(request.GetClusterContext())
if len(filers) == 0 {
_ = sender.SendActivity(pluginworker.BuildDetectorActivity("skipped", "no filer addresses in cluster context", nil))
return sender.SendComplete(&plugin_pb.DetectionComplete{JobType: jobType, Success: true})
}
from := time.Now().UTC().Add(-minRetention(request.GetAdminConfigValues())).Truncate(day)
var proposals []*plugin_pb.JobProposal
var readErrors []string
for _, address := range pluginworker.OneFilerPerStore(ctx, filers, h.grpcDialOption, sender) {
client := &pluginworker.AdminFilerClient{Address: address, GrpcDialOption: h.grpcDialOption}
var days []string
err := client.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
names, err := logDayNames(ctx, c)
days = purgeableDays(names, from)
return err
})
if err != nil {
readErrors = append(readErrors, fmt.Sprintf("filer %s: %v", address, err))
continue
}
if len(days) == 0 {
continue
}
proposals = append(proposals, &plugin_pb.JobProposal{
JobType: jobType,
ProposalId: fmt.Sprintf("meta-log-purge-%s-%d", address, time.Now().UnixNano()),
DedupeKey: fmt.Sprintf("%s:%s", jobType, address),
Priority: plugin_pb.JobPriority_JOB_PRIORITY_LOW,
Summary: fmt.Sprintf("Purge up to %d metadata log day(s) on the store of filer %s", len(days), address),
Parameters: map[string]*plugin_pb.ConfigValue{
filerAddressParam: {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: string(address)}},
},
})
}
if len(proposals) > 0 {
if err := sender.SendProposals(&plugin_pb.DetectionProposals{JobType: jobType, Proposals: proposals}); err != nil {
return err
}
}
return sender.SendComplete(&plugin_pb.DetectionComplete{
JobType: jobType,
Success: len(readErrors) == 0,
ErrorMessage: strings.Join(readErrors, "; "),
TotalProposals: int32(len(proposals)),
})
}
func logDayNames(ctx context.Context, client filer_pb.SeaweedFilerClient) ([]string, error) {
var names []string
err := filer_pb.SeaweedList(ctx, client, filer.SystemLogDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if entry.IsDirectory {
names = append(names, entry.Name)
}
return nil
}, "", false, math.MaxInt32)
if errors.Is(err, filer_pb.ErrNotFound) {
err = nil
}
return names, err
}
type purgeResult struct {
keepFrom time.Time
reason string
purged []string
}
// purge deletes the store's log days that end before the floor. Every input
// to the floor is read before the first delete, so a failing one purges nothing.
func purge(ctx context.Context, client *pluginworker.AdminFilerClient, minRetention time.Duration, runNow time.Time) (purgeResult, error) {
var result purgeResult
var err error
result.keepFrom, result.reason, err = SafeKeepFrom(ctx, client, client, minRetention, runNow)
if err != nil {
return result, err
}
var names []string
err = client.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error {
names, err = logDayNames(ctx, c)
return err
})
if err != nil {
return result, err
}
for _, name := range purgeableDays(names, result.keepFrom) {
if err := filer_pb.Remove(ctx, client, filer.SystemLogDir, name, true, true, true, false, nil); err != nil {
return result, fmt.Errorf("delete %s/%s: %w", filer.SystemLogDir, name, err)
}
result.purged = append(result.purged, name)
}
return result, nil
}
func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequest, sender pluginworker.ExecutionSender) error {
if request == nil || request.Job == nil || sender == nil {
return fmt.Errorf("execute: nil request/job/sender")
}
if request.Job.JobType != "" && request.Job.JobType != jobType {
return fmt.Errorf("job type %q is not handled by meta log purge handler", request.Job.JobType)
}
address := pluginworker.ReadStringConfig(request.Job.Parameters, filerAddressParam, "")
if address == "" {
return fmt.Errorf("execute: missing %s in job parameters", filerAddressParam)
}
client := &pluginworker.AdminFilerClient{Address: pb.ServerAddress(address), GrpcDialOption: h.grpcDialOption}
_ = sender.SendProgress(&plugin_pb.JobProgressUpdate{
JobId: request.Job.JobId, JobType: jobType,
State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "purging",
Message: fmt.Sprintf("filer %s", address),
})
result, err := purge(ctx, client, minRetention(request.GetAdminConfigValues()), time.Now())
summary := fmt.Sprintf("filer %s: purged %d log day(s)", address, len(result.purged))
if !result.keepFrom.IsZero() {
summary += fmt.Sprintf(", keeping from %s (%s)", result.keepFrom.Format(logDayLayout), result.reason)
}
completed := &plugin_pb.JobCompleted{
JobId: request.Job.JobId,
JobType: jobType,
Success: err == nil,
Result: &plugin_pb.JobResult{
Summary: summary,
OutputValues: map[string]*plugin_pb.ConfigValue{
"purged_days": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: int64(len(result.purged))}},
},
},
}
if err != nil {
completed.ErrorMessage = err.Error()
}
return sender.SendCompleted(completed)
}
var _ pluginworker.JobHandler = (*Handler)(nil)