Files
seaweedfs/weed/shell/command_fs_du_test.go
T
76aa922d06 shell: let fs.du print subdirectory totals and list directories in parallel (#13212)
* shell: let fs.du print subdirectory totals and list directories in parallel

fs.du prints one total and walks the tree one directory at a time. Finding
where the data of a large bucket sits takes one fs.du per directory, each a
full walk, and every listing waits on the filer and its store in turn.

-depth N also prints the total of each directory down to N levels below the
given one, like du -d N. Directories come in du's order: each one after the
directories below it, siblings by name, and the given directory's total
last, as before. One walk now gives the whole breakdown.

-concurrency N lists up to N directories at a time. A subdirectory gets a
goroutine of its own while the limit allows one and is walked in place
otherwise, so memory grows with depth and concurrency, not with the number
of directories. filer_pb.TraverseBfs is not used because it remembers every
directory it visits and queues whole levels: on a tree of 200k directories
it held 49 MB more live heap than this walk at the same speed, and weed
shell often runs in a small container. A directory's listing is complete
before its subdirectories are walked, so no listing stream stays open while
a subtree is walked.

A directory that cannot be listed used to drop out of the totals silently.
It is still left out, but the command now fails at the end with the number
of such directories and the first of them. fs.du took its last argument as
the path, or the current directory when that argument started with a dash,
so "fs.du /dir -depth=1" would have walked the current directory. Flags now
go before the path, and anything else is an error. With a prefix
(fs.du /dir/name_prefix) and no -depth, the directories the prefix matches
are no longer walked, because nothing below them is printed.

The defaults, -depth=0 and -concurrency=1, print what fs.du printed before.

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

* shell: fs.du walks a page of subdirectories before listing the next one

fs.du collected the names of all subdirectories of a directory before it
walked any of them, so a directory with millions of subdirectories held
millions of names. It now lists 1024 entries at a time and walks the
subdirectories of a page before it asks for the next page. A directory
holds at most one page of names, and still no listing stream stays open
while its subdirectories are walked. On one directory with 200k
subdirectories the walk holds 0.5 MB of live heap with -concurrency=1 and
2.5 MB with -concurrency=5.

When a page of a listing fails, the pages before it still count and the
failed page is dropped. The help and the error said that such a directory
was left out of the totals; they now say that the totals are incomplete.
When the given directory itself cannot be listed, fs.du cancels the walks
under way and waits for them before it returns the error.

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

* shell: fs.du tests refuse a listing the way a failing filer store does

An Unavailable without details makes pb close the shared connection, so the
listings running beside the refused one failed with "the client connection
is closing" and the error named another directory (6 of 30 runs with -race).
A store error reaches the client as Unknown and leaves the connection up.

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

* shell: fs.du lists directories in parallel without a -concurrency flag

The walk prints the same totals in the same order at any concurrency, so
there is nothing for a user to choose: list up to DefaultMaxParallelization
directories at a time, like the other shell commands that fan out.

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>
2026-12-01 11:01:37 -08:00

420 lines
12 KiB
Go

package shell
import (
"bytes"
"context"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
// fsDuTestFilerServer serves a directory tree from memory and records how the
// directories are listed.
type fsDuTestFilerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
children map[string][]*filer_pb.Entry
// listings of these directories fail
failing map[string]bool
// listings of these directories fail after the first page
failingAfterFirstPage map[string]bool
listDelay time.Duration
mu sync.Mutex
listing int
maxListing int
listed map[string]int
// each listing as directory@startFrom, in order
requests []string
}
func newFsDuTestFilerServer() *fsDuTestFilerServer {
return &fsDuTestFilerServer{
children: make(map[string][]*filer_pb.Entry),
failing: make(map[string]bool),
failingAfterFirstPage: make(map[string]bool),
listed: make(map[string]int),
}
}
func (s *fsDuTestFilerServer) addDir(path string) {
dir, name := util.FullPath(path).DirAndName()
if dir != "/" {
s.addDir(dir)
}
for _, entry := range s.children[dir] {
if entry.Name == name {
return
}
}
s.addEntry(dir, &filer_pb.Entry{Name: name, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}})
}
// addFile adds a file made of chunks of the given sizes.
func (s *fsDuTestFilerServer) addFile(path string, chunkSizes ...uint64) {
dir, name := util.FullPath(path).DirAndName()
s.addDir(dir)
entry := &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{}}
var offset int64
for _, size := range chunkSizes {
entry.Chunks = append(entry.Chunks, &filer_pb.FileChunk{Offset: offset, Size: size})
offset += int64(size)
}
entry.Attributes.FileSize = uint64(offset)
s.addEntry(dir, entry)
}
func (s *fsDuTestFilerServer) addEntry(dir string, entry *filer_pb.Entry) {
s.children[dir] = append(s.children[dir], entry)
sort.Slice(s.children[dir], func(i, j int) bool { return s.children[dir][i].Name < s.children[dir][j].Name })
}
func (s *fsDuTestFilerServer) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
for _, entry := range s.children[req.Directory] {
if entry.Name == req.Name {
return &filer_pb.LookupDirectoryEntryResponse{Entry: entry}, nil
}
}
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
}
func (s *fsDuTestFilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
s.mu.Lock()
s.listing++
s.maxListing = max(s.maxListing, s.listing)
s.listed[req.Directory]++
s.requests = append(s.requests, req.Directory+"@"+req.StartFromFileName)
s.mu.Unlock()
defer func() {
s.mu.Lock()
s.listing--
s.mu.Unlock()
}()
time.Sleep(s.listDelay)
if s.failing[req.Directory] || s.failingAfterFirstPage[req.Directory] && req.StartFromFileName != "" {
return status.Error(codes.Unknown, "listing refused")
}
var sent uint32
for _, entry := range s.children[req.Directory] {
if !strings.HasPrefix(entry.Name, req.Prefix) {
continue
}
if entry.Name < req.StartFromFileName || entry.Name == req.StartFromFileName && !req.InclusiveStartFrom {
continue
}
if req.Limit > 0 && sent >= req.Limit {
break
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
return err
}
sent++
}
return nil
}
func (s *fsDuTestFilerServer) resetCounts() {
s.mu.Lock()
defer s.mu.Unlock()
s.maxListing = 0
s.listed = make(map[string]int)
s.requests = nil
}
func setDuPageSize(t *testing.T, size uint32) {
t.Helper()
saved := duPageSize
duPageSize = size
t.Cleanup(func() { duPageSize = saved })
}
func setDuConcurrency(t *testing.T, concurrency int) {
t.Helper()
saved := duConcurrency
duConcurrency = concurrency
t.Cleanup(func() { duConcurrency = saved })
}
var fsDuTestPortCounter atomic.Int64
// newFsDuTestCommandEnv serves filerServer on a unix socket of its own. Each
// env gets a port number of its own too: pb caches gRPC connections by
// address, and a cached connection keeps dialing the socket it was made for.
func newFsDuTestCommandEnv(t *testing.T, filerServer filer_pb.SeaweedFilerServer) *CommandEnv {
t.Helper()
socketDir, err := os.MkdirTemp("", "swdu-")
if err != nil {
t.Fatalf("create socket dir: %v", err)
}
t.Cleanup(func() { _ = os.RemoveAll(socketDir) })
socketPath := filepath.Join(socketDir, "filer.sock")
listener, err := net.Listen("unix", socketPath)
if err != nil {
t.Fatalf("listen unix socket: %v", err)
}
grpcServer := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(grpcServer, filerServer)
go func() {
_ = grpcServer.Serve(listener)
}()
t.Cleanup(grpcServer.Stop)
grpcPort := 20000 + int(fsDuTestPortCounter.Add(1))
pb.RegisterLocalGrpcSocket("127.0.0.1", grpcPort, socketPath)
return &CommandEnv{
option: &ShellOptions{
FilerAddress: pb.ServerAddress(fmt.Sprintf("127.0.0.1:8888.%d", grpcPort)),
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
Directory: "/",
},
}
}
func runFsDu(t *testing.T, commandEnv *CommandEnv, args ...string) (string, error) {
t.Helper()
var output bytes.Buffer
err := (&commandFsDu{}).Do(args, commandEnv, &output)
return output.String(), err
}
func duLines(lines ...string) string {
return strings.Join(lines, "\n") + "\n"
}
// /data holds 5 chunks and 25 bytes: 15 in a, nothing in b, 7 in c, 3 in f4.
func newFsDuTestTree() *fsDuTestFilerServer {
server := newFsDuTestFilerServer()
server.addFile("/data/a/x/f1", 10)
server.addFile("/data/a/f2", 3, 2)
server.addDir("/data/b")
server.addFile("/data/c/y/z/f3", 7)
server.addFile("/data/f4", 3)
return server
}
func TestFsDuPrintsTheTotalOfEachDirectoryDownToDepth(t *testing.T) {
server := newFsDuTestTree()
commandEnv := newFsDuTestCommandEnv(t, server)
out, err := runFsDu(t, commandEnv, "/data")
if err != nil {
t.Fatalf("fs.du /data: %v", err)
}
if want := duLines("block: 5\tlogical size: 25\t/data"); out != want {
t.Fatalf("fs.du /data printed\n%s\nwant\n%s", out, want)
}
want := duLines(
"block: 1\tlogical size: 10\t/data/a/x",
"block: 3\tlogical size: 15\t/data/a",
"block: 0\tlogical size: 0\t/data/b",
"block: 1\tlogical size: 7\t/data/c/y",
"block: 1\tlogical size: 7\t/data/c",
"block: 5\tlogical size: 25\t/data",
)
for _, pageSize := range []uint32{duPageSize, 2} {
setDuPageSize(t, pageSize)
for _, concurrency := range []int{1, 4} {
setDuConcurrency(t, concurrency)
out, err := runFsDu(t, commandEnv, "-depth=2", "/data")
if err != nil {
t.Fatalf("page size %d, concurrency %d: %v", pageSize, concurrency, err)
}
if out != want {
t.Fatalf("page size %d, concurrency %d printed\n%s\nwant\n%s", pageSize, concurrency, out, want)
}
}
}
}
// A directory is listed a page at a time, and the subdirectories of a page
// are walked before the next page is listed, so no more than a page of names
// is held for it.
func TestFsDuWalksAPageOfSubdirectoriesBeforeListingTheNext(t *testing.T) {
setDuPageSize(t, 2)
setDuConcurrency(t, 1)
setDuConcurrency(t, 1)
server := newFsDuTestFilerServer()
for i := 0; i < 6; i++ {
server.addFile(fmt.Sprintf("/w/d%02d/f", i), 1)
}
commandEnv := newFsDuTestCommandEnv(t, server)
out, err := runFsDu(t, commandEnv, "/w")
if err != nil {
t.Fatalf("fs.du /w: %v", err)
}
if want := duLines("block: 6\tlogical size: 6\t/w"); out != want {
t.Fatalf("fs.du /w printed\n%s\nwant\n%s", out, want)
}
want := []string{
"/w@", "/w/d00@", "/w/d01@",
"/w@d01", "/w/d02@", "/w/d03@",
"/w@d03", "/w/d04@", "/w/d05@",
"/w@d05",
}
server.mu.Lock()
requests := server.requests
server.mu.Unlock()
if strings.Join(requests, " ") != strings.Join(want, " ") {
t.Fatalf("listings %v, want %v", requests, want)
}
}
func TestFsDuListsUpToConcurrencyDirectoriesAtOnce(t *testing.T) {
server := newFsDuTestFilerServer()
for i := 0; i < 12; i++ {
for j := 0; j < 3; j++ {
server.addFile(fmt.Sprintf("/data/d%02d/e%d/f", i, j), 1)
}
}
server.listDelay = 20 * time.Millisecond
commandEnv := newFsDuTestCommandEnv(t, server)
for _, concurrency := range []int{1, 4, duConcurrency} {
setDuConcurrency(t, concurrency)
server.resetCounts()
out, err := runFsDu(t, commandEnv, "/data")
if err != nil {
t.Fatalf("concurrency %d: %v", concurrency, err)
}
if want := duLines("block: 36\tlogical size: 36\t/data"); out != want {
t.Fatalf("concurrency %d printed\n%s\nwant\n%s", concurrency, out, want)
}
server.mu.Lock()
maxListing, listed := server.maxListing, server.listed
server.mu.Unlock()
if maxListing > concurrency {
t.Errorf("concurrency %d: %d directories were listed at once", concurrency, maxListing)
}
if concurrency > 1 && maxListing < 2 {
t.Errorf("concurrency %d: directories were listed one at a time", concurrency)
}
if len(listed) != 1+12+36 {
t.Errorf("concurrency %d: %d directories listed, want %d", concurrency, len(listed), 1+12+36)
}
for dir, n := range listed {
if n != 1 {
t.Errorf("concurrency %d: %s listed %d times", concurrency, dir, n)
}
}
}
}
func TestFsDuReportsADirectoryItCannotList(t *testing.T) {
server := newFsDuTestTree()
server.failing["/data/c/y"] = true
commandEnv := newFsDuTestCommandEnv(t, server)
out, err := runFsDu(t, commandEnv, "-depth=1", "/data")
if err == nil || !strings.Contains(err.Error(), "the totals are incomplete") || !strings.Contains(err.Error(), "/data/c/y") {
t.Fatalf("fs.du returned %v, want it to name /data/c/y", err)
}
want := duLines(
"block: 3\tlogical size: 15\t/data/a",
"block: 0\tlogical size: 0\t/data/b",
"block: 0\tlogical size: 0\t/data/c",
"block: 4\tlogical size: 18\t/data",
)
if out != want {
t.Fatalf("fs.du printed\n%s\nwant\n%s", out, want)
}
}
// When a later page of a listing fails, the pages before it still count.
func TestFsDuCountsWhatWasListedBeforeAListingFailed(t *testing.T) {
setDuPageSize(t, 2)
server := newFsDuTestFilerServer()
server.addFile("/data/s/d/g", 16)
server.addFile("/data/s/f1", 1)
server.addFile("/data/s/f2", 2)
server.addFile("/data/s/f3", 4)
server.failingAfterFirstPage["/data/s"] = true
commandEnv := newFsDuTestCommandEnv(t, server)
out, err := runFsDu(t, commandEnv, "-depth=1", "/data")
if err == nil || !strings.Contains(err.Error(), "the totals are incomplete") || !strings.Contains(err.Error(), "/data/s") {
t.Fatalf("fs.du returned %v, want it to name /data/s", err)
}
// the first page of /data/s is d and f1
want := duLines(
"block: 2\tlogical size: 17\t/data/s",
"block: 2\tlogical size: 17\t/data",
)
if out != want {
t.Fatalf("fs.du printed\n%s\nwant\n%s", out, want)
}
}
func TestFsDuPrintsEachFileAPrefixMatches(t *testing.T) {
server := newFsDuTestTree()
server.addFile("/data/f5/g", 4)
commandEnv := newFsDuTestCommandEnv(t, server)
out, err := runFsDu(t, commandEnv, "/data/f")
if err != nil {
t.Fatalf("fs.du /data/f: %v", err)
}
if want := duLines("block: 1\tlogical size: 3\t/data/f4"); out != want {
t.Fatalf("fs.du /data/f printed\n%s\nwant\n%s", out, want)
}
server.mu.Lock()
listedF5 := server.listed["/data/f5"]
server.mu.Unlock()
if listedF5 != 0 {
t.Fatalf("fs.du /data/f listed the matched directory /data/f5, whose total it does not print")
}
out, err = runFsDu(t, commandEnv, "-depth=1", "/data/f")
if err != nil {
t.Fatalf("fs.du -depth=1 /data/f: %v", err)
}
want := duLines(
"block: 1\tlogical size: 3\t/data/f4",
"block: 1\tlogical size: 4\t/data/f5",
)
if out != want {
t.Fatalf("fs.du -depth=1 /data/f printed\n%s\nwant\n%s", out, want)
}
}
func TestFsDuRefusesBadArguments(t *testing.T) {
server := newFsDuTestTree()
commandEnv := newFsDuTestCommandEnv(t, server)
for _, args := range [][]string{
{"/data", "-depth=1"},
{"-depth=-1", "/data"},
} {
server.resetCounts()
if _, err := runFsDu(t, commandEnv, args...); err == nil {
t.Errorf("fs.du %s: no error", strings.Join(args, " "))
}
server.mu.Lock()
listed := len(server.listed)
server.mu.Unlock()
if listed != 0 {
t.Errorf("fs.du %s listed %d directories", strings.Join(args, " "), listed)
}
}
}