mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
* shell: fs.du walks with a shared treewalk.Walker The walker fs.du used moves to a new package, filer/treewalk, so that the dir_usage job proposed in #13257 walks the same way. fs.du adds up what its visitor is told; what it prints and how it fails stay the same. A page now also carries the snapshot the filer listed it at, and when it was listed. treewalktest serves a tree from memory and logs an event for each change, for the tests of walks and of what follows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * filer/treewalk: Seed adds up a walk and the events logged while it runs Seed walks a directory tree while it follows the metadata log below it, and reconciles the two, so that the result is the tree as of one log position: - an event at or before the snapshot of the page that lists its name shows in that page, and so does an event in a directory not listed yet; - an event after the page's snapshot replaces what the page counted for the name, since the page may or may not show it; - once a page is older than a margin, a minute by default since a rename logs its events after the move, an event changes the entry from its old to its new entry. A directory missing from its parent's page counts from its events if it was created after that page's snapshot, and not at all otherwise. This is how the mount's metadata cache builds a directory from a listing and the events around it, with a replace per name in place of the cache's overwrite, which a running total cannot do. Follow reads the events of a range of the log. The lookup of where the log starts moves here from filer_ttl as LogStartTsNs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * worker: dir_usage keeps the sizes of buckets and their large directories A plugin worker job, off by default, that keeps what fs.du adds up of each bucket and each top-level directory outside the buckets folder, and of each directory in it holding at least 1% of its bytes, down to 10 levels. Directories at one depth do not overlap, so a bucket has at most 1,000 such records, whatever the shape of its tree. They are one JSON file per bucket under /etc/seaweedfs/dir_usage/<store signature>/. The buckets without a record are seeded in one treewalk.Seed walk of the buckets folder, and the top-level directories in one of /. After that, each run replays the events since the last run, up to a minute before now, applies each to the directories with a record above the entry, writes the files that changed, and saves a cursor that meta_log_purge keeps the log for. A record the log no longer reaches is seeded again, and so is every record when no log is kept and the cursor is older than the purge honors. A tracked directory that moves keeps its record, which the events of the entries it took along fill again. One deleted with totals left had entries that went without events, as when a store drops a whole bucket, and the rest comes off the directories above it. A bucket created since the last run is seeded by the next. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * shell: fs.du -report prints what the dir_usage job keeps fs.du -report [-depth=N] path prints the totals the dir_usage job keeps of path and of the directories below it with a record, down to N levels, the way fs.du prints a walk, and how old they are: as old as the job's cursor for a record the last replay did not change. Nothing is walked. For / and the buckets folder, the buckets and top-level directories add up. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * treewalk, dir_usage: wait for the filer's own position, stop waits on cancel A subscription with an end stops once it has read everything the filer has logged, without waiting for the end to come. So the seed's catch-up now waits until the filer's listing snapshot reaches the seed's end, and a replay ends at the snapshot the filer gives when it starts, both on the filer's clock rather than this process's. - A walk waiting for its pages to free names stops when its context ends. - A seed reports the listing that failed, not the cancellation it caused. - A walk canceled while the last page's subdirectories start fails. - LogStartTsNs passes over a day a purge that stopped midway left empty. - A bucket dropped while the buckets folder is seeded gets no record; the next run seeds it if it is made again. - Detection keys a store's job by its signature, so no two runs share a store whichever filer each starts from. - The buckets folder is taken without a trailing slash. - fs.du -report names the buckets and top-level directories it leaves out for want of a record, and no longer says why a directory has no total of its own. - treewalktest.Filer replays a quiet drop with what was below it, and can refuse a listing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * treewalk: list a page again after a transient failure A seed walks every bucket without a record in one walk, which on a large store runs for hours. One page that failed because the filer restarted or a connection dropped failed the whole walk, and the next run started it over. A page that fails with a transient error is now asked for again, with backoff, for up to a minute. Other failures still end the listing at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * dir_usage: keep the other seeded records when one fails to save A save that failed after a seed returned at once, so the records of the batch not saved yet were lost, and the top-level directories were not seeded at all when it was the buckets' batch that failed. The next run walked them all again, which on a large store takes hours. A failed save is now reported and the run goes on; the next run seeds only that root. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * treewalk: measure how far the filer's clock runs ahead in a seed A page's end is on this host's clock and the events it is compared to are on the filer's, so a filer clock ahead by more than the margin expired pages before the events they show arrived, and set the seed's end before positions the filer had already logged. The seed now learns a lower bound of the filer's lead from the page snapshots and the event stamps, and adds it to page expiry and to the end. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mini: expect the dir_usage handler among the default job types Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
328 lines
10 KiB
Go
328 lines
10 KiB
Go
// Package dirusage holds what the dir_usage worker job keeps of a filer
|
|
// store: the totals of each bucket, and of the directories in it that hold at
|
|
// least MinSharePercent of it, in one file per bucket under Dir.
|
|
package dirusage
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"math"
|
|
"strings"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
const (
|
|
// Dir holds the records, in a directory per store signature, so the
|
|
// copies filer.sync makes in another cluster are never read there, and
|
|
// the cursor of each store, which meta_log_purge reads.
|
|
Dir = filer.DirectoryEtcSeaweedFS + "/dir_usage"
|
|
// Version is the version of the record format and of the rules that
|
|
// pick the directories; a record of another version is made again.
|
|
Version = 1
|
|
// MinSharePercent is the share of its bucket's bytes a directory holds
|
|
// at least to get a record of its own. Directories at one depth do not
|
|
// overlap, so a bucket has at most 100/MinSharePercent records per level.
|
|
MinSharePercent = 1
|
|
// MaxDepth is how many levels below its bucket a directory is at most to
|
|
// get a record of its own.
|
|
MaxDepth = 10
|
|
)
|
|
|
|
// Usage is what fs.du adds up for a directory, everything below it included:
|
|
// the logical size, the chunks, the files and the directories.
|
|
type Usage struct {
|
|
Bytes int64 `json:"bytes"`
|
|
Chunks int64 `json:"chunks"`
|
|
Files int64 `json:"files"`
|
|
Dirs int64 `json:"dirs"`
|
|
}
|
|
|
|
// EntryUsage is what one entry adds to the directories above it.
|
|
func EntryUsage(entry *filer_pb.Entry) Usage {
|
|
if entry == nil {
|
|
return Usage{}
|
|
}
|
|
if entry.IsDirectory {
|
|
return Usage{Dirs: 1}
|
|
}
|
|
return Usage{Bytes: int64(min(filer.FileSize(entry), math.MaxInt64)), Chunks: int64(len(entry.GetChunks())), Files: 1}
|
|
}
|
|
|
|
func (u *Usage) Add(other Usage) {
|
|
u.Bytes += other.Bytes
|
|
u.Chunks += other.Chunks
|
|
u.Files += other.Files
|
|
u.Dirs += other.Dirs
|
|
}
|
|
|
|
func (u *Usage) Sub(other Usage) {
|
|
u.Bytes -= other.Bytes
|
|
u.Chunks -= other.Chunks
|
|
u.Files -= other.Files
|
|
u.Dirs -= other.Dirs
|
|
}
|
|
|
|
func (u Usage) IsZero() bool {
|
|
return u == Usage{}
|
|
}
|
|
|
|
// Record is what the job keeps of one bucket, or of one directory directly
|
|
// under / outside the buckets folder.
|
|
type Record struct {
|
|
Version int `json:"version"`
|
|
Root string `json:"root"`
|
|
// TsNs is the log position the totals are at.
|
|
TsNs int64 `json:"ts_ns"`
|
|
// SeededNs is when the walk the totals started from ended.
|
|
SeededNs int64 `json:"seeded_ns"`
|
|
// Dirs are the totals of Root, at "", and of each directory below it
|
|
// with a record of its own, by its path relative to Root.
|
|
Dirs map[string]Usage `json:"dirs"`
|
|
}
|
|
|
|
// Relative is path relative to root, "" for root itself.
|
|
func Relative(root, path util.FullPath) string {
|
|
if path == root {
|
|
return ""
|
|
}
|
|
if root == "/" {
|
|
return strings.TrimPrefix(string(path), "/")
|
|
}
|
|
return strings.TrimPrefix(string(path), string(root)+"/")
|
|
}
|
|
|
|
// Roots tells which bucket, or top-level directory outside the buckets folder,
|
|
// a path counts toward.
|
|
type Roots struct {
|
|
Buckets util.FullPath
|
|
}
|
|
|
|
// RootsOf reads the buckets folder of the filer behind client.
|
|
func RootsOf(ctx context.Context, client filer_pb.SeaweedFilerClient) (Roots, int32, error) {
|
|
conf, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
|
|
if err != nil {
|
|
return Roots{}, 0, fmt.Errorf("filer configuration: %w", err)
|
|
}
|
|
return NewRoots(conf.GetDirBuckets()), conf.Signature, nil
|
|
}
|
|
|
|
// NewRoots takes the buckets folder as filer.toml spells it.
|
|
func NewRoots(buckets string) Roots {
|
|
if buckets = strings.TrimRight(buckets, "/"); buckets == "" {
|
|
buckets = "/buckets"
|
|
}
|
|
return Roots{Buckets: util.FullPath(buckets)}
|
|
}
|
|
|
|
// List lists the buckets and the top-level directories outside the buckets
|
|
// folder.
|
|
func (r Roots) List(ctx context.Context, client filer_pb.FilerClient) (map[util.FullPath]bool, error) {
|
|
roots := make(map[util.FullPath]bool)
|
|
for _, dir := range []util.FullPath{"/", r.Buckets} {
|
|
err := filer_pb.List(ctx, client, string(dir), "", func(entry *filer_pb.Entry, isLast bool) error {
|
|
if path := dir.Child(entry.Name); entry.IsDirectory && r.IsRoot(path) {
|
|
roots[path] = true
|
|
}
|
|
return nil
|
|
}, "", false, math.MaxInt32)
|
|
// no buckets folder yet: no buckets
|
|
if err != nil && !(dir == r.Buckets && errors.Is(err, filer_pb.ErrNotFound)) {
|
|
return nil, fmt.Errorf("list %s: %w", dir, err)
|
|
}
|
|
}
|
|
return roots, nil
|
|
}
|
|
|
|
// container is the top-level directory the buckets folder is in. Outside the
|
|
// buckets folder, nothing in it is counted.
|
|
func (r Roots) container() string {
|
|
if parts := r.Buckets.Split(); len(parts) > 0 {
|
|
return parts[0]
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// RootOf is the bucket or top-level directory path is in, or path itself if
|
|
// it is one. ok is false for /, the buckets folder and what holds it, and
|
|
// what is left out of the counts.
|
|
func (r Roots) RootOf(path util.FullPath) (root util.FullPath, ok bool) {
|
|
if Skipped(path) {
|
|
return "", false
|
|
}
|
|
if path.IsUnder(r.Buckets) {
|
|
name := strings.SplitN(Relative(r.Buckets, path), "/", 2)[0]
|
|
return r.Buckets.Child(name), true
|
|
}
|
|
parts := path.Split()
|
|
if len(parts) == 0 || parts[0] == r.container() {
|
|
return "", false
|
|
}
|
|
return util.FullPath("/" + parts[0]), true
|
|
}
|
|
|
|
// IsRoot reports whether path is a bucket or a top-level directory.
|
|
func (r Roots) IsRoot(path util.FullPath) bool {
|
|
root, ok := r.RootOf(path)
|
|
return ok && root == path
|
|
}
|
|
|
|
// Skipped reports whether path is in a part of the tree the counts leave
|
|
// out: the metadata log, which logs no events about itself, and the records.
|
|
func Skipped(path util.FullPath) bool {
|
|
for _, dir := range []util.FullPath{filer.SystemLogDir, Dir} {
|
|
if path == dir || path.IsUnder(dir) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Store reads and writes the records of one filer store.
|
|
type Store struct {
|
|
Client filer_pb.FilerClient
|
|
Signature int32
|
|
Roots Roots
|
|
}
|
|
|
|
// location is the directory and the name of root's record.
|
|
func (s *Store) location(root util.FullPath) (dir, name string) {
|
|
kind := "top"
|
|
if root.IsUnder(s.Roots.Buckets) {
|
|
kind = "buckets"
|
|
}
|
|
return fmt.Sprintf("%s/%d/%s", Dir, s.Signature, kind), root.Name() + ".json"
|
|
}
|
|
|
|
func (s *Store) cursorName() string {
|
|
return fmt.Sprintf("cursor-%d.json", s.Signature)
|
|
}
|
|
|
|
// Load reads root's record; it is nil if there is none, or none of this
|
|
// version.
|
|
func (s *Store) Load(ctx context.Context, root util.FullPath) (*Record, error) {
|
|
dir, name := s.location(root)
|
|
var content []byte
|
|
err := s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
var err error
|
|
content, err = filer.ReadInsideFiler(ctx, client, dir, name)
|
|
return err
|
|
})
|
|
if errors.Is(err, filer_pb.ErrNotFound) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read %s/%s: %w", dir, name, err)
|
|
}
|
|
return decode(content, root), nil
|
|
}
|
|
|
|
func decode(content []byte, root util.FullPath) *Record {
|
|
var record Record
|
|
if json.Unmarshal(content, &record) != nil || record.Version != Version || record.Root != string(root) || record.Dirs == nil {
|
|
return nil
|
|
}
|
|
return &record
|
|
}
|
|
|
|
// Cursor is the log position the last replay that finished reached. A
|
|
// record at or before it is at it: a replay writes only the records it
|
|
// changed.
|
|
func (s *Store) Cursor(ctx context.Context) (int64, error) {
|
|
var tsNs int64
|
|
err := s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
content, err := filer.ReadInsideFiler(ctx, client, Dir, s.cursorName())
|
|
if errors.Is(err, filer_pb.ErrNotFound) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("read %s/%s: %w", Dir, s.cursorName(), err)
|
|
}
|
|
var cursor struct {
|
|
TsNs int64 `json:"ts_ns"`
|
|
}
|
|
if json.Unmarshal(content, &cursor) == nil {
|
|
tsNs = cursor.TsNs
|
|
}
|
|
return nil
|
|
})
|
|
return tsNs, err
|
|
}
|
|
|
|
// LoadAll reads every record of the store, by root, and the cursor.
|
|
func (s *Store) LoadAll(ctx context.Context) (records map[util.FullPath]*Record, cursorTsNs int64, err error) {
|
|
if cursorTsNs, err = s.Cursor(ctx); err != nil {
|
|
return nil, 0, err
|
|
}
|
|
records = make(map[util.FullPath]*Record)
|
|
err = s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
for _, kind := range []string{"buckets", "top"} {
|
|
dir := fmt.Sprintf("%s/%d/%s", Dir, s.Signature, kind)
|
|
err := filer_pb.SeaweedList(ctx, client, dir, "", func(entry *filer_pb.Entry, isLast bool) error {
|
|
name, found := strings.CutSuffix(entry.Name, ".json")
|
|
if entry.IsDirectory || !found {
|
|
return nil
|
|
}
|
|
root := s.Roots.Buckets.Child(name)
|
|
if kind == "top" {
|
|
root = util.FullPath("/" + name)
|
|
}
|
|
if record := decode(entry.Content, root); record != nil {
|
|
records[root] = record
|
|
}
|
|
return nil
|
|
}, "", false, math.MaxInt32)
|
|
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
|
return fmt.Errorf("list %s: %w", dir, err)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
return records, cursorTsNs, err
|
|
}
|
|
|
|
// Save writes root's record.
|
|
func (s *Store) Save(ctx context.Context, record *Record) error {
|
|
content, err := json.Marshal(record)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
dir, name := s.location(util.FullPath(record.Root))
|
|
return s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
if err := filer.SaveInsideFiler(ctx, client, dir, name, content); err != nil {
|
|
return fmt.Errorf("save %s/%s: %w", dir, name, err)
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// Delete removes root's record.
|
|
func (s *Store) Delete(ctx context.Context, root util.FullPath) error {
|
|
dir, name := s.location(root)
|
|
err := filer_pb.Remove(ctx, s.Client, dir, name, true, false, false, false, nil)
|
|
if err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
|
return fmt.Errorf("delete %s/%s: %w", dir, name, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SaveCursor writes the log position a replay of every record reached.
|
|
func (s *Store) SaveCursor(ctx context.Context, tsNs int64) error {
|
|
content, err := json.Marshal(struct {
|
|
TsNs int64 `json:"ts_ns"`
|
|
}{tsNs})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.Client.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
if err := filer.SaveInsideFiler(ctx, client, Dir, s.cursorName(), content); err != nil {
|
|
return fmt.Errorf("save %s/%s: %w", Dir, s.cursorName(), err)
|
|
}
|
|
return nil
|
|
})
|
|
}
|