package dir_usage import ( "context" "fmt" "math" "strings" "time" "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/security" "google.golang.org/grpc" ) const ( jobType = "dir_usage" filerAddressParam = "filer_address" defaultDetectionMinutes = 60 ) func init() { pluginworker.RegisterHandler(pluginworker.HandlerFactory{ JobType: jobType, Category: pluginworker.CategoryDefault, Aliases: []string{"dir-usage", "dir.usage"}, Build: func(opts pluginworker.HandlerBuildOptions) (pluginworker.JobHandler, error) { return NewHandler(opts.GrpcDialOption), nil }, }) } // Handler keeps the totals of each bucket, and of the directories in it that // hold at least 1% of it, from one walk and the metadata events after it, so // reading a directory's size is no walk. 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: "Directory Usage", Description: "Keep the size of each bucket and of its largest directories from the filer metadata events.", Weight: 10, } } func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor { return &plugin_pb.JobTypeDescriptor{ JobType: jobType, DisplayName: "Directory Usage", Description: "Keep the totals of each bucket, and of the directories in it holding at least 1% of it, once per filer store. A bucket is walked once; after that each run replays the metadata events since the last.", Icon: "bi bi-pie-chart", DescriptorVersion: 1, AdminRuntimeDefaults: &plugin_pb.AdminRuntimeDefaults{ Enabled: false, DetectionIntervalMinutes: defaultDetectionMinutes, DetectionTimeoutSeconds: 60, // walking a large bucket the first time takes as long as fs.du ExecutionTimeoutSeconds: math.MaxInt32, JobTypeMaxRuntimeSeconds: math.MaxInt32, }, WorkerDefaultValues: map[string]*plugin_pb.ConfigValue{}, } } 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 dir usage 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}) } var proposals []*plugin_pb.JobProposal for _, address := range pluginworker.OneFilerPerStore(ctx, filers, h.grpcDialOption, sender) { // Two runs on one store would overwrite each other's records and // cursor, whichever filer each started from. var signature int32 err := pb.WithGrpcFilerClient(false, 0, address, h.grpcDialOption, security.FilerAdminToken, func(client filer_pb.SeaweedFilerClient) error { conf, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) signature = conf.GetSignature() return err }) if err != nil { _ = sender.SendActivity(pluginworker.BuildDetectorActivity("filer_unreachable", fmt.Sprintf("filer %s: %v", address, err), nil)) continue } proposals = append(proposals, &plugin_pb.JobProposal{ JobType: jobType, ProposalId: fmt.Sprintf("dir-usage-%s-%d", address, time.Now().UnixNano()), DedupeKey: fmt.Sprintf("%s:%d", jobType, signature), Priority: plugin_pb.JobPriority_JOB_PRIORITY_LOW, Summary: fmt.Sprintf("Bring the directory usage of the store of filer %s up to date", 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: true, TotalProposals: int32(len(proposals)), }) } 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 dir usage 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} progress := func(message string) { _ = sender.SendProgress(&plugin_pb.JobProgressUpdate{ JobId: request.Job.JobId, JobType: jobType, State: plugin_pb.JobState_JOB_STATE_RUNNING, Stage: "running", Message: fmt.Sprintf("filer %s: %s", address, message), }) } stats := &runStats{} err := run(ctx, client, time.Now(), stats, progress) summary := fmt.Sprintf("filer %s: %d events replayed, %d records written, %d removed, %d seeded", address, stats.events, stats.written, stats.removed, stats.seeded) if len(stats.failed) > 0 { summary += fmt.Sprintf(", %d not seeded: %s", len(stats.failed), strings.Join(stats.failed, "; ")) } 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{ "events": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.events}}, "written": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.written}}, "removed": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.removed}}, "seeded": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: stats.seeded}}, }, }, } if err != nil { completed.ErrorMessage = err.Error() } return sender.SendCompleted(completed) } var _ pluginworker.JobHandler = (*Handler)(nil)