package dir_usage import ( "context" "fmt" "math" "strings" "time" "github.com/seaweedfs/seaweedfs/weed/filer/dirusage" "github.com/seaweedfs/seaweedfs/weed/filer/treewalk" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/worker/tasks/meta_log_purge" ) const ( clientName = "dir_usage" // seedConcurrency and seedPageSize are fs.du's seedConcurrency = 10 seedPageSize = 1024 ) // logMargin is the seeds' Margin, how long after a change its event is // logged at most. Tests shorten it. var logMargin = time.Minute type runStats struct { events int64 written int64 removed int64 seeded int64 failed []string } // run brings the records of the store behind client up to a margin before // now: it replays the events since the records' positions, and seeds the // buckets and top-level directories without a record from a walk. func run(ctx context.Context, client filer_pb.FilerClient, now time.Time, stats *runStats, progress func(string)) error { var roots dirusage.Roots var signature int32 var logStart int64 err := client.WithFilerClient(false, func(c filer_pb.SeaweedFilerClient) error { var err error if roots, signature, err = dirusage.RootsOf(ctx, c); err != nil { return err } logStart, err = treewalk.LogStartTsNs(ctx, c) return err }) if err != nil { return err } store := &dirusage.Store{Client: client, Signature: signature, Roots: roots} records, cursorTsNs, err := store.LoadAll(ctx) if err != nil { return err } if logStart == 0 && now.Sub(time.Unix(0, cursorTsNs)) > meta_log_purge.CursorStaleAfter { // No log is kept. The purge keeps the log from a cursor saved since, // so no event was logged after it; from a stale one, some may be gone. logStart = now.UnixNano() } for root, record := range records { // the replay that saved the cursor took this record to it record.TsNs = max(record.TsNs, cursorTsNs) // the events it needs are gone: seed it again if record.TsNs < logStart { if err := store.Delete(ctx, root); err != nil { return err } delete(records, root) stats.removed++ } } // The replay ends where the filer says it has logged every event, on its // own clock: a subscription with an end stops once it read all the filer // logged. The cursor never goes back. untilNs, err := treewalk.SnapshotTsNs(ctx, client, "/") if err != nil { return err } if untilNs == 0 { untilNs = now.Add(-logMargin).UnixNano() } untilNs = max(untilNs, cursorTsNs) if len(records) > 0 { progress(fmt.Sprintf("replaying the events of %d records", len(records))) t := newTracker(roots, records) sinceNs := int64(math.MaxInt64) for _, record := range records { sinceNs = min(sinceNs, record.TsNs) } _, err := treewalk.Follow(ctx, client, clientName, "/", sinceNs, untilNs, t.apply) stats.events += t.events if err != nil { return fmt.Errorf("replay: %w", err) } for root := range t.removed { if err := store.Delete(ctx, root); err != nil { return err } stats.removed++ } for root, record := range t.records { if takeOffExpired(record, untilNs) { t.changed[root] = true } } for root := range t.changed { record := t.records[root] record.TsNs = max(record.TsNs, untilNs) if err := store.Save(ctx, record); err != nil { return err } stats.written++ } records = t.records } // Every record is at untilNs now. Saved after the records, so a run // that stops in between replays again what it did not save. if err := store.SaveCursor(ctx, untilNs); err != nil { return err } current, err := roots.List(ctx, client) if err != nil { return err } for root := range records { if !current[root] { // gone without an event the replay saw if err := store.Delete(ctx, root); err != nil { return err } stats.removed++ } } // The buckets without a record are seeded in one walk of the buckets // folder, and the top-level directories in one of /, so that a run waits // the margin at the end of a walk at most twice. buckets, tops := make(map[util.FullPath]bool), make(map[util.FullPath]bool) for root := range current { switch { case records[root] != nil: case root.IsUnder(roots.Buckets): buckets[root] = true default: tops[root] = true } } for _, batch := range []struct { container util.FullPath roots map[util.FullPath]bool }{{roots.Buckets, buckets}, {"/", tops}} { if len(batch.roots) == 0 { continue } progress(fmt.Sprintf("seeding %d directories in %s", len(batch.roots), batch.container)) seeded, err := seedRoots(ctx, client, roots, batch.container, batch.roots) if err != nil { if ctx.Err() != nil { return err } // the next run tries again stats.failed = append(stats.failed, fmt.Sprintf("seed %s: %v", batch.container, err)) continue } for _, record := range seeded { if err := store.Save(ctx, record); err != nil { if ctx.Err() != nil { return err } // the next run seeds this one again, not the whole batch stats.failed = append(stats.failed, err.Error()) continue } stats.seeded++ } } if len(stats.failed) > 0 { return fmt.Errorf("%s", strings.Join(stats.failed, "; ")) } return nil } // tracker applies metadata events to the records. type tracker struct { roots dirusage.Roots records map[util.FullPath]*dirusage.Record changed map[util.FullPath]bool removed map[util.FullPath]bool events int64 } func newTracker(roots dirusage.Roots, records map[util.FullPath]*dirusage.Record) *tracker { return &tracker{ roots: roots, records: records, changed: make(map[util.FullPath]bool), removed: make(map[util.FullPath]bool), } } func (t *tracker) apply(event *filer_pb.SubscribeMetadataResponse) error { t.events++ n := event.EventNotification oldDir := util.FullPath(event.Directory) newDir := util.FullPath(filer_pb.MetadataEventTargetDirectory(event)) if n.OldEntry != nil && n.NewEntry != nil && oldDir == newDir && n.OldEntry.Name == n.NewEntry.Name { t.side(oldDir.Child(n.OldEntry.Name), event.TsNs, n.OldEntry, n.NewEntry, false) return nil } // a moved directory keeps its record, and so do the ones below it var carried []string if n.OldEntry != nil && n.NewEntry != nil && n.OldEntry.IsDirectory && n.NewEntry.IsDirectory { carried = t.trackedBelow(oldDir.Child(n.OldEntry.Name), event.TsNs) } if n.OldEntry != nil { t.side(oldDir.Child(n.OldEntry.Name), event.TsNs, n.OldEntry, nil, n.NewEntry != nil) } if n.NewEntry != nil { t.side(newDir.Child(n.NewEntry.Name), event.TsNs, nil, n.NewEntry, false) } if len(carried) > 0 { t.track(newDir.Child(n.NewEntry.Name), event.TsNs, carried) } return nil } // recordOf is the record that counts an entry at path, and the path of the // entry's directory relative to the record's root; nil for an entry inside a // part of the tree left out, or outside every bucket and top-level directory, // and for an event the record already counted. func (t *tracker) recordOf(path util.FullPath, tsNs int64) (*dirusage.Record, string) { dir, _ := path.DirAndName() parent := util.FullPath(dir) if dirusage.Skipped(parent) { return nil, "" } root, ok := t.roots.RootOf(parent) if !ok { return nil, "" } record := t.records[root] if record == nil || tsNs <= record.TsNs { return nil, "" } return record, dirusage.Relative(root, parent) } // side applies what an event did at path: from and to are the entry before // and after, nil where there was none. moved is set when from went elsewhere. // An entry the record has taken off for its TTL is no longer counted, so an // event about it changes nothing again. func (t *tracker) side(path util.FullPath, tsNs int64, from, to *filer_pb.Entry, moved bool) { if t.roots.IsRoot(path) { t.rootChanged(path, tsNs, to) return } record, rel := t.recordOf(path, tsNs) if record == nil { return } var delta dirusage.Usage if from != nil { if value := dirusage.EntryValue(from); counted(value, record.TsNs) { delta.Sub(value.Usage) expireAt(record, rel, value, -1) } } if to != nil { if value := dirusage.EntryValue(to); counted(value, record.TsNs) { delta.Add(value.Usage) expireAt(record, rel, value, 1) } } addUp(record, rel, delta) if from != nil && from.IsDirectory && (to == nil || !to.IsDirectory) { dropTracked(record, joinRelative(rel, path.Name()), rel, moved && to == nil) } t.changed[util.FullPath(record.Root)] = true } // counted reports whether a record at tsNs counts an entry with value. func counted(value dirusage.Value, tsNs int64) bool { return !dirusage.TakenOff(value.Expires, tsNs) } // expireAt adds (sign 1) or withdraws (sign -1) an entry in the directory // at rel to what comes off when it expires, under the directory with a // record nearest above it. func expireAt(record *dirusage.Record, rel string, value dirusage.Value, sign int) { if value.Expires == 0 { return } if record.Expiring == nil { record.Expiring = make(map[int64]map[string]dirusage.Usage) } totals := record.Expiring[value.Expires] if totals == nil { totals = make(map[string]dirusage.Usage) record.Expiring[value.Expires] = totals } at := nearestTracked(record, rel) usage := totals[at] if sign > 0 { usage.Add(value.Usage) } else { usage.Sub(value.Usage) } if usage.IsZero() { delete(totals, at) } else { totals[at] = usage } if len(totals) == 0 { delete(record.Expiring, value.Expires) } } // takeOffExpired takes off what expired by tsNs and reports whether // anything did. func takeOffExpired(record *dirusage.Record, tsNs int64) bool { took := false for expires, totals := range record.Expiring { if !dirusage.TakenOff(expires, tsNs) { continue } for at, usage := range totals { var expired dirusage.Usage expired.Sub(usage) addUp(record, at, expired) } delete(record.Expiring, expires) took = true } return took } // nearestTracked is rel, or the directory with a record nearest above it. func nearestTracked(record *dirusage.Record, rel string) string { for { if _, tracked := record.Dirs[rel]; tracked || rel == "" { return rel } rel = parentRelative(rel) } } // trackedBelow are the directories at or below path with a record, relative // to path. func (t *tracker) trackedBelow(path util.FullPath, tsNs int64) []string { if t.roots.IsRoot(path) { return nil } record, parentRel := t.recordOf(path, tsNs) if record == nil { return nil } rel := joinRelative(parentRel, path.Name()) var below []string for tracked := range record.Dirs { if tracked == rel { below = append(below, "") } else if strings.HasPrefix(tracked, rel+"/") { below = append(below, tracked[len(rel)+1:]) } } return below } // track gives the directories a move carried to path an empty record each, // as deep as records go; the events of the entries the move took along fill // them. func (t *tracker) track(path util.FullPath, tsNs int64, carried []string) { if t.roots.IsRoot(path) { return } record, parentRel := t.recordOf(path, tsNs) if record == nil { return } rel := joinRelative(parentRel, path.Name()) for _, below := range carried { tracked := joinRelative(rel, below) if _, found := record.Dirs[tracked]; !found && depthOf(tracked) <= dirusage.MaxDepth { record.Dirs[tracked] = dirusage.Usage{} } } t.changed[util.FullPath(record.Root)] = true } // rootChanged drops the record of a bucket or top-level directory that went // away or moved. One created or moved in is seeded by the run. func (t *tracker) rootChanged(root util.FullPath, tsNs int64, to *filer_pb.Entry) { record := t.records[root] if record == nil || tsNs <= record.TsNs || to != nil { return } delete(t.records, root) delete(t.changed, root) t.removed[root] = true } // addUp adds delta to the directory at rel and to each directory above it // that has a record of its own. func addUp(record *dirusage.Record, rel string, delta dirusage.Usage) { for { if usage, tracked := record.Dirs[rel]; tracked { usage.Add(delta) record.Dirs[rel] = usage } if rel == "" { return } rel = parentRelative(rel) } } // dropTracked drops the record of a removed directory and of what was below // it. A directory deleted with totals left had entries that went without // events, as when a store drops a whole bucket: the rest comes off the // directories above it, and so does what was still to expire there. A moved // directory's entries each log their own move, and what they had still to // expire waits for that under the directory above. func dropTracked(record *dirusage.Record, rel, parentRel string, moved bool) { usage, tracked := record.Dirs[rel] if !tracked { return } if !moved && !usage.IsZero() { var rest dirusage.Usage rest.Sub(usage) addUp(record, parentRel, rest) } below := func(at string) bool { return at == rel || strings.HasPrefix(at, rel+"/") } for at := range record.Dirs { if below(at) { delete(record.Dirs, at) } } above := nearestTracked(record, parentRel) for expires, totals := range record.Expiring { for at, usage := range totals { if !below(at) { continue } delete(totals, at) if moved { waiting := totals[above] waiting.Add(usage) totals[above] = waiting } } if len(totals) == 0 { delete(record.Expiring, expires) } } } func parentRelative(rel string) string { if i := strings.LastIndex(rel, "/"); i >= 0 { return rel[:i] } return "" } func joinRelative(rel, name string) string { switch { case rel == "": return name case name == "": return rel } return rel + "/" + name } // depthOf is how many levels below its root the directory at rel is. func depthOf(rel string) int { if rel == "" { return 0 } return strings.Count(rel, "/") + 1 } // seeding adds up a walk of the buckets folder or of / into the totals of // the roots in it: of each directory being walked, kept once it is done while // it holds its share of what the walk counted of its root so far. A directory // holding its share of the whole root holds it of any part, unless entries // went or expired since it was done. type seeding struct { roots dirusage.Roots dirs map[util.FullPath]map[string]*seedDir // by root, then by path relative to it } // seedDir is what a walk keeps of a directory: its totals, and what of them // a TTL takes out, by when, for the entries it is the nearest kept directory // above. type seedDir struct { usage dirusage.Usage expiring map[int64]dirusage.Usage } func (d *seedDir) expire(expires int64, usage dirusage.Usage, sign int) { if d.expiring == nil { d.expiring = make(map[int64]dirusage.Usage) } total := d.expiring[expires] if sign > 0 { total.Add(usage) } else { total.Sub(usage) } if total.IsZero() { delete(d.expiring, expires) } else { d.expiring[expires] = total } } // seedRoots walks container, the buckets folder or /, into the roots in it // that toSeed holds, and returns their records. func seedRoots(ctx context.Context, client filer_pb.FilerClient, roots dirusage.Roots, container util.FullPath, toSeed map[util.FullPath]bool) (map[util.FullPath]*dirusage.Record, error) { s := &seeding{roots: roots, dirs: make(map[util.FullPath]map[string]*seedDir)} seed := &treewalk.Seed[dirusage.Value]{ Client: client, ClientName: clientName, Concurrency: seedConcurrency, PageSize: seedPageSize, Value: dirusage.EntryValue, Change: s.change, Started: s.started, Done: s.done, Skip: func(dir util.FullPath) bool { if dirusage.Skipped(dir) { return true } root, ok := roots.RootOf(dir) if !ok { // the buckets folder, when walking / return dir != container } return !toSeed[root] }, Margin: logMargin, } atNs, err := seed.Run(ctx, container) if err != nil { return nil, err } return s.records(atNs), nil } // of is the directories kept of the root dir is in, and dir relative to it; // nil for the container. func (s *seeding) of(dir util.FullPath) (root util.FullPath, dirs map[string]*seedDir, rel string) { root, ok := s.roots.RootOf(dir) if !ok { return "", nil, "" } return root, s.dirs[root], dirusage.Relative(root, dir) } func (s *seeding) started(dir util.FullPath, depth int) { root, dirs, rel := s.of(dir) switch { case root == "": case rel == "": s.dirs[root] = map[string]*seedDir{"": {}} case dirs != nil && depthOf(rel) <= dirusage.MaxDepth: dirs[rel] = &seedDir{} } } // change adds what changed in dir to each directory being walked or kept // above it, and what of it expires to the nearest. An entry of the container // is a root: one that goes away during the walk gets no record, since a // store that drops a whole bucket logs no event for what was in it; the next // run seeds it if it comes back. func (s *seeding) change(dir util.FullPath, name string, from, to *dirusage.Value) { if path := dir.Child(name); s.roots.IsRoot(path) { if to == nil { delete(s.dirs, path) } return } _, dirs, rel := s.of(dir) if dirs == nil { return } var delta dirusage.Usage if to != nil { delta.Add(to.Usage) } if from != nil { delta.Sub(from.Usage) } var nearest *seedDir for { if d := dirs[rel]; d != nil { d.usage.Add(delta) if nearest == nil { nearest = d } } if rel == "" { break } rel = parentRelative(rel) } if from != nil && from.Expires != 0 { nearest.expire(from.Expires, from.Usage, -1) } if to != nil && to.Expires != 0 { nearest.expire(to.Expires, to.Usage, 1) } } // done drops a directory below its share, and hands what of it expires to // the nearest directory kept above. func (s *seeding) done(dir util.FullPath, depth int) { _, dirs, rel := s.of(dir) if dirs == nil || rel == "" { return } d := dirs[rel] if d == nil || holdsShare(d.usage, dirs[""].usage) { return } delete(dirs, rel) for above := parentRelative(rel); ; above = parentRelative(above) { if kept := dirs[above]; kept != nil { for expires, usage := range d.expiring { kept.expire(expires, usage, 1) } return } } } // records are the totals of each root at atNs. What expired by then comes off // first, so a directory the walk kept keeps its record if it holds its share // of its root at atNs. func (s *seeding) records(atNs int64) map[util.FullPath]*dirusage.Record { records := make(map[util.FullPath]*dirusage.Record, len(s.dirs)) for root, dirs := range s.dirs { record := &dirusage.Record{ Version: dirusage.Version, Root: string(root), TsNs: atNs, SeededNs: atNs, Dirs: make(map[string]dirusage.Usage, len(dirs)), } for rel, d := range dirs { record.Dirs[rel] = d.usage } for rel, d := range dirs { for expires, usage := range d.expiring { expireAt(record, rel, dirusage.Value{Usage: usage, Expires: expires}, 1) } } takeOffExpired(record, atNs) rootUsage := record.Dirs[""] for rel, usage := range record.Dirs { if rel != "" && !holdsShare(usage, rootUsage) { // its entries stay counted above, and none below holds its share dropTracked(record, rel, parentRelative(rel), true) } } records[root] = record } return records } // holdsShare reports whether a directory with usage holds its share of a // bucket with total. func holdsShare(usage, total dirusage.Usage) bool { return usage.Bytes > 0 && usage.Bytes >= (total.Bytes*dirusage.MinSharePercent+99)/100 }