diff --git a/weed/filer/abstract_sql/abstract_sql_store_list_recursive.go b/weed/filer/abstract_sql/abstract_sql_store_list_recursive.go new file mode 100644 index 0000000000..349ddf0bc5 --- /dev/null +++ b/weed/filer/abstract_sql/abstract_sql_store_list_recursive.go @@ -0,0 +1,95 @@ +package abstract_sql + +import ( + "context" + "fmt" + "strings" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +var _ filer.RecursiveLister = (*AbstractSqlStore)(nil) + +// RecursiveListSqlGenerator is implemented by a generator whose rows are keyed +// by their path. GetSqlListRecursive selects directory, name and meta of the +// rows with after < path, from <= path and, unless to is empty, path < to, in +// path order. +type RecursiveListSqlGenerator interface { + GetSqlListRecursive(tableName string, after, from, to string, limit int64) (string, []interface{}) +} + +// ListRecursivePrefixedEntries implements filer.RecursiveLister for a +// generator keyed by path, and for a directory whose subtree is in one table. +func (store *AbstractSqlStore) ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastPath util.FullPath, err error) { + gen, ok := store.SqlGenerator.(RecursiveListSqlGenerator) + if !ok { + return "", filer.ErrUnsupportedRecursiveListing + } + if store.SupportBucketTable && (dirPath == "/" || string(dirPath) == bucketsRoot) { + return "", fmt.Errorf("%w: %s spans the bucket tables", filer.ErrUnsupportedRecursiveListing, dirPath) + } + db, table, shortPath, err := store.getTxOrDB(ctx, dirPath, true) + if err != nil { + return "", fmt.Errorf("findDB %s : %v", dirPath, err) + } + base := "" + if table != DEFAULT_TABLE { + base = bucketBase(table) + } + + from := strings.TrimSuffix(string(shortPath), "/") + "/" + prefix + to, _ := prefixEnd(from) + after := string(startPath) + if base != "" { + switch { + case strings.HasPrefix(after, base+"/"): + after = after[len(base):] + case after < base+"/": + after = "" + default: + return "", nil + } + } + sqlText, args := gen.GetSqlListRecursive(table, after, from, to, limit) + rows, err := db.QueryContext(ctx, sqlText, args...) + if err != nil { + return "", fmt.Errorf("list %s recursively: %v", dirPath, err) + } + defer rows.Close() + + // The callback may query the store (a hard link's record), so the entries + // are handed over after the rows close. + var entries []*filer.Entry + for rows.Next() { + var dir, name string + var data []byte + if err = rows.Scan(&dir, &name, &data); err != nil { + return lastPath, fmt.Errorf("scan %s: %v", dirPath, err) + } + if base != "" { + dir = base + strings.TrimSuffix(dir, "/") + } + entry := &filer.Entry{FullPath: util.NewFullPath(dir, name)} + if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil { + return lastPath, fmt.Errorf("decode %s : %v", entry.FullPath, err) + } + entries = append(entries, entry) + } + if err = rows.Err(); err != nil { + return lastPath, fmt.Errorf("list %s recursively: %w", dirPath, err) + } + rows.Close() + + for _, entry := range entries { + lastPath = entry.FullPath + more, eachErr := eachEntryFunc(entry) + if eachErr != nil { + return lastPath, fmt.Errorf("failed to process eachEntryFunc: %w", eachErr) + } + if !more { + break + } + } + return lastPath, nil +} diff --git a/weed/filer/filerstore.go b/weed/filer/filerstore.go index 7ee755b69c..c84af6f176 100644 --- a/weed/filer/filerstore.go +++ b/weed/filer/filerstore.go @@ -118,6 +118,19 @@ type EntryScanner interface { ScanEntries(ctx context.Context, dirPath util.FullPath, fn func(ctx context.Context, entry *Entry) error) error } +// ErrUnsupportedRecursiveListing is returned by RecursiveLister, before any +// entry is listed, when the store cannot list below dirPath in path order. +var ErrUnsupportedRecursiveListing = errors.New("recursive listing not supported by this filer store") + +// RecursiveLister is an optional FilerStore capability: list the entries below +// dirPath, directories included, in byte order of their full paths. Only +// paths after startPath that start with dirPath + "/" + prefix are listed; +// prefix may hold "/". lastPath is the last path the store read, and a +// listing continues after it. +type RecursiveLister interface { + ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc ListEachEntryFunc) (lastPath util.FullPath, err error) +} + type BucketAware interface { OnBucketCreation(bucket string) OnBucketDeletion(bucket string) diff --git a/weed/filer/filerstore_hardlink.go b/weed/filer/filerstore_hardlink.go index 02525c6ec7..05147f5120 100644 --- a/weed/filer/filerstore_hardlink.go +++ b/weed/filer/filerstore_hardlink.go @@ -478,6 +478,7 @@ type hardLinkListing struct { each ListEachEntryFunc held []*Entry // waiting for their records; the first has a hard link last string // the name of the last entry handed on + byPath bool // last holds the full path instead ended bool // each ended the listing or failed passed bool // each ended it at an entry with others waiting behind } @@ -545,6 +546,9 @@ func (l *hardLinkListing) handOn(entry *Entry) (bool, error) { return more, err } l.last = entry.Name() + if l.byPath { + l.last = string(entry.FullPath) + } l.ended = !more return more, nil } diff --git a/weed/filer/filerstore_wrapper.go b/weed/filer/filerstore_wrapper.go index 68ca20fe22..dd41ce4fe7 100644 --- a/weed/filer/filerstore_wrapper.go +++ b/weed/filer/filerstore_wrapper.go @@ -22,6 +22,7 @@ var ( _ = VirtualFilerStore(&FilerStoreWrapper{}) _ = Debuggable(&FilerStoreWrapper{}) _ = EntryScanner(&FilerStoreWrapper{}) + _ = RecursiveLister(&FilerStoreWrapper{}) ) type VirtualFilerStore interface { @@ -453,6 +454,32 @@ func (fsw *FilerStoreWrapper) ScanEntries(ctx context.Context, dirPath util.Full }) } +// ListRecursivePrefixedEntries delegates to the default store, and is declined +// when path-specific stores could hold part of the subtree. +func (fsw *FilerStoreWrapper) ListRecursivePrefixedEntries(ctx context.Context, dirPath, startPath util.FullPath, prefix string, limit int64, eachEntryFunc ListEachEntryFunc) (lastPath util.FullPath, err error) { + if fsw.hasPathSpecificStore { + return "", ErrUnsupportedRecursiveListing + } + lister, ok := fsw.defaultStore.(RecursiveLister) + if !ok { + return "", ErrUnsupportedRecursiveListing + } + ctx = context.WithoutCancel(ctx) + stats.FilerStoreCounter.WithLabelValues(fsw.defaultStore.GetName(), "recursiveList").Inc() + start := time.Now() + defer func() { + stats.FilerStoreHistogram.WithLabelValues(fsw.defaultStore.GetName(), "recursiveList").Observe(time.Since(start).Seconds()) + }() + listing := fsw.newHardLinkListing(ctx, eachEntryFunc) + listing.byPath = true + defer func() { + var last string + last, err = listing.finish(string(lastPath), err) + lastPath = util.FullPath(last) + }() + return lister.ListRecursivePrefixedEntries(ctx, dirPath, startPath, prefix, limit, listing.add) +} + func (fsw *FilerStoreWrapper) prefixFilterEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (lastFileName string, err error) { actualStore := fsw.getActualStore(dirPath + "/") diff --git a/weed/filer/postgres/postgres_flat_sql_gen.go b/weed/filer/postgres/postgres_flat_sql_gen.go index 24f03de50d..e770a7ba4c 100644 --- a/weed/filer/postgres/postgres_flat_sql_gen.go +++ b/weed/filer/postgres/postgres_flat_sql_gen.go @@ -21,6 +21,7 @@ const DefaultFlatUpsertQuery = `INSERT INTO "%s" (path,directory,name,meta) VALU var ( _ = abstract_sql.SqlGenerator(&SqlGenPostgresFlat{}) _ = abstract_sql.PathListSqlGenerator(&SqlGenPostgresFlat{}) + _ = abstract_sql.RecursiveListSqlGenerator(&SqlGenPostgresFlat{}) ) func flatPath(key abstract_sql.RowKey) string { @@ -109,3 +110,16 @@ func (gen *SqlGenPostgresFlat) GetSqlListPath(tableName, dir, after, from, to st return fmt.Sprintf(`SELECT directory, name, CASE WHEN directory=$1 THEN meta END FROM "%s" WHERE %s>$2 AND %s>=$3 AND %s<$4 ORDER BY %s ASC LIMIT $5`, tableIdent(tableName), path, path, path, path), []interface{}{dir, after, from, to, limit} } + +func (gen *SqlGenPostgresFlat) GetSqlListRecursive(tableName string, after, from, to string, limit int64) (string, []interface{}) { + path := "path" + if gen.ForceBinaryCollation { + path = `path COLLATE "C"` + } + if to == "" { + return fmt.Sprintf(`SELECT directory, name, meta FROM "%s" WHERE %s>$1 AND %s>=$2 ORDER BY %s ASC LIMIT $3`, tableIdent(tableName), path, path, path), + []interface{}{after, from, limit} + } + return fmt.Sprintf(`SELECT directory, name, meta FROM "%s" WHERE %s>$1 AND %s>=$2 AND %s<$3 ORDER BY %s ASC LIMIT $4`, tableIdent(tableName), path, path, path, path), + []interface{}{after, from, to, limit} +} diff --git a/weed/filer/postgres/postgres_flat_sql_gen_test.go b/weed/filer/postgres/postgres_flat_sql_gen_test.go index a4f16ee830..c0034bffbf 100644 --- a/weed/filer/postgres/postgres_flat_sql_gen_test.go +++ b/weed/filer/postgres/postgres_flat_sql_gen_test.go @@ -44,6 +44,22 @@ func TestFlatStatementsAddressRowsByPath(t *testing.T) { } } +func TestFlatRecursiveListing(t *testing.T) { + gen := &SqlGenPostgresFlat{} + list, args := gen.GetSqlListRecursive("bkt", "/a/b", "/a/", "/a0", 100) + if !strings.Contains(list, "WHERE path>$1 AND path>=$2 AND path<$3 ORDER BY path ASC LIMIT $4") || len(args) != 4 || args[0] != "/a/b" || args[2] != "/a0" { + t.Fatalf("list %s %v", list, args) + } + list, args = gen.GetSqlListRecursive("bkt", "", "/", "", 100) + if strings.Contains(list, "$4") || len(args) != 3 { + t.Fatalf("unbounded list %s %v", list, args) + } + gen.ForceBinaryCollation = true + if list, _ = gen.GetSqlListRecursive("bkt", "", "/", "/0", 1); !strings.Contains(list, `ORDER BY path COLLATE "C"`) { + t.Fatalf("list without a byte-ordered column: %s", list) + } +} + func TestFlatPathListing(t *testing.T) { gen := &SqlGenPostgresFlat{} list, args := gen.GetSqlListPath("bkt", "/a", "/a/b", "/a/", "/a0", 100) diff --git a/weed/filer/store_test/conformance.go b/weed/filer/store_test/conformance.go index 371bddcade..8a1bd71b6e 100644 --- a/weed/filer/store_test/conformance.go +++ b/weed/filer/store_test/conformance.go @@ -192,6 +192,77 @@ func TestFilerStoreConformance(t *testing.T, store filer.FilerStore) { }) } + if lister, ok := store.(filer.RecursiveLister); ok { + t.Run("recursive listing", func(t *testing.T) { + listAll := func(t *testing.T, d, start, prefix string, limit int64) ([]string, error) { + t.Helper() + var paths []string + for { + n := 0 + last, err := lister.ListRecursivePrefixedEntries(ctx, util.FullPath(d), util.FullPath(start), prefix, limit, func(e *filer.Entry) (bool, error) { + paths = append(paths, string(e.FullPath)) + n++ + return true, nil + }) + if err != nil || int64(n) < limit { + return paths, err + } + start = string(last) + } + } + root := "/buckets/bkt1/rec" + if _, err := listAll(t, root, "", "", 10); errors.Is(err, filer.ErrUnsupportedRecursiveListing) { + t.Skip(err) + } + insert(t, dir(root), dir(root+"/a"), dir(root+"/a/y"), dir(root+"/a-b"), dir(root+"/日本"), + file(root+"/a+b", 1), file(root+"/a/x", 1), file(root+"/a/y/z", 1), file(root+"/a-b/x", 1), + file(root+"/a0", 1), file(root+"/日本/x", 1), file(root+"/%_!", 1), file("/buckets/bkt1/rec0", 1)) + rel := func(names ...string) []string { + for i, n := range names { + names[i] = root + "/" + n + } + return names + } + all := rel("%_!", "a", "a+b", "a-b", "a-b/x", "a/x", "a/y", "a/y/z", "a0", "日本", "日本/x") + for _, limit := range []int64{1000, 3, 1} { + got, err := listAll(t, root, "", "", limit) + require.NoError(t, err) + require.Equal(t, all, got, "limit %d", limit) + } + got, err := listAll(t, root, "", "a/", 1000) + require.NoError(t, err) + require.Equal(t, rel("a/x", "a/y", "a/y/z"), got) + got, err = listAll(t, root, "", "a", 2) + require.NoError(t, err) + require.Equal(t, rel("a", "a+b", "a-b", "a-b/x", "a/x", "a/y", "a/y/z", "a0"), got) + got, err = listAll(t, root, "", "%_", 1000) + require.NoError(t, err) + require.Equal(t, rel("%_!"), got, "% and _ are literal") + got, err = listAll(t, root, root+"/a-b/x", "", 1000) + require.NoError(t, err) + require.Equal(t, rel("a/x", "a/y", "a/y/z", "a0", "日本", "日本/x"), got) + got, err = listAll(t, root+"/a", "", "", 1000) + require.NoError(t, err) + require.Equal(t, rel("a/x", "a/y", "a/y/z"), got) + got, err = listAll(t, root, "/buckets/aaa/z", "", 1000) + require.NoError(t, err) + require.Equal(t, all, got, "a start path before the subtree") + got, err = listAll(t, root, "/buckets/bkt2/a", "", 1000) + require.NoError(t, err) + require.Empty(t, got, "a start path past the subtree") + got, err = listAll(t, "/topics", "", "", 1000) + require.NoError(t, err) + require.Equal(t, []string{"/topics/t.log"}, got) + + if bucketAware, ok := store.(filer.BucketAware); ok && bucketAware.CanDropWholeBucket() { + for _, d := range []string{"/", "/buckets"} { + _, err := listAll(t, d, "", "", 10) + require.ErrorIs(t, err, filer.ErrUnsupportedRecursiveListing, "%s spans the bucket tables", d) + } + } + }) + } + t.Run("delete folder children", func(t *testing.T) { require.NoError(t, store.DeleteFolderChildren(ctx, "/buckets/bkt1/order")) require.Empty(t, list(t, "/buckets/bkt1/order", "", false, 100, ""))