mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
* worker: dir_usage takes off what a TTL expires A plain TTL removes an expired row without an event, so a record kept counting it until its bucket was seeded again. An entry's attributes say when listings start leaving it out (Entry.ExpiresAt, which listingExpired now uses), so a record keeps what each directory has still to expire, grouped by the step it expires in, and each run takes off what came off by its position. A step is an hour, or for a TTL of 200 hours or more the largest power of two hours up to 1% of it, so a record stays bounded. An event counts an entry only if the record has not taken it off yet, so an S3 expiry, which logs a delete, comes off once. Record version 2 seeds the records made before again. Part of #13257. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * dir_usage: decide a seeded directory's share after what expired The seed took off what had expired by its position only after the final share check, so a directory the walk kept could be dropped against a total that still counted those entries. Take them off first, and hand what a dropped directory has still to expire to the directory above. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * dir_usage: drop a seeded directory below its share with dropTracked A directory below its share has none above its share below it, so dropping it with what is below, its entries staying counted above, is what untrack did. 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>
387 lines
12 KiB
Go
387 lines
12 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"
|
|
"time"
|
|
|
|
"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 2 takes off what a TTL expires.
|
|
Version = 2
|
|
// 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{}
|
|
}
|
|
|
|
// Value is what an entry adds to the directories above it, and when a record
|
|
// takes that off for its TTL.
|
|
type Value struct {
|
|
Usage
|
|
// Expires is when a record takes the entry off, in unix seconds, 0 if
|
|
// never: see Expires.
|
|
Expires int64
|
|
}
|
|
|
|
// EntryValue is what entry adds to the directories above it, and until when.
|
|
func EntryValue(entry *filer_pb.Entry) Value {
|
|
return Value{Usage: EntryUsage(entry), Expires: Expires(entry)}
|
|
}
|
|
|
|
// Expires is when a record takes entry off, in unix seconds: the end of the
|
|
// step in which listings start leaving it out, or 0 if they never do. The
|
|
// plain TTL removes the row without an event, so a record takes off by the
|
|
// step what expired in it, and counts an expired entry for at most a step.
|
|
func Expires(entry *filer_pb.Entry) int64 {
|
|
ttlSec := int64(entry.GetAttributes().GetTtlSec())
|
|
if entry == nil || entry.IsDirectory || ttlSec <= 0 {
|
|
return 0
|
|
}
|
|
expiresAt, ok := filer.FromPbEntry("/", entry).ExpiresAt()
|
|
if !ok {
|
|
return 0
|
|
}
|
|
step := expiryStep(ttlSec)
|
|
if t := expiresAt.Unix(); t > 0 {
|
|
return (t + step - 1) / step * step
|
|
}
|
|
// expired long ago
|
|
return step
|
|
}
|
|
|
|
// expiryStep is an hour, or for a TTL of 200 hours or more the largest power
|
|
// of two hours up to 1% of it: a record counts an expired entry for at most
|
|
// an hour or 1% of its TTL, and fewer than 200 steps fit in any TTL, so a
|
|
// directory has about that many pending for each TTL in it at most.
|
|
func expiryStep(ttlSec int64) int64 {
|
|
step := int64(time.Hour / time.Second)
|
|
for step*2 <= ttlSec/100 {
|
|
step *= 2
|
|
}
|
|
return step
|
|
}
|
|
|
|
// TakenOff reports whether a record at tsNs has taken off what comes off at
|
|
// expires.
|
|
func TakenOff(expires, tsNs int64) bool {
|
|
return expires != 0 && expires <= tsNs/int64(time.Second)
|
|
}
|
|
|
|
// 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"`
|
|
// Expiring is what Dirs count that a TTL takes out later, by when it
|
|
// comes off (unix seconds, see Expires) and then by the directory in Dirs
|
|
// nearest above it. What comes off by TsNs is taken off.
|
|
Expiring map[int64]map[string]Usage `json:"expiring,omitempty"`
|
|
}
|
|
|
|
// 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
|
|
})
|
|
}
|