Skip to content

SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.

s3tables: add the maintenance configuration APIs (#10773)

Chris Lueef6f3d1e641
diff --git a/weed/s3api/s3api_tables.go b/weed/s3api/s3api_tables.go
index a1eb54d6f1..2c76b91d79 100644
--- a/weed/s3api/s3api_tables.go
+++ b/weed/s3api/s3api_tables.go
@@ -76,8 +76,9 @@ func (s3a *S3ApiServer) registerS3TablesRoutes(router *mux.Router) {
s3TablesApi.SetDefaultAllow(true)
}
- // Regex for S3 Tables Bucket ARN
- const tableBucketARNRegex = "arn:aws:s3tables:[^/:]*:[^/:]*:bucket/[^/]+"
+ // Regex for S3 Tables Bucket ARN. The partition is not fixed to "aws":
+ // aws-cn and aws-us-gov ARNs are valid and have to reach the handlers.
+ const tableBucketARNRegex = s3tables.ARNPrefixPatternStr + ":[^/:]*:[^/:]*:bucket/[^/]+"
// REST-style S3 Tables API routes (used by AWS CLI)
targetMatcher := func(r *http.Request, rm *mux.RouteMatch) bool {
@@ -133,11 +134,22 @@ func (s3a *S3ApiServer) registerS3TablesRoutes(router *mux.Router) {
router.Methods(http.MethodDelete).Path("/tables/{tableBucketARN:" + tableBucketARNRegex + "}/{namespace}/{name}/policy").MatcherFunc(serviceMatcher).
HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("DeleteTablePolicy", buildDeleteTablePolicyRequest)), "S3Tables-DeleteTablePolicy"))
- router.Methods(http.MethodPost).Path("/tag/{resourceArn:arn:aws:s3tables:.*}").MatcherFunc(serviceMatcher).
+ router.Methods(http.MethodPut).Path("/buckets/{tableBucketARN:" + tableBucketARNRegex + "}/maintenance/{type}").MatcherFunc(serviceMatcher).
+ HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("PutTableBucketMaintenanceConfiguration", buildPutTableBucketMaintenanceConfigurationRequest)), "S3Tables-PutTableBucketMaintenanceConfiguration"))
+ router.Methods(http.MethodGet).Path("/buckets/{tableBucketARN:" + tableBucketARNRegex + "}/maintenance").MatcherFunc(serviceMatcher).
+ HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("GetTableBucketMaintenanceConfiguration", buildGetTableBucketMaintenanceConfigurationRequest)), "S3Tables-GetTableBucketMaintenanceConfiguration"))
+ router.Methods(http.MethodPut).Path("/tables/{tableBucketARN:" + tableBucketARNRegex + "}/{namespace}/{name}/maintenance/{type}").MatcherFunc(serviceMatcher).
+ HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("PutTableMaintenanceConfiguration", buildPutTableMaintenanceConfigurationRequest)), "S3Tables-PutTableMaintenanceConfiguration"))
+ router.Methods(http.MethodGet).Path("/tables/{tableBucketARN:" + tableBucketARNRegex + "}/{namespace}/{name}/maintenance").MatcherFunc(serviceMatcher).
+ HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("GetTableMaintenanceConfiguration", buildGetTableMaintenanceConfigurationRequest)), "S3Tables-GetTableMaintenanceConfiguration"))
+ router.Methods(http.MethodGet).Path("/tables/{tableBucketARN:" + tableBucketARNRegex + "}/{namespace}/{name}/maintenance-job-status").MatcherFunc(serviceMatcher).
+ HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("GetTableMaintenanceJobStatus", buildGetTableMaintenanceJobStatusRequest)), "S3Tables-GetTableMaintenanceJobStatus"))
+
+ router.Methods(http.MethodPost).Path("/tag/{resourceArn:" + s3tables.ARNPrefixPatternStr + ":.*}").MatcherFunc(serviceMatcher).
HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("TagResource", buildTagResourceRequest)), "S3Tables-TagResource"))
- router.Methods(http.MethodGet).Path("/tag/{resourceArn:arn:aws:s3tables:.*}").MatcherFunc(serviceMatcher).
+ router.Methods(http.MethodGet).Path("/tag/{resourceArn:" + s3tables.ARNPrefixPatternStr + ":.*}").MatcherFunc(serviceMatcher).
HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("ListTagsForResource", buildListTagsForResourceRequest)), "S3Tables-ListTagsForResource"))
- router.Methods(http.MethodDelete).Path("/tag/{resourceArn:arn:aws:s3tables:.*}").MatcherFunc(serviceMatcher).
+ router.Methods(http.MethodDelete).Path("/tag/{resourceArn:" + s3tables.ARNPrefixPatternStr + ":.*}").MatcherFunc(serviceMatcher).
HandlerFunc(track(s3a.authenticateS3Tables(s3TablesApi.handleRestOperation("UntagResource", buildUntagResourceRequest)), "S3Tables-UntagResource"))
router.Methods(http.MethodGet).Path("/get-table").MatcherFunc(serviceMatcher).
@@ -711,3 +723,94 @@ func (s3a *S3ApiServer) authenticateS3Tables(f http.HandlerFunc) http.HandlerFun
f(w, r)
}
}
+
+// maintenanceTableTarget pulls the bucket/namespace/table triple every
+// table-scoped maintenance route carries in its path.
+func maintenanceTableTarget(r *http.Request) (tableBucketARN string, namespace []string, name string, err error) {
+ if tableBucketARN, err = getDecodedPathParam(r, "tableBucketARN"); err != nil {
+ return "", nil, "", err
+ }
+ if namespace, err = parseRequiredNamespacePathParam(r, "namespace"); err != nil {
+ return "", nil, "", err
+ }
+ if name, err = getDecodedPathParam(r, "name"); err != nil {
+ return "", nil, "", err
+ }
+ if name == "" {
+ return "", nil, "", fmt.Errorf("name is required")
+ }
+ if _, err = s3tables.ValidateTableName(name); err != nil {
+ return "", nil, "", err
+ }
+ return tableBucketARN, namespace, name, nil
+}
+
+func buildPutTableBucketMaintenanceConfigurationRequest(r *http.Request) (interface{}, error) {
+ var req s3tables.PutTableBucketMaintenanceConfigurationRequest
+ if err := readS3TablesJSONBody(r, &req); err != nil {
+ return nil, err
+ }
+ tableBucketARN, err := getDecodedPathParam(r, "tableBucketARN")
+ if err != nil {
+ return nil, err
+ }
+ maintenanceType, err := getDecodedPathParam(r, "type")
+ if err != nil {
+ return nil, err
+ }
+ req.TableBucketARN = tableBucketARN
+ req.Type = maintenanceType
+ return &req, nil
+}
+
+func buildGetTableBucketMaintenanceConfigurationRequest(r *http.Request) (interface{}, error) {
+ tableBucketARN, err := getDecodedPathParam(r, "tableBucketARN")
+ if err != nil {
+ return nil, err
+ }
+ return &s3tables.GetTableBucketMaintenanceConfigurationRequest{TableBucketARN: tableBucketARN}, nil
+}
+
+func buildPutTableMaintenanceConfigurationRequest(r *http.Request) (interface{}, error) {
+ var req s3tables.PutTableMaintenanceConfigurationRequest
+ if err := readS3TablesJSONBody(r, &req); err != nil {
+ return nil, err
+ }
+ tableBucketARN, namespace, name, err := maintenanceTableTarget(r)
+ if err != nil {
+ return nil, err
+ }
+ maintenanceType, err := getDecodedPathParam(r, "type")
+ if err != nil {
+ return nil, err
+ }
+ req.TableBucketARN = tableBucketARN
+ req.Namespace = namespace
+ req.Name = name
+ req.Type = maintenanceType
+ return &req, nil
+}
+
+func buildGetTableMaintenanceConfigurationRequest(r *http.Request) (interface{}, error) {
+ tableBucketARN, namespace, name, err := maintenanceTableTarget(r)
+ if err != nil {
+ return nil, err
+ }
+ return &s3tables.GetTableMaintenanceConfigurationRequest{
+ TableBucketARN: tableBucketARN,
+ Namespace: namespace,
+ Name: name,
+ }, nil
+}
+
+func buildGetTableMaintenanceJobStatusRequest(r *http.Request) (interface{}, error) {
+ tableBucketARN, namespace, name, err := maintenanceTableTarget(r)
+ if err != nil {
+ return nil, err
+ }
+ return &s3tables.GetTableMaintenanceJobStatusRequest{
+ TableBucketARN: tableBucketARN,
+ Namespace: namespace,
+ Name: name,
+ }, nil
+}
diff --git a/weed/s3api/s3api_tables_maintenance_rest_test.go b/weed/s3api/s3api_tables_maintenance_rest_test.go
new file mode 100644
index 0000000000..0620db3369
--- /dev/null
+++ b/weed/s3api/s3api_tables_maintenance_rest_test.go
@@ -0,0 +1,137 @@
+package s3api
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gorilla/mux"
+
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
+)
+
+// The AWS CLI and SDK address these operations by REST path, not by
+// X-Amz-Target, so the paths have to match the published bindings exactly.
+func TestMaintenanceRestPathsMatchAWSBindings(t *testing.T) {
+ const arnPattern = "arn:aws:s3tables:[^/:]*:[^/:]*:bucket/[^/]+"
+
+ router := mux.NewRouter()
+ matched := ""
+ for _, route := range []struct {
+ method string
+ path string
+ operation string
+ }{
+ {http.MethodPut, "/buckets/{tableBucketARN:" + arnPattern + "}/maintenance/{type}", "PutTableBucketMaintenanceConfiguration"},
+ {http.MethodGet, "/buckets/{tableBucketARN:" + arnPattern + "}/maintenance", "GetTableBucketMaintenanceConfiguration"},
+ {http.MethodPut, "/tables/{tableBucketARN:" + arnPattern + "}/{namespace}/{name}/maintenance/{type}", "PutTableMaintenanceConfiguration"},
+ {http.MethodGet, "/tables/{tableBucketARN:" + arnPattern + "}/{namespace}/{name}/maintenance", "GetTableMaintenanceConfiguration"},
+ {http.MethodGet, "/tables/{tableBucketARN:" + arnPattern + "}/{namespace}/{name}/maintenance-job-status", "GetTableMaintenanceJobStatus"},
+ } {
+ operation := route.operation
+ router.Methods(route.method).Path(route.path).HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ matched = operation
+ })
+ }
+
+ cases := []struct {
+ method string
+ path string
+ want string
+ }{
+ {http.MethodPut, "/buckets/" + testTableBucketARN + "/maintenance/icebergUnreferencedFileRemoval", "PutTableBucketMaintenanceConfiguration"},
+ {http.MethodGet, "/buckets/" + testTableBucketARN + "/maintenance", "GetTableBucketMaintenanceConfiguration"},
+ {http.MethodPut, "/tables/" + testTableBucketARN + "/sales/orders/maintenance/icebergCompaction", "PutTableMaintenanceConfiguration"},
+ {http.MethodGet, "/tables/" + testTableBucketARN + "/sales/orders/maintenance", "GetTableMaintenanceConfiguration"},
+ {http.MethodGet, "/tables/" + testTableBucketARN + "/sales/orders/maintenance-job-status", "GetTableMaintenanceJobStatus"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.want, func(t *testing.T) {
+ matched = ""
+ router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(tc.method, tc.path, nil))
+ if matched != tc.want {
+ t.Errorf("path %s %s routed to %q, want %q", tc.method, tc.path, matched, tc.want)
+ }
+ })
+ }
+}
+
+func TestBuildPutTableMaintenanceConfigurationRequest(t *testing.T) {
+ body := `{"value":{"status":"enabled","settings":{"icebergCompaction":{"targetFileSizeMB":512}}}}`
+ req := httptest.NewRequest(http.MethodPut, "/tables/"+testTableBucketARN+"/sales/orders/maintenance/icebergCompaction", strings.NewReader(body))
+ req = mux.SetURLVars(req, map[string]string{
+ "tableBucketARN": testTableBucketARN,
+ "namespace": "sales",
+ "name": "orders",
+ "type": "icebergCompaction",
+ })
+
+ built, err := buildPutTableMaintenanceConfigurationRequest(req)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ got, ok := built.(*s3tables.PutTableMaintenanceConfigurationRequest)
+ if !ok {
+ t.Fatalf("unexpected request type %T", built)
+ }
+ if got.TableBucketARN != testTableBucketARN || got.Name != "orders" {
+ t.Errorf("path params not applied: %+v", got)
+ }
+ if len(got.Namespace) != 1 || got.Namespace[0] != "sales" {
+ t.Errorf("expected namespace [sales], got %v", got.Namespace)
+ }
+ if got.Type != s3tables.MaintenanceTypeIcebergCompaction {
+ t.Errorf("expected type from the path, got %q", got.Type)
+ }
+ if got.Value == nil || got.Value.Settings == nil || got.Value.Settings.IcebergCompaction == nil {
+ t.Fatalf("expected the body value decoded, got %+v", got.Value)
+ }
+ if size := got.Value.Settings.IcebergCompaction.TargetFileSizeMB; size == nil || *size != 512 {
+ t.Errorf("expected targetFileSizeMB=512, got %v", size)
+ }
+}
+
+func TestBuildPutTableBucketMaintenanceConfigurationRequest(t *testing.T) {
+ body := `{"value":{"status":"disabled"}}`
+ req := httptest.NewRequest(http.MethodPut, "/buckets/"+testTableBucketARN+"/maintenance/icebergUnreferencedFileRemoval", strings.NewReader(body))
+ req = mux.SetURLVars(req, map[string]string{
+ "tableBucketARN": testTableBucketARN,
+ "type": "icebergUnreferencedFileRemoval",
+ })
+
+ built, err := buildPutTableBucketMaintenanceConfigurationRequest(req)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ got := built.(*s3tables.PutTableBucketMaintenanceConfigurationRequest)
+ if got.TableBucketARN != testTableBucketARN {
+ t.Errorf("expected the ARN from the path, got %q", got.TableBucketARN)
+ }
+ if got.Type != s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval {
+ t.Errorf("expected the type from the path, got %q", got.Type)
+ }
+ if got.Value == nil || got.Value.Status != s3tables.MaintenanceStatusDisabled {
+ t.Errorf("expected the body value decoded, got %+v", got.Value)
+ }
+}
+
+func TestBuildMaintenanceRequestsRejectBadNamespace(t *testing.T) {
+ for _, build := range map[string]func(*http.Request) (interface{}, error){
+ "GetTableMaintenanceConfiguration": buildGetTableMaintenanceConfigurationRequest,
+ "GetTableMaintenanceJobStatus": buildGetTableMaintenanceJobStatusRequest,
+ } {
+ req := httptest.NewRequest(http.MethodGet, "/tables/"+testTableBucketARN+"/Bad/orders/maintenance", nil)
+ req = mux.SetURLVars(req, map[string]string{
+ "tableBucketARN": testTableBucketARN,
+ "namespace": "InvalidNamespace",
+ "name": "orders",
+ })
+ if _, err := build(req); err == nil {
+ t.Error("expected an invalid namespace to be rejected")
+ }
+ }
+}
diff --git a/weed/s3api/s3tables/filer_ops.go b/weed/s3api/s3tables/filer_ops.go
index d3b8c69167..eb991b9dd9 100644
--- a/weed/s3api/s3tables/filer_ops.go
+++ b/weed/s3api/s3tables/filer_ops.go
@@ -1,6 +1,7 @@
package s3tables
import (
+ "bytes"
"context"
"errors"
"fmt"
@@ -8,12 +9,19 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
)
var (
ErrAttributeNotFound = errors.New("attribute not found")
+ ErrConcurrentUpdate = errors.New("attribute changed concurrently")
)
+// extendedAttributeUpdateAttempts bounds the read-modify-write retry loop in
+// updateExtendedAttribute.
+const extendedAttributeUpdateAttempts = 5
+
// Filer operations - Common functions for interacting with the filer
// createDirectory creates a new directory at the specified path
@@ -56,85 +64,164 @@ func (h *S3TablesHandler) deleteEntryIfExists(ctx context.Context, client filer_
return filer_pb.DoRemove(ctx, client, dir, name, true, false, true, false, nil)
}
-// setExtendedAttribute sets an extended attribute on an existing entry
-func (h *S3TablesHandler) setExtendedAttribute(ctx context.Context, client filer_pb.SeaweedFilerClient, path, key string, data []byte) error {
+// mutateEntryExtended applies mutate to an entry's extended attributes and
+// writes the entry back, asserting that nothing on it changed in between.
+// UpdateEntry rewrites the whole entry from the snapshot read here, so an
+// unconditional write would delete an attribute a concurrent writer created.
+func (h *S3TablesHandler) mutateEntryExtended(
+ ctx context.Context,
+ client filer_pb.SeaweedFilerClient,
+ path string,
+ mutate func(extended map[string][]byte) error,
+) error {
dir, name := splitPath(path)
- // First, get the existing entry
- resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
- Directory: dir,
- Name: name,
- })
- if err != nil {
- return err
- }
+ for attempt := 0; attempt < extendedAttributeUpdateAttempts; attempt++ {
+ resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
+ Directory: dir,
+ Name: name,
+ })
+ if err != nil {
+ return err
+ }
- entry := resp.Entry
+ entry := resp.Entry
+ expected := snapshotExtended(entry.Extended)
+ if entry.Extended == nil {
+ entry.Extended = make(map[string][]byte)
+ }
+ if err := mutate(entry.Extended); err != nil {
+ return err
+ }
- // Update the extended attributes
- if entry.Extended == nil {
- entry.Extended = make(map[string][]byte)
+ _, err = client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
+ Directory: dir,
+ Entry: entry,
+ ExpectedExtended: expected,
+ })
+ if err == nil {
+ return nil
+ }
+ if status.Code(err) != codes.FailedPrecondition {
+ return err
+ }
}
- entry.Extended[key] = data
- // Save the updated entry
- return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
- Directory: dir,
- Entry: entry,
+ return fmt.Errorf("%w: %s", ErrConcurrentUpdate, path)
+}
+
+// setExtendedAttribute sets an extended attribute on an existing entry
+func (h *S3TablesHandler) setExtendedAttribute(ctx context.Context, client filer_pb.SeaweedFilerClient, path, key string, data []byte) error {
+ return h.mutateEntryExtended(ctx, client, path, func(extended map[string][]byte) error {
+ extended[key] = data
+ return nil
+ })
+}
+
+// setExtendedAttributes sets multiple extended attributes on an existing entry
+// in a single UpdateEntry, so callers don't leave the entry partially tagged.
+func (h *S3TablesHandler) setExtendedAttributes(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, attrs map[string][]byte) error {
+ return h.mutateEntryExtended(ctx, client, path, func(extended map[string][]byte) error {
+ for key, data := range attrs {
+ extended[key] = data
+ }
+ return nil
})
}
// removeExtendedAttributes deletes the given extended attributes from an entry,
// leaving the directory and its children intact.
func (h *S3TablesHandler) removeExtendedAttributes(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, keys ...string) error {
- dir, name := splitPath(path)
-
- resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
- Directory: dir,
- Name: name,
+ return h.mutateEntryExtended(ctx, client, path, func(extended map[string][]byte) error {
+ for _, key := range keys {
+ delete(extended, key)
+ }
+ return nil
})
- if err != nil {
- return err
- }
+}
- entry := resp.Entry
- if entry.Extended != nil {
+// removeExtendedAttributesIf drops the given attributes only while they still
+// hold the values the caller captured. A rename copies attributes to the
+// destination and then clears the source; without this, a write that landed in
+// between is deleted here and never reaches the new name.
+func (h *S3TablesHandler) removeExtendedAttributesIf(
+ ctx context.Context,
+ client filer_pb.SeaweedFilerClient,
+ path string,
+ expected map[string][]byte,
+ keys ...string,
+) error {
+ return h.mutateEntryExtended(ctx, client, path, func(extended map[string][]byte) error {
+ for key, want := range expected {
+ if !bytes.Equal(extended[key], want) {
+ return fmt.Errorf("%w: %s changed on %s", ErrConcurrentUpdate, key, path)
+ }
+ }
for _, key := range keys {
- delete(entry.Extended, key)
+ delete(extended, key)
}
- }
+ return nil
+ })
+}
- return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
- Directory: dir,
- Entry: entry,
+// updateExtendedAttribute applies mutate to the current value of key and writes
+// the result back. mutate runs again on each retry, so it always sees the
+// current value.
+func (h *S3TablesHandler) updateExtendedAttribute(
+ ctx context.Context,
+ client filer_pb.SeaweedFilerClient,
+ path, key string,
+ mutate func(current []byte) ([]byte, error),
+) error {
+ return h.mutateEntryExtended(ctx, client, path, func(extended map[string][]byte) error {
+ updated, err := mutate(extended[key])
+ if err != nil {
+ return err
+ }
+ extended[key] = updated
+ return nil
})
}
-// setExtendedAttributes sets multiple extended attributes on an existing entry
-// in a single UpdateEntry, so callers don't leave the entry partially tagged.
-func (h *S3TablesHandler) setExtendedAttributes(ctx context.Context, client filer_pb.SeaweedFilerClient, path string, attrs map[string][]byte) error {
- dir, name := splitPath(path)
+// s3tablesExtendedKeys is every attribute this package stores on a bucket or
+// table entry. A whole-entry write has to assert the absent ones too: a key
+// missing from the precondition is a key a concurrent writer can create and
+// this write will then delete.
+var s3tablesExtendedKeys = []string{
+ ExtendedKeyTableBucket,
+ ExtendedKeyMetadata,
+ ExtendedKeyMetadataVersion,
+ ExtendedKeyPolicy,
+ ExtendedKeyTags,
+ ExtendedKeyMaintenance,
+ ExtendedKeyMaintenanceStatus,
+ ExtendedKeyEntryType,
+}
- resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
- Directory: dir,
- Name: name,
- })
- if err != nil {
- return err
- }
+// SnapshotExtended captures an entry's attributes as an UpdateEntry
+// precondition, so a whole-entry write cannot silently revert or delete an
+// attribute a concurrent writer touched. Attributes absent at read time are
+// asserted absent, which fails the precondition if someone creates one first.
+func SnapshotExtended(extended map[string][]byte, keys ...string) map[string][]byte {
+ return snapshotExtended(extended, keys...)
+}
- entry := resp.Entry
- if entry.Extended == nil {
- entry.Extended = make(map[string][]byte)
+func snapshotExtended(extended map[string][]byte, keys ...string) map[string][]byte {
+ expected := make(map[string][]byte, len(extended)+len(s3tablesExtendedKeys))
+ for k, v := range extended {
+ expected[k] = v
}
- for key, data := range attrs {
- entry.Extended[key] = data
+ for _, k := range s3tablesExtendedKeys {
+ if _, ok := expected[k]; !ok {
+ expected[k] = nil
+ }
}
-
- return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
- Directory: dir,
- Entry: entry,
- })
+ for _, k := range keys {
+ if _, ok := expected[k]; !ok {
+ expected[k] = nil
+ }
+ }
+ return expected
}
// getExtendedAttribute gets an extended attribute from an entry
@@ -175,28 +262,9 @@ func (h *S3TablesHandler) lookupEntry(ctx context.Context, client filer_pb.Seawe
// deleteExtendedAttribute deletes an extended attribute from an entry
func (h *S3TablesHandler) deleteExtendedAttribute(ctx context.Context, client filer_pb.SeaweedFilerClient, path, key string) error {
- dir, name := splitPath(path)
-
- // Get the existing entry
- resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
- Directory: dir,
- Name: name,
- })
- if err != nil {
- return err
- }
-
- entry := resp.Entry
-
- // Remove the extended attribute
- if entry.Extended != nil {
- delete(entry.Extended, key)
- }
-
- // Save the updated entry
- return filer_pb.UpdateEntry(ctx, client, &filer_pb.UpdateEntryRequest{
- Directory: dir,
- Entry: entry,
+ return h.mutateEntryExtended(ctx, client, path, func(extended map[string][]byte) error {
+ delete(extended, key)
+ return nil
})
}
diff --git a/weed/s3api/s3tables/handler.go b/weed/s3api/s3tables/handler.go
index 6013a20b56..6b42c21cba 100644
--- a/weed/s3api/s3tables/handler.go
+++ b/weed/s3api/s3tables/handler.go
@@ -26,7 +26,12 @@ const (
ExtendedKeyMetadataVersion = "s3tables.metadataVersion"
ExtendedKeyPolicy = "s3tables.policy"
ExtendedKeyTags = "s3tables.tags"
- ExtendedKeyEntryType = "s3tables.entryType"
+ ExtendedKeyMaintenance = "s3tables.maintenance"
+ // Written by the maintenance worker, read by GetTableMaintenanceJobStatus.
+ // Separate from ExtendedKeyMaintenance so worker and operator writes do not
+ // contend on the same attribute.
+ ExtendedKeyMaintenanceStatus = "s3tables.maintenanceStatus"
+ ExtendedKeyEntryType = "s3tables.entryType"
// Entry-type marker values for ExtendedKeyEntryType. Absent or "table" means
// a table; views are stored like tables but tagged "view".
@@ -182,6 +187,18 @@ func (h *S3TablesHandler) HandleRequest(w http.ResponseWriter, r *http.Request,
case "DeleteTablePolicy":
err = h.handleDeleteTablePolicy(w, r, filerClient)
+ // Maintenance configuration operations
+ case "PutTableBucketMaintenanceConfiguration":
+ err = h.handlePutTableBucketMaintenanceConfiguration(w, r, filerClient)
+ case "GetTableBucketMaintenanceConfiguration":
+ err = h.handleGetTableBucketMaintenanceConfiguration(w, r, filerClient)
+ case "PutTableMaintenanceConfiguration":
+ err = h.handlePutTableMaintenanceConfiguration(w, r, filerClient)
+ case "GetTableMaintenanceConfiguration":
+ err = h.handleGetTableMaintenanceConfiguration(w, r, filerClient)
+ case "GetTableMaintenanceJobStatus":
+ err = h.handleGetTableMaintenanceJobStatus(w, r, filerClient)
+
// Tagging operations
case "TagResource":
err = h.handleTagResource(w, r, filerClient)
@@ -377,15 +394,20 @@ func (h *S3TablesHandler) writeError(w http.ResponseWriter, status int, code, me
// ARN generation helpers
func (h *S3TablesHandler) generateTableBucketARN(ownerAccountID, bucketName string) string {
- return fmt.Sprintf("arn:aws:s3tables:%s:%s:bucket/%s", h.region, ownerAccountID, bucketName)
+ return buildARN(h.region, ownerAccountID, fmt.Sprintf("bucket/%s", bucketName))
}
func (h *S3TablesHandler) generateTableARN(ownerAccountID, bucketName, tableID string) string {
- return fmt.Sprintf("arn:aws:s3tables:%s:%s:bucket/%s/table/%s", h.region, ownerAccountID, bucketName, tableID)
+ return buildARN(h.region, ownerAccountID, fmt.Sprintf("bucket/%s/table/%s", bucketName, tableID))
}
func (h *S3TablesHandler) generateViewARN(ownerAccountID, bucketName, viewID string) string {
- return fmt.Sprintf("arn:aws:s3tables:%s:%s:bucket/%s/view/%s", h.region, ownerAccountID, bucketName, viewID)
+ return buildARN(h.region, ownerAccountID, fmt.Sprintf("bucket/%s/view/%s", bucketName, viewID))
+}
+
+// generateS3BucketARN builds the plain S3 ARN used for IAM resource matching.
+func (h *S3TablesHandler) generateS3BucketARN(bucketName string) string {
+ return fmt.Sprintf("arn:%s:s3:::%s", arnPartitionForRegion(h.region), bucketName)
}
func isAuthError(err error) bool {
diff --git a/weed/s3api/s3tables/handler_bucket_create.go b/weed/s3api/s3tables/handler_bucket_create.go
index 37d692780b..6adf29c6cd 100644
--- a/weed/s3api/s3tables/handler_bucket_create.go
+++ b/weed/s3api/s3tables/handler_bucket_create.go
@@ -32,7 +32,7 @@ func (h *S3TablesHandler) handleCreateTableBucket(w http.ResponseWriter, r *http
useIAM := h.shouldUseIAM(r, identityActions, identityPolicyNames)
useLegacy := !useIAM
if useIAM {
- allowed, err := h.authorizeIAMAction(r, identityPolicyNames, "CreateTableBucket", h.generateTableBucketARN(principal, req.Name), fmt.Sprintf("arn:aws:s3:::%s", req.Name))
+ allowed, err := h.authorizeIAMAction(r, identityPolicyNames, "CreateTableBucket", h.generateTableBucketARN(principal, req.Name), h.generateS3BucketARN(req.Name))
if err != nil {
h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, "not authorized to create table buckets")
return NewAuthError("CreateTableBucket", principal, "not authorized to create table buckets")
diff --git a/weed/s3api/s3tables/handler_maintenance.go b/weed/s3api/s3tables/handler_maintenance.go
new file mode 100644
index 0000000000..f80f2ba09d
--- /dev/null
+++ b/weed/s3api/s3tables/handler_maintenance.go
@@ -0,0 +1,529 @@
+package s3tables
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+
+ "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+)
+
+// Maintenance types are scoped: AWS configures unreferenced file removal on the
+// table bucket and compaction and snapshot management on the table.
+var (
+ bucketMaintenanceTypes = map[string]bool{
+ MaintenanceTypeIcebergUnreferencedFileRemoval: true,
+ }
+ tableMaintenanceTypes = map[string]bool{
+ MaintenanceTypeIcebergCompaction: true,
+ MaintenanceTypeIcebergSnapshotManagement: true,
+ }
+)
+
+// handlePutTableBucketMaintenanceConfiguration sets a maintenance configuration on a table bucket
+func (h *S3TablesHandler) handlePutTableBucketMaintenanceConfiguration(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
+ var req PutTableBucketMaintenanceConfigurationRequest
+ if err := h.readRequestBody(r, &req); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ if req.TableBucketARN == "" {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, "tableBucketARN is required")
+ return fmt.Errorf("tableBucketARN is required")
+ }
+
+ bucketName, err := parseBucketNameFromARN(req.TableBucketARN)
+ if err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ if err := validateMaintenanceValue(req.Type, bucketMaintenanceTypes, req.Value); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ if _, err := h.authorizeMaintenanceBucket(r, filerClient, "PutTableBucketMaintenanceConfiguration", bucketName); err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
+ return err
+ }
+
+ if err := h.putMaintenanceConfiguration(r, filerClient, GetTableBucketPath(bucketName), req.Type, req.Value); err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
+ return err
+ }
+
+ h.writeJSON(w, http.StatusOK, nil)
+ return nil
+}
+
+// handleGetTableBucketMaintenanceConfiguration gets the maintenance configuration of a table bucket
+func (h *S3TablesHandler) handleGetTableBucketMaintenanceConfiguration(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
+ var req GetTableBucketMaintenanceConfigurationRequest
+ if err := h.readRequestBody(r, &req); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ if req.TableBucketARN == "" {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, "tableBucketARN is required")
+ return fmt.Errorf("tableBucketARN is required")
+ }
+
+ bucketName, err := parseBucketNameFromARN(req.TableBucketARN)
+ if err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ bucketARN, err := h.authorizeMaintenanceBucket(r, filerClient, "GetTableBucketMaintenanceConfiguration", bucketName)
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
+ return err
+ }
+
+ config, err := h.readMaintenanceConfiguration(r, filerClient, GetTableBucketPath(bucketName))
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
+ return err
+ }
+
+ h.writeJSON(w, http.StatusOK, &GetTableBucketMaintenanceConfigurationResponse{
+ TableBucketARN: bucketARN,
+ Configuration: config,
+ })
+ return nil
+}
+
+// handlePutTableMaintenanceConfiguration sets a maintenance configuration on a table
+func (h *S3TablesHandler) handlePutTableMaintenanceConfiguration(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
+ var req PutTableMaintenanceConfigurationRequest
+ if err := h.readRequestBody(r, &req); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ bucketName, namespaceName, tableName, err := h.parseTableTarget(req.TableBucketARN, req.Namespace, req.Name)
+ if err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ if err := validateMaintenanceValue(req.Type, tableMaintenanceTypes, req.Value); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ if _, err := h.authorizeMaintenanceTable(r, filerClient, "PutTableMaintenanceConfiguration", bucketName, namespaceName, tableName); err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+
+ tablePath := GetTablePath(bucketName, namespaceName, tableName)
+ if err := h.putMaintenanceConfiguration(r, filerClient, tablePath, req.Type, req.Value); err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+
+ h.writeJSON(w, http.StatusOK, nil)
+ return nil
+}
+
+// handleGetTableMaintenanceConfiguration gets the maintenance configuration of a table
+func (h *S3TablesHandler) handleGetTableMaintenanceConfiguration(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
+ var req GetTableMaintenanceConfigurationRequest
+ if err := h.readRequestBody(r, &req); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ bucketName, namespaceName, tableName, err := h.parseTableTarget(req.TableBucketARN, req.Namespace, req.Name)
+ if err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ tableARN, err := h.authorizeMaintenanceTable(r, filerClient, "GetTableMaintenanceConfiguration", bucketName, namespaceName, tableName)
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+
+ tablePath := GetTablePath(bucketName, namespaceName, tableName)
+ config, err := h.readMaintenanceConfiguration(r, filerClient, tablePath)
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+
+ h.writeJSON(w, http.StatusOK, &GetTableMaintenanceConfigurationResponse{
+ TableARN: tableARN,
+ Namespace: []string{namespaceName},
+ Name: tableName,
+ Configuration: config,
+ })
+ return nil
+}
+
+// handleGetTableMaintenanceJobStatus reports the outcome of the last maintenance run on a table
+func (h *S3TablesHandler) handleGetTableMaintenanceJobStatus(w http.ResponseWriter, r *http.Request, filerClient FilerClient) error {
+ var req GetTableMaintenanceJobStatusRequest
+ if err := h.readRequestBody(r, &req); err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ bucketName, namespaceName, tableName, err := h.parseTableTarget(req.TableBucketARN, req.Namespace, req.Name)
+ if err != nil {
+ h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, err.Error())
+ return err
+ }
+
+ tableARN, err := h.authorizeMaintenanceTable(r, filerClient, "GetTableMaintenanceJobStatus", bucketName, namespaceName, tableName)
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+
+ tablePath := GetTablePath(bucketName, namespaceName, tableName)
+
+ // Unreferenced file removal is configured on the bucket, so a bucket-level
+ // disable has to show up here as Disabled rather than a stale table status.
+ bucketConfig, err := h.readMaintenanceConfiguration(r, filerClient, GetTableBucketPath(bucketName))
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchBucket, fmt.Sprintf("table bucket %s not found", bucketName))
+ return err
+ }
+ tableConfig, err := h.readMaintenanceConfiguration(r, filerClient, tablePath)
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+ config := MergeMaintenanceConfiguration(bucketConfig, tableConfig)
+
+ recorded := MaintenanceJobStatus{}
+ err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+ data, err := h.getExtendedAttribute(r.Context(), client, tablePath, ExtendedKeyMaintenanceStatus)
+ if err != nil {
+ if errors.Is(err, ErrAttributeNotFound) {
+ return nil
+ }
+ return err
+ }
+ return json.Unmarshal(data, &recorded)
+ })
+ if err != nil {
+ h.writeMaintenanceError(w, err, ErrCodeNoSuchTable, fmt.Sprintf("table %s not found", tableName))
+ return err
+ }
+
+ h.writeJSON(w, http.StatusOK, &GetTableMaintenanceJobStatusResponse{
+ TableARN: tableARN,
+ Status: buildJobStatusResponse(recorded, config),
+ })
+ return nil
+}
+
+// buildJobStatusResponse reports every job type: what the worker recorded, or
+// Disabled when the configuration switched the type off, or Not_Yet_Run.
+func buildJobStatusResponse(recorded MaintenanceJobStatus, config MaintenanceConfiguration) MaintenanceJobStatus {
+ jobTypes := []string{
+ MaintenanceTypeIcebergCompaction,
+ MaintenanceTypeIcebergSnapshotManagement,
+ MaintenanceTypeIcebergUnreferencedFileRemoval,
+ }
+
+ status := make(MaintenanceJobStatus, len(jobTypes))
+ for _, jobType := range jobTypes {
+ if value, ok := config[jobType]; ok && value != nil && value.Status == MaintenanceStatusDisabled {
+ status[jobType] = &MaintenanceJobStatusValue{Status: MaintenanceJobStatusDisabled}
+ continue
+ }
+ if value, ok := recorded[jobType]; ok && value != nil {
+ status[jobType] = value
+ continue
+ }
+ status[jobType] = &MaintenanceJobStatusValue{Status: MaintenanceJobStatusNotYetRun}
+ }
+ return status
+}
+
+// putMaintenanceConfiguration merges one maintenance type into the stored
+// configuration, leaving the other types alone. The write checks the catalog
+// identity in the same conditional mutation, so it cannot land on a name a
+// concurrent rename or delete has already soft-deleted.
+func (h *S3TablesHandler) putMaintenanceConfiguration(
+ r *http.Request,
+ filerClient FilerClient,
+ resourcePath, maintenanceType string,
+ value *MaintenanceConfigurationValue,
+) error {
+ return filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+ return h.mutateEntryExtended(r.Context(), client, resourcePath, func(extended map[string][]byte) error {
+ if len(extended[ExtendedKeyMetadata]) == 0 {
+ return fmt.Errorf("%w: %s", filer_pb.ErrNotFound, resourcePath)
+ }
+
+ config := MaintenanceConfiguration{}
+ if current := extended[ExtendedKeyMaintenance]; len(current) > 0 {
+ if err := json.Unmarshal(current, &config); err != nil {
+ return fmt.Errorf("failed to unmarshal maintenance configuration: %w", err)
+ }
+ }
+ config[maintenanceType] = value
+
+ data, err := json.Marshal(config)
+ if err != nil {
+ return err
+ }
+ extended[ExtendedKeyMaintenance] = data
+ return nil
+ })
+ })
+}
+
+// readMaintenanceConfiguration returns the stored configuration, or an empty
+// one when the resource has never been configured.
+func (h *S3TablesHandler) readMaintenanceConfiguration(r *http.Request, filerClient FilerClient, resourcePath string) (MaintenanceConfiguration, error) {
+ config := MaintenanceConfiguration{}
+
+ err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+ data, err := h.getExtendedAttribute(r.Context(), client, resourcePath, ExtendedKeyMaintenance)
+ if err != nil {
+ if errors.Is(err, ErrAttributeNotFound) {
+ return nil
+ }
+ return err
+ }
+ return json.Unmarshal(data, &config)
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ return config, nil
+}
+
+// parseTableTarget validates the bucket/namespace/table triple every
+// table-scoped maintenance request carries.
+func (h *S3TablesHandler) parseTableTarget(tableBucketARN string, namespace []string, name string) (bucketName, namespaceName, tableName string, err error) {
+ if tableBucketARN == "" || len(namespace) == 0 || name == "" {
+ return "", "", "", fmt.Errorf("tableBucketARN, namespace, and name are required")
+ }
+ if namespaceName, err = validateNamespace(namespace); err != nil {
+ return "", "", "", err
+ }
+ if bucketName, err = parseBucketNameFromARN(tableBucketARN); err != nil {
+ return "", "", "", err
+ }
+ if tableName, err = validateTableName(name); err != nil {
+ return "", "", "", err
+ }
+ return bucketName, namespaceName, tableName, nil
+}
+
+// authorizeMaintenanceBucket checks the caller may perform operation on the
+// table bucket, returning the bucket ARN.
+func (h *S3TablesHandler) authorizeMaintenanceBucket(r *http.Request, filerClient FilerClient, operation, bucketName string) (string, error) {
+ bucketPath := GetTableBucketPath(bucketName)
+
+ var bucketMetadata tableBucketMetadata
+ var bucketPolicy string
+ err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+ data, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata)
+ if err != nil {
+ return err
+ }
+ if err := json.Unmarshal(data, &bucketMetadata); err != nil {
+ return fmt.Errorf("failed to unmarshal bucket metadata: %w", err)
+ }
+ bucketPolicy, err = h.readBucketPolicy(r, client, bucketPath)
+ return err
+ })
+ if err != nil {
+ return "", err
+ }
+
+ bucketARN := h.generateTableBucketARN(bucketMetadata.OwnerAccountID, bucketName)
+ principal := h.getAccountID(r)
+ if !CheckPermissionWithContext(operation, principal, bucketMetadata.OwnerAccountID, bucketPolicy, bucketARN, &PolicyContext{
+ TableBucketName: bucketName,
+ IdentityActions: getIdentityActions(r),
+ DefaultAllow: h.defaultAllowFor(r),
+ }) {
+ return "", NewAuthError(operation, principal, "not authorized to "+operation)
+ }
+
+ return bucketARN, nil
+}
+
+// authorizeMaintenanceTable checks the caller may perform operation on the
+// table, returning the table ARN.
+func (h *S3TablesHandler) authorizeMaintenanceTable(r *http.Request, filerClient FilerClient, operation, bucketName, namespaceName, tableName string) (string, error) {
+ tablePath := GetTablePath(bucketName, namespaceName, tableName)
+ bucketPath := GetTableBucketPath(bucketName)
+
+ var metadata tableMetadataInternal
+ var bucketPolicy string
+ err := filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+ data, err := h.getExtendedAttribute(r.Context(), client, tablePath, ExtendedKeyMetadata)
+ if err != nil {
+ return err
+ }
+ if err := json.Unmarshal(data, &metadata); err != nil {
+ return fmt.Errorf("failed to unmarshal table metadata: %w", err)
+ }
+ bucketPolicy, err = h.readBucketPolicy(r, client, bucketPath)
+ return err
+ })
+ if err != nil {
+ return "", err
+ }
+
+ tableARN := h.generateTableARN(metadata.OwnerAccountID, bucketName, namespaceName+"/"+tableName)
+ principal := h.getAccountID(r)
+ if !CheckPermissionWithContext(operation, principal, metadata.OwnerAccountID, bucketPolicy, tableARN, &PolicyContext{
+ TableBucketName: bucketName,
+ Namespace: namespaceName,
+ TableName: tableName,
+ IdentityActions: getIdentityActions(r),
+ DefaultAllow: h.defaultAllowFor(r),
+ }) {
+ return "", NewAuthError(operation, principal, "not authorized to "+operation)
+ }
+
+ return tableARN, nil
+}
+
+// readBucketPolicy returns the bucket policy, or an empty string when the
+// bucket has none.
+func (h *S3TablesHandler) readBucketPolicy(r *http.Request, client filer_pb.SeaweedFilerClient, bucketPath string) (string, error) {
+ data, err := h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyPolicy)
+ if err != nil {
+ if errors.Is(err, ErrAttributeNotFound) {
+ return "", nil
+ }
+ return "", fmt.Errorf("failed to read bucket policy: %w", err)
+ }
+ return string(data), nil
+}
+
+// writeMaintenanceError maps the shared failure modes of the maintenance
+// handlers onto responses.
+func (h *S3TablesHandler) writeMaintenanceError(w http.ResponseWriter, err error, notFoundCode, notFoundMessage string) {
+ switch {
+ case errors.Is(err, filer_pb.ErrNotFound):
+ h.writeError(w, http.StatusNotFound, notFoundCode, notFoundMessage)
+ case isAuthError(err):
+ h.writeError(w, http.StatusForbidden, ErrCodeAccessDenied, err.Error())
+ case errors.Is(err, ErrConcurrentUpdate):
+ h.writeError(w, http.StatusConflict, ErrCodeConflict, "maintenance configuration changed concurrently, retry the request")
+ default:
+ h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, err.Error())
+ }
+}
+
+// validateMaintenanceValue rejects a type that does not belong to the scope and
+// settings that do not name that same type.
+func validateMaintenanceValue(maintenanceType string, allowed map[string]bool, value *MaintenanceConfigurationValue) error {
+ if maintenanceType == "" {
+ return fmt.Errorf("type is required")
+ }
+ if !allowed[maintenanceType] {
+ return fmt.Errorf("unsupported maintenance type %q", maintenanceType)
+ }
+ if value == nil {
+ return fmt.Errorf("value is required")
+ }
+
+ switch value.Status {
+ case MaintenanceStatusEnabled, MaintenanceStatusDisabled:
+ case "":
+ return fmt.Errorf("value.status is required")
+ default:
+ return fmt.Errorf("invalid value.status %q, expected %q or %q", value.Status, MaintenanceStatusEnabled, MaintenanceStatusDisabled)
+ }
+
+ if value.Settings != nil && !settingsMatchType(maintenanceType, value.Settings) {
+ return fmt.Errorf("value.settings must only contain %s", maintenanceType)
+ }
+ return validateMaintenanceSettings(value.Settings)
+}
+
+// AWS bounds every maintenance setting to a positive 32-bit value. Accepting
+// anything else would store a number the worker then ignores or saturates, so
+// the configuration read back would not be the one that runs.
+const (
+ maintenanceSettingMin int64 = 1
+ maintenanceSettingMax int64 = 2147483647
+)
+
+func validateMaintenanceSettings(settings *MaintenanceSettings) error {
+ if settings == nil {
+ return nil
+ }
+
+ if c := settings.IcebergCompaction; c != nil {
+ if err := validateCompactionStrategy(c.Strategy); err != nil {
+ return err
+ }
+ if err := validateMaintenanceSetting("targetFileSizeMB", c.TargetFileSizeMB); err != nil {
+ return err
+ }
+ }
+ if m := settings.IcebergSnapshotManagement; m != nil {
+ if err := validateMaintenanceSetting("minSnapshotsToKeep", m.MinSnapshotsToKeep); err != nil {
+ return err
+ }
+ if err := validateMaintenanceSetting("maxSnapshotAgeHours", m.MaxSnapshotAgeHours); err != nil {
+ return err
+ }
+ }
+ if u := settings.IcebergUnreferencedFileRemoval; u != nil {
+ if err := validateMaintenanceSetting("unreferencedDays", u.UnreferencedDays); err != nil {
+ return err
+ }
+ if err := validateMaintenanceSetting("nonCurrentDays", u.NonCurrentDays); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func validateMaintenanceSetting(name string, value *int64) error {
+ if value == nil {
+ return nil
+ }
+ if *value < maintenanceSettingMin || *value > maintenanceSettingMax {
+ return fmt.Errorf("%s must be between %d and %d, got %d", name, maintenanceSettingMin, maintenanceSettingMax, *value)
+ }
+ return nil
+}
+
+// validateCompactionStrategy rejects a strategy the maintenance worker cannot
+// carry out, rather than accepting it and quietly compacting some other way.
+func validateCompactionStrategy(strategy string) error {
+ switch strategy {
+ case "", CompactionStrategyAuto, CompactionStrategyBinpack, CompactionStrategySort:
+ return nil
+ case CompactionStrategyZOrder:
+ return fmt.Errorf("compaction strategy %q is not supported", strategy)
+ default:
+ return fmt.Errorf("invalid compaction strategy %q, expected one of %q, %q, %q",
+ strategy, CompactionStrategyAuto, CompactionStrategyBinpack, CompactionStrategySort)
+ }
+}
+
+func settingsMatchType(maintenanceType string, settings *MaintenanceSettings) bool {
+ switch maintenanceType {
+ case MaintenanceTypeIcebergCompaction:
+ return settings.IcebergSnapshotManagement == nil && settings.IcebergUnreferencedFileRemoval == nil
+ case MaintenanceTypeIcebergSnapshotManagement:
+ return settings.IcebergCompaction == nil && settings.IcebergUnreferencedFileRemoval == nil
+ case MaintenanceTypeIcebergUnreferencedFileRemoval:
+ return settings.IcebergCompaction == nil && settings.IcebergSnapshotManagement == nil
+ }
+ return false
+}
diff --git a/weed/s3api/s3tables/handler_maintenance_test.go b/weed/s3api/s3tables/handler_maintenance_test.go
new file mode 100644
index 0000000000..4e427bdf74
--- /dev/null
+++ b/weed/s3api/s3tables/handler_maintenance_test.go
@@ -0,0 +1,476 @@
+package s3tables
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func settingPtr(v int64) *int64 { return &v }
+
+func TestValidateMaintenanceValueAcceptsScopedTypes(t *testing.T) {
+ err := validateMaintenanceValue(MaintenanceTypeIcebergCompaction, tableMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergCompaction: &IcebergCompactionSettings{TargetFileSizeMB: settingPtr(512)}},
+ })
+ if err != nil {
+ t.Errorf("expected compaction accepted on a table, got %v", err)
+ }
+
+ err = validateMaintenanceValue(MaintenanceTypeIcebergUnreferencedFileRemoval, bucketMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusDisabled,
+ })
+ if err != nil {
+ t.Errorf("expected unreferenced file removal accepted on a bucket, got %v", err)
+ }
+}
+
+func TestValidateMaintenanceValueRejectsWrongScope(t *testing.T) {
+ if err := validateMaintenanceValue(MaintenanceTypeIcebergCompaction, bucketMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ }); err == nil {
+ t.Error("expected compaction rejected on a table bucket")
+ }
+
+ if err := validateMaintenanceValue(MaintenanceTypeIcebergUnreferencedFileRemoval, tableMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ }); err == nil {
+ t.Error("expected unreferenced file removal rejected on a table")
+ }
+}
+
+func TestValidateMaintenanceValueRejectsBadInput(t *testing.T) {
+ cases := map[string]struct {
+ maintenanceType string
+ value *MaintenanceConfigurationValue
+ }{
+ "empty type": {"", &MaintenanceConfigurationValue{Status: MaintenanceStatusEnabled}},
+ "unknown type": {"icebergSomethingElse", &MaintenanceConfigurationValue{Status: MaintenanceStatusEnabled}},
+ "nil value": {MaintenanceTypeIcebergCompaction, nil},
+ "no status": {MaintenanceTypeIcebergCompaction, &MaintenanceConfigurationValue{}},
+ "bad status": {MaintenanceTypeIcebergCompaction, &MaintenanceConfigurationValue{Status: "Enabled"}},
+ "settings for another type": {MaintenanceTypeIcebergCompaction, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergSnapshotManagement: &IcebergSnapshotManagementSettings{MinSnapshotsToKeep: settingPtr(3)}},
+ }},
+ }
+
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ if err := validateMaintenanceValue(tc.maintenanceType, tableMaintenanceTypes, tc.value); err == nil {
+ t.Error("expected rejection")
+ }
+ })
+ }
+}
+
+// The stored attribute is the wire shape, so Get can hand it straight back.
+func TestMaintenanceConfigurationRoundTrip(t *testing.T) {
+ original := MaintenanceConfiguration{
+ MaintenanceTypeIcebergCompaction: {
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergCompaction: &IcebergCompactionSettings{TargetFileSizeMB: settingPtr(512)}},
+ },
+ MaintenanceTypeIcebergSnapshotManagement: {
+ Status: MaintenanceStatusDisabled,
+ Settings: &MaintenanceSettings{IcebergSnapshotManagement: &IcebergSnapshotManagementSettings{
+ MinSnapshotsToKeep: settingPtr(3),
+ MaxSnapshotAgeHours: settingPtr(120),
+ }},
+ },
+ }
+
+ data, err := json.Marshal(original)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+
+ var decoded MaintenanceConfiguration
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+
+ compaction := decoded[MaintenanceTypeIcebergCompaction]
+ if compaction == nil || compaction.Settings == nil || compaction.Settings.IcebergCompaction == nil {
+ t.Fatalf("expected compaction settings, got %s", data)
+ }
+ if got := compaction.Settings.IcebergCompaction.TargetFileSizeMB; got == nil || *got != 512 {
+ t.Errorf("expected targetFileSizeMB=512, got %v", got)
+ }
+
+ snapshots := decoded[MaintenanceTypeIcebergSnapshotManagement]
+ if snapshots == nil || snapshots.Status != MaintenanceStatusDisabled {
+ t.Fatalf("expected snapshot management disabled, got %s", data)
+ }
+ if got := snapshots.Settings.IcebergSnapshotManagement.MaxSnapshotAgeHours; got == nil || *got != 120 {
+ t.Errorf("expected maxSnapshotAgeHours=120, got %v", got)
+ }
+}
+
+// Putting one type must not drop the others already stored.
+func TestMaintenanceConfigurationMergeKeepsOtherTypes(t *testing.T) {
+ stored, err := json.Marshal(MaintenanceConfiguration{
+ MaintenanceTypeIcebergCompaction: {Status: MaintenanceStatusEnabled},
+ })
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+
+ config := MaintenanceConfiguration{}
+ if err := json.Unmarshal(stored, &config); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ config[MaintenanceTypeIcebergSnapshotManagement] = &MaintenanceConfigurationValue{Status: MaintenanceStatusDisabled}
+
+ if len(config) != 2 {
+ t.Errorf("expected both types retained, got %+v", config)
+ }
+ if config[MaintenanceTypeIcebergCompaction].Status != MaintenanceStatusEnabled {
+ t.Error("expected the existing compaction entry preserved")
+ }
+}
+
+func TestParseTableTarget(t *testing.T) {
+ h := NewS3TablesHandler()
+ arn := h.generateTableBucketARN(DefaultAccountID, "analytics")
+
+ bucketName, namespaceName, tableName, err := h.parseTableTarget(arn, []string{"sales"}, "orders")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if bucketName != "analytics" || namespaceName != "sales" || tableName != "orders" {
+ t.Errorf("got %q/%q/%q", bucketName, namespaceName, tableName)
+ }
+
+ for name, tc := range map[string]struct {
+ arn string
+ namespace []string
+ table string
+ }{
+ "missing arn": {"", []string{"sales"}, "orders"},
+ "missing namespace": {arn, nil, "orders"},
+ "missing name": {arn, []string{"sales"}, ""},
+ "bad arn": {"not-an-arn", []string{"sales"}, "orders"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if _, _, _, err := h.parseTableTarget(tc.arn, tc.namespace, tc.table); err == nil {
+ t.Error("expected rejection")
+ }
+ })
+ }
+}
+
+func TestBuildJobStatusResponseReportsEveryType(t *testing.T) {
+ status := buildJobStatusResponse(nil, nil)
+ if len(status) != 3 {
+ t.Fatalf("expected all three job types reported, got %v", status)
+ }
+ for jobType, value := range status {
+ if value.Status != MaintenanceJobStatusNotYetRun {
+ t.Errorf("expected %s not yet run, got %q", jobType, value.Status)
+ }
+ }
+}
+
+func TestBuildJobStatusResponseDisabledBeatsRecorded(t *testing.T) {
+ recorded := MaintenanceJobStatus{
+ MaintenanceTypeIcebergCompaction: {Status: MaintenanceJobStatusSuccessful},
+ MaintenanceTypeIcebergSnapshotManagement: {Status: MaintenanceJobStatusFailed, FailureMessage: "boom"},
+ }
+ config := MaintenanceConfiguration{
+ MaintenanceTypeIcebergCompaction: {Status: MaintenanceStatusDisabled},
+ }
+
+ status := buildJobStatusResponse(recorded, config)
+ if status[MaintenanceTypeIcebergCompaction].Status != MaintenanceJobStatusDisabled {
+ t.Errorf("expected a disabled type reported as disabled, got %q", status[MaintenanceTypeIcebergCompaction].Status)
+ }
+ if status[MaintenanceTypeIcebergSnapshotManagement].FailureMessage != "boom" {
+ t.Error("expected the recorded failure preserved")
+ }
+ if status[MaintenanceTypeIcebergUnreferencedFileRemoval].Status != MaintenanceJobStatusNotYetRun {
+ t.Error("expected an unrun type reported as not yet run")
+ }
+}
+
+// A strategy the worker cannot carry out must be rejected, not accepted and
+// silently compacted some other way.
+func TestValidateMaintenanceValueCompactionStrategy(t *testing.T) {
+ for _, strategy := range []string{"", CompactionStrategyAuto, CompactionStrategyBinpack, CompactionStrategySort} {
+ if err := validateMaintenanceValue(MaintenanceTypeIcebergCompaction, tableMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergCompaction: &IcebergCompactionSettings{Strategy: strategy}},
+ }); err != nil {
+ t.Errorf("expected strategy %q accepted, got %v", strategy, err)
+ }
+ }
+
+ for _, strategy := range []string{CompactionStrategyZOrder, "nonsense"} {
+ if err := validateMaintenanceValue(MaintenanceTypeIcebergCompaction, tableMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergCompaction: &IcebergCompactionSettings{Strategy: strategy}},
+ }); err == nil {
+ t.Errorf("expected strategy %q rejected", strategy)
+ }
+ }
+}
+
+// Put then Get must return the strategy unchanged.
+func TestMaintenanceConfigurationPreservesStrategy(t *testing.T) {
+ data, err := json.Marshal(MaintenanceConfiguration{
+ MaintenanceTypeIcebergCompaction: {
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergCompaction: &IcebergCompactionSettings{Strategy: CompactionStrategySort, TargetFileSizeMB: settingPtr(512)}},
+ },
+ })
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+
+ var decoded MaintenanceConfiguration
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if got := decoded[MaintenanceTypeIcebergCompaction].Settings.IcebergCompaction.Strategy; got != CompactionStrategySort {
+ t.Errorf("expected the strategy preserved, got %q", got)
+ }
+}
+
+// Unreferenced file removal is configured on the bucket, so a bucket-level
+// disable has to surface here rather than a stale table status.
+func TestBuildJobStatusResponseHonoursBucketDisable(t *testing.T) {
+ recorded := MaintenanceJobStatus{
+ MaintenanceTypeIcebergUnreferencedFileRemoval: {Status: MaintenanceJobStatusSuccessful},
+ }
+ bucketConfig := MaintenanceConfiguration{
+ MaintenanceTypeIcebergUnreferencedFileRemoval: {Status: MaintenanceStatusDisabled},
+ }
+
+ status := buildJobStatusResponse(recorded, MergeMaintenanceConfiguration(bucketConfig, nil))
+ if got := status[MaintenanceTypeIcebergUnreferencedFileRemoval].Status; got != MaintenanceJobStatusDisabled {
+ t.Errorf("expected Disabled from the bucket configuration, got %q", got)
+ }
+}
+
+func TestMergeMaintenanceConfiguration(t *testing.T) {
+ bucket := MaintenanceConfiguration{
+ MaintenanceTypeIcebergUnreferencedFileRemoval: {Status: MaintenanceStatusEnabled},
+ MaintenanceTypeIcebergCompaction: {Status: MaintenanceStatusEnabled},
+ }
+ table := MaintenanceConfiguration{
+ MaintenanceTypeIcebergCompaction: {Status: MaintenanceStatusDisabled},
+ }
+
+ merged := MergeMaintenanceConfiguration(bucket, table)
+ if merged[MaintenanceTypeIcebergCompaction].Status != MaintenanceStatusDisabled {
+ t.Error("expected the table entry to win")
+ }
+ if merged[MaintenanceTypeIcebergUnreferencedFileRemoval].Status != MaintenanceStatusEnabled {
+ t.Error("expected the bucket-only entry retained")
+ }
+ if got := MergeMaintenanceConfiguration(nil, table); len(got) != 1 {
+ t.Errorf("expected the table configuration passed through, got %v", got)
+ }
+ if got := MergeMaintenanceConfiguration(bucket, nil); len(got) != 2 {
+ t.Errorf("expected the bucket configuration passed through, got %v", got)
+ }
+}
+
+// UpdateEntry rewrites the whole entry, so the precondition has to cover every
+// attribute this package stores — including the ones absent right now, which a
+// concurrent writer can create and this write would then delete.
+func TestSnapshotExtendedCoversEveryAttribute(t *testing.T) {
+ extended := map[string][]byte{
+ ExtendedKeyMetadata: []byte(`{"a":1}`),
+ ExtendedKeyMaintenance: []byte(`{"icebergCompaction":{"status":"disabled"}}`),
+ }
+
+ expected := SnapshotExtended(extended, ExtendedKeyMaintenanceStatus)
+
+ for key, want := range extended {
+ if string(expected[key]) != string(want) {
+ t.Errorf("attribute %s not carried into the precondition", key)
+ }
+ }
+ for _, key := range s3tablesExtendedKeys {
+ if _, ok := expected[key]; !ok {
+ t.Errorf("attribute %s missing from the precondition", key)
+ }
+ }
+
+ // The absent ones are asserted absent, so a concurrent create fails the write.
+ for _, key := range []string{ExtendedKeyMaintenanceStatus, ExtendedKeyPolicy, ExtendedKeyTags} {
+ if got, ok := expected[key]; !ok || len(got) != 0 {
+ t.Errorf("expected %s asserted absent, got %v", key, got)
+ }
+ }
+
+ // Mutating the snapshot must not disturb the entry it came from.
+ expected[ExtendedKeyMetadata] = []byte("changed")
+ if string(extended[ExtendedKeyMetadata]) != `{"a":1}` {
+ t.Error("expected the source map left alone")
+ }
+}
+
+// The regression this closes: a maintenance configuration that did not exist
+// when the writer read the entry must still be asserted, or a first-time
+// disable lands between the read and the write and gets erased.
+func TestSnapshotExtendedAssertsAbsentMaintenanceKey(t *testing.T) {
+ expected := SnapshotExtended(map[string][]byte{ExtendedKeyMetadata: []byte(`{}`)})
+
+ value, ok := expected[ExtendedKeyMaintenance]
+ if !ok {
+ t.Fatal("expected the maintenance key asserted even when absent")
+ }
+ if len(value) != 0 {
+ t.Errorf("expected an absent assertion, got %v", value)
+ }
+}
+
+// AWS bounds every numeric setting to 1..2147483647. Accepting anything else
+// would store a value the worker ignores or saturates, so the configuration
+// read back would not be the one that runs.
+func TestValidateMaintenanceSettingRange(t *testing.T) {
+ compaction := func(v *int64) error {
+ return validateMaintenanceValue(MaintenanceTypeIcebergCompaction, tableMaintenanceTypes, &MaintenanceConfigurationValue{
+ Status: MaintenanceStatusEnabled,
+ Settings: &MaintenanceSettings{IcebergCompaction: &IcebergCompactionSettings{TargetFileSizeMB: v}},
+ })
+ }
+
+ if err := compaction(nil); err != nil {
+ t.Errorf("expected an unset setting accepted, got %v", err)
+ }
+ for _, v := range []int64{1, 512, maintenanceSettingMax} {
+ if err := compaction(settingPtr(v)); err != nil {
+ t.Errorf("expected %d accepted, got %v", v, err)
+ }
+ }
+ for _, v := range []int64{0, -1, maintenanceSettingMax + 1, 1 << 62} {
+ if err := compaction(settingPtr(v)); err == nil {
+ t.Errorf("expected %d rejected", v)
+ }
+ }
+}
+
+func TestValidateMaintenanceSettingRangeCoversEveryField(t *testing.T) {
+ cases := map[string]*MaintenanceSettings{
+ "minSnapshotsToKeep": {IcebergSnapshotManagement: &IcebergSnapshotManagementSettings{MinSnapshotsToKeep: settingPtr(0)}},
+ "maxSnapshotAgeHours": {IcebergSnapshotManagement: &IcebergSnapshotManagementSettings{MaxSnapshotAgeHours: settingPtr(-5)}},
+ "unreferencedDays": {IcebergUnreferencedFileRemoval: &IcebergUnreferencedFileRemovalSettings{UnreferencedDays: settingPtr(maintenanceSettingMax + 1)}},
+ "nonCurrentDays": {IcebergUnreferencedFileRemoval: &IcebergUnreferencedFileRemovalSettings{NonCurrentDays: settingPtr(0)}},
+ }
+
+ for name, settings := range cases {
+ t.Run(name, func(t *testing.T) {
+ if err := validateMaintenanceSettings(settings); err == nil {
+ t.Errorf("expected %s out of range to be rejected", name)
+ }
+ })
+ }
+}
+
+// An explicit zero has to be distinguishable from an omitted field, or it is
+// silently accepted and then ignored.
+func TestMaintenanceSettingsDistinguishZeroFromUnset(t *testing.T) {
+ var decoded MaintenanceSettings
+ if err := json.Unmarshal([]byte(`{"icebergCompaction":{"targetFileSizeMB":0}}`), &decoded); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if decoded.IcebergCompaction.TargetFileSizeMB == nil {
+ t.Fatal("expected an explicit zero to survive decoding")
+ }
+
+ var omitted MaintenanceSettings
+ if err := json.Unmarshal([]byte(`{"icebergCompaction":{}}`), &omitted); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if omitted.IcebergCompaction.TargetFileSizeMB != nil {
+ t.Error("expected an omitted field to stay unset")
+ }
+}
+
+// aws-cn and aws-us-gov ARNs are valid and must parse; the emitted ARN has to
+// use the partition its region belongs to so it round-trips.
+func TestARNPartitionsBeyondCommercial(t *testing.T) {
+ for _, arn := range []string{
+ "arn:aws:s3tables:us-east-1:123456789012:bucket/analytics",
+ "arn:aws-cn:s3tables:cn-north-1:123456789012:bucket/analytics",
+ "arn:aws-us-gov:s3tables:us-gov-west-1:123456789012:bucket/analytics",
+ } {
+ got, err := parseBucketNameFromARN(arn)
+ if err != nil {
+ t.Errorf("expected %s to parse, got %v", arn, err)
+ continue
+ }
+ if got != "analytics" {
+ t.Errorf("expected bucket analytics from %s, got %q", arn, got)
+ }
+ }
+
+ if _, err := parseBucketNameFromARN("arn:notaws:s3tables:us-east-1:123456789012:bucket/analytics"); err == nil {
+ t.Error("expected a non-AWS partition to be rejected")
+ }
+}
+
+func TestARNPartitionForRegion(t *testing.T) {
+ for region, want := range map[string]string{
+ "us-east-1": "aws",
+ "eu-west-2": "aws",
+ "cn-north-1": "aws-cn",
+ "cn-northwest-1": "aws-cn",
+ "us-gov-west-1": "aws-us-gov",
+ "us-iso-east-1": "aws-iso",
+ "us-isob-east-1": "aws-iso-b",
+ "eu-isoe-west-1": "aws-iso-e",
+ "us-isof-south-1": "aws-iso-f",
+ "eusc-de-east-1": "aws-eusc",
+ } {
+ if got := arnPartitionForRegion(region); got != want {
+ t.Errorf("region %s: expected partition %q, got %q", region, want, got)
+ }
+ }
+}
+
+// An ARN this handler emits has to carry the partition its region belongs to,
+// not just parse back — a commercial ARN returned for a gov region still parses
+// but is wrong for IAM matching and for the caller.
+func TestGeneratedARNsUseTheRegionPartition(t *testing.T) {
+ for region, partition := range map[string]string{
+ "us-east-1": "aws",
+ "cn-north-1": "aws-cn",
+ "us-gov-west-1": "aws-us-gov",
+ } {
+ h := NewS3TablesHandler()
+ h.SetRegion(region)
+
+ bucketARN := h.generateTableBucketARN(DefaultAccountID, "analytics")
+ tableARN := h.generateTableARN(DefaultAccountID, "analytics", "sales/orders")
+ viewARN := h.generateViewARN(DefaultAccountID, "analytics", "sales/v1")
+ s3ARN := h.generateS3BucketARN("analytics")
+
+ for _, arn := range []string{bucketARN, tableARN, viewARN, s3ARN} {
+ if !strings.HasPrefix(arn, "arn:"+partition+":") {
+ t.Errorf("region %s: expected partition %q, got %s", region, partition, arn)
+ }
+ }
+
+ got, err := parseBucketNameFromARN(bucketARN)
+ if err != nil {
+ t.Errorf("generated ARN %s does not parse: %v", bucketARN, err)
+ continue
+ }
+ if got != "analytics" {
+ t.Errorf("expected analytics from %s, got %q", bucketARN, got)
+ }
+
+ bucket, namespace, table, err := parseTableFromARN(tableARN)
+ if err != nil {
+ t.Errorf("generated table ARN %s does not parse: %v", tableARN, err)
+ continue
+ }
+ if bucket != "analytics" || namespace != "sales" || table != "orders" {
+ t.Errorf("unexpected parse of %s: %s/%s/%s", tableARN, bucket, namespace, table)
+ }
+ }
+}
diff --git a/weed/s3api/s3tables/handler_rename_test.go b/weed/s3api/s3tables/handler_rename_test.go
index 4507a0b62a..7f522704f4 100644
--- a/weed/s3api/s3tables/handler_rename_test.go
+++ b/weed/s3api/s3tables/handler_rename_test.go
@@ -352,3 +352,66 @@ func TestRenameTableInvalidName(t *testing.T) {
require.ErrorAs(t, err, &s3Err)
assert.Equal(t, ErrCodeInvalidRequest, s3Err.Type)
}
+
+// A disabled maintenance configuration has to move with the table. Leaving it
+// behind re-enables maintenance under the new name, and leaks the old settings
+// onto whatever is created at the old one.
+func TestRenameTableCarriesMaintenanceConfiguration(t *testing.T) {
+ fs, m := startRenameManager(t)
+
+ src := fs.getEntry(GetNamespacePath(renameTestBucket, "ns"), "t")
+ require.NotNil(t, src)
+ config := []byte(`{"icebergSnapshotManagement":{"status":"disabled"}}`)
+ status := []byte(`{"icebergCompaction":{"status":"Successful"}}`)
+ src.Extended[ExtendedKeyMaintenance] = config
+ src.Extended[ExtendedKeyMaintenanceStatus] = status
+
+ require.NoError(t, runRename(t, m, fs, &RenameTableRequest{
+ TableBucketARN: mustBucketARN(t),
+ SourceNamespace: []string{"ns"},
+ SourceName: "t",
+ DestNamespace: []string{"ns"},
+ DestName: "t2",
+ }))
+
+ dest := fs.getEntry(GetNamespacePath(renameTestBucket, "ns"), "t2")
+ require.NotNil(t, dest)
+ assert.Equal(t, config, dest.Extended[ExtendedKeyMaintenance], "the disable must move with the table")
+ assert.Equal(t, status, dest.Extended[ExtendedKeyMaintenanceStatus])
+
+ // And must not linger on the old name, where a reused name would inherit it.
+ moved := fs.getEntry(GetNamespacePath(renameTestBucket, "ns"), "t")
+ require.NotNil(t, moved)
+ _, hasConfig := moved.Extended[ExtendedKeyMaintenance]
+ assert.False(t, hasConfig, "source maintenance configuration must be cleared")
+ _, hasStatus := moved.Extended[ExtendedKeyMaintenanceStatus]
+ assert.False(t, hasStatus, "source maintenance status must be cleared")
+}
+
+// A maintenance configuration written after the rename copied the source must
+// not be deleted by the source cleanup: it would vanish without ever reaching
+// the destination.
+func TestRenameTableRejectsConcurrentMaintenanceWrite(t *testing.T) {
+ fs, _ := startRenameManager(t)
+
+ src := fs.getEntry(GetNamespacePath(renameTestBucket, "ns"), "t")
+ require.NotNil(t, src)
+ copied := []byte(`{"icebergCompaction":{"status":"enabled"}}`)
+ src.Extended[ExtendedKeyMaintenance] = copied
+
+ // Stand in for the Put that lands between the copy and the cleanup.
+ landedLate := []byte(`{"icebergSnapshotManagement":{"status":"disabled"}}`)
+ expected := map[string][]byte{ExtendedKeyMaintenance: copied}
+
+ src.Extended[ExtendedKeyMaintenance] = landedLate
+
+ h := NewS3TablesHandler()
+ err := NewManagerClient(fs.client).WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
+ return h.removeExtendedAttributesIf(context.Background(),
+ client, GetTablePath(renameTestBucket, "ns", "t"), expected, renamedTableAttributes...)
+ })
+
+ require.Error(t, err, "cleanup must refuse to delete a configuration written after the copy")
+ assert.ErrorIs(t, err, ErrConcurrentUpdate)
+ assert.Equal(t, landedLate, src.Extended[ExtendedKeyMaintenance], "the late write must survive")
+}
diff --git a/weed/s3api/s3tables/handler_table.go b/weed/s3api/s3tables/handler_table.go
index f3ff610c0a..0c0bda04fa 100644
--- a/weed/s3api/s3tables/handler_table.go
+++ b/weed/s3api/s3tables/handler_table.go
@@ -1200,7 +1200,8 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
return err
}
return h.removeExtendedAttributes(r.Context(), client, tablePath,
- ExtendedKeyMetadata, ExtendedKeyMetadataVersion, ExtendedKeyPolicy, ExtendedKeyTags, ExtendedKeyEntryType)
+ ExtendedKeyMetadata, ExtendedKeyMetadataVersion, ExtendedKeyPolicy, ExtendedKeyTags, ExtendedKeyEntryType,
+ ExtendedKeyMaintenance, ExtendedKeyMaintenanceStatus)
}
// Colocated table: the name path holds the data.
return h.deleteDirectory(r.Context(), client, tablePath)
@@ -1215,6 +1216,17 @@ func (h *S3TablesHandler) handleDeleteTable(w http.ResponseWriter, r *http.Reque
return nil
}
+// renamedTableAttributes are the catalog attributes a rename carries to the new
+// name and clears from the old one.
+var renamedTableAttributes = []string{
+ ExtendedKeyMetadata,
+ ExtendedKeyMetadataVersion,
+ ExtendedKeyPolicy,
+ ExtendedKeyTags,
+ ExtendedKeyMaintenance,
+ ExtendedKeyMaintenanceStatus,
+}
+
// handleRenameTable moves a table's catalog entry to a new namespace/name within
// the same bucket. It is catalog-only: the metadata.json and data files stay put,
// the destination keeps the source's MetadataLocation, and the source name is
@@ -1263,6 +1275,12 @@ func (h *S3TablesHandler) handleRenameTable(w http.ResponseWriter, r *http.Reque
var metadata tableMetadataInternal
var metadataVersionXattr []byte
+ var maintenanceXattr []byte
+ var maintenanceStatusXattr []byte
+ // The values the rename copies. The source is only cleared while it still
+ // holds exactly these, so a write that lands mid-rename is not deleted here
+ // after having missed the copy to the destination.
+ var copiedFromSource map[string][]byte
var tablePolicy string
var bucketPolicy string
var bucketTags map[string]string
@@ -1294,6 +1312,34 @@ func (h *S3TablesHandler) handleRenameTable(w http.ResponseWriter, r *http.Reque
return err
}
+ srcEntry, err := h.lookupEntry(r.Context(), client, srcPath)
+ if err != nil {
+ return err
+ }
+ copiedFromSource = make(map[string][]byte, len(renamedTableAttributes))
+ for _, key := range renamedTableAttributes {
+ copiedFromSource[key] = srcEntry.Extended[key]
+ }
+
+ // The maintenance configuration and its last-run status belong to the
+ // table, so they move with it; leaving them behind re-enables
+ // maintenance under the new name and leaks the old settings onto
+ // whatever is created at the old one.
+ for _, attr := range []struct {
+ key string
+ dest *[]byte
+ }{
+ {ExtendedKeyMaintenance, &maintenanceXattr},
+ {ExtendedKeyMaintenanceStatus, &maintenanceStatusXattr},
+ } {
+ data, err := h.getExtendedAttribute(r.Context(), client, srcPath, attr.key)
+ if err == nil {
+ *attr.dest = data
+ } else if !errors.Is(err, ErrAttributeNotFound) {
+ return fmt.Errorf("failed to fetch %s: %w", attr.key, err)
+ }
+ }
+
bucketPath := GetTableBucketPath(bucketName)
data, err = h.getExtendedAttribute(r.Context(), client, bucketPath, ExtendedKeyMetadata)
if err == nil {
@@ -1452,14 +1498,28 @@ func (h *S3TablesHandler) handleRenameTable(w http.ResponseWriter, r *http.Reque
return err
}
}
+ if len(maintenanceXattr) > 0 {
+ if err := h.setExtendedAttribute(r.Context(), client, destPath, ExtendedKeyMaintenance, maintenanceXattr); err != nil {
+ return err
+ }
+ }
+ if len(maintenanceStatusXattr) > 0 {
+ if err := h.setExtendedAttribute(r.Context(), client, destPath, ExtendedKeyMaintenanceStatus, maintenanceStatusXattr); err != nil {
+ return err
+ }
+ }
// Soft-delete the source catalog identity in place: drop its catalog xattrs
// so the name stops resolving while the metadata/ and data/ children stay put
// (manifests embed absolute paths, so the data must not move).
- return h.removeExtendedAttributes(r.Context(), client, srcPath,
- ExtendedKeyMetadata, ExtendedKeyMetadataVersion, ExtendedKeyPolicy, ExtendedKeyTags)
+ return h.removeExtendedAttributesIf(r.Context(), client, srcPath, copiedFromSource,
+ renamedTableAttributes...)
})
if err != nil {
+ if errors.Is(err, ErrConcurrentUpdate) {
+ h.writeError(w, http.StatusConflict, ErrCodeConflict, "table changed during rename, retry the request")
+ return err
+ }
h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, "failed to rename table")
return err
}
diff --git a/weed/s3api/s3tables/types.go b/weed/s3api/s3tables/types.go
index 6416cf08f9..767c1f1be1 100644
--- a/weed/s3api/s3tables/types.go
+++ b/weed/s3api/s3tables/types.go
@@ -394,6 +394,143 @@ type DeleteTablePolicyRequest struct {
Name string `json:"name"`
}
+// Maintenance configuration types
+
+const (
+ MaintenanceTypeIcebergCompaction = "icebergCompaction"
+ MaintenanceTypeIcebergSnapshotManagement = "icebergSnapshotManagement"
+ MaintenanceTypeIcebergUnreferencedFileRemoval = "icebergUnreferencedFileRemoval"
+
+ MaintenanceStatusEnabled = "enabled"
+ MaintenanceStatusDisabled = "disabled"
+)
+
+type IcebergCompactionSettings struct {
+ Strategy string `json:"strategy,omitempty"`
+ TargetFileSizeMB *int64 `json:"targetFileSizeMB,omitempty"`
+}
+
+// Compaction strategies. AWS also defines z-order, which the maintenance
+// worker cannot produce, so it is rejected rather than silently binpacked.
+const (
+ CompactionStrategyAuto = "auto"
+ CompactionStrategyBinpack = "binpack"
+ CompactionStrategySort = "sort"
+ CompactionStrategyZOrder = "z-order"
+)
+
+type IcebergSnapshotManagementSettings struct {
+ MinSnapshotsToKeep *int64 `json:"minSnapshotsToKeep,omitempty"`
+ MaxSnapshotAgeHours *int64 `json:"maxSnapshotAgeHours,omitempty"`
+}
+
+type IcebergUnreferencedFileRemovalSettings struct {
+ UnreferencedDays *int64 `json:"unreferencedDays,omitempty"`
+ NonCurrentDays *int64 `json:"nonCurrentDays,omitempty"`
+}
+
+type MaintenanceSettings struct {
+ IcebergCompaction *IcebergCompactionSettings `json:"icebergCompaction,omitempty"`
+ IcebergSnapshotManagement *IcebergSnapshotManagementSettings `json:"icebergSnapshotManagement,omitempty"`
+ IcebergUnreferencedFileRemoval *IcebergUnreferencedFileRemovalSettings `json:"icebergUnreferencedFileRemoval,omitempty"`
+}
+
+type MaintenanceConfigurationValue struct {
+ Status string `json:"status,omitempty"`
+ Settings *MaintenanceSettings `json:"settings,omitempty"`
+}
+
+// MaintenanceConfiguration maps a maintenance type to its configuration. It is
+// stored verbatim as the maintenance extended attribute so Get is a passthrough.
+type MaintenanceConfiguration map[string]*MaintenanceConfigurationValue
+
+// MergeMaintenanceConfiguration overlays a table's configuration on its
+// bucket's. Unreferenced file removal is only configurable on the bucket, so
+// anything reading a table's effective configuration has to consult both.
+func MergeMaintenanceConfiguration(bucket, table MaintenanceConfiguration) MaintenanceConfiguration {
+ if len(bucket) == 0 {
+ return table
+ }
+ if len(table) == 0 {
+ return bucket
+ }
+
+ merged := make(MaintenanceConfiguration, len(bucket)+len(table))
+ for k, v := range bucket {
+ merged[k] = v
+ }
+ for k, v := range table {
+ merged[k] = v
+ }
+ return merged
+}
+
+type PutTableBucketMaintenanceConfigurationRequest struct {
+ TableBucketARN string `json:"tableBucketARN"`
+ Type string `json:"type"`
+ Value *MaintenanceConfigurationValue `json:"value"`
+}
+
+type GetTableBucketMaintenanceConfigurationRequest struct {
+ TableBucketARN string `json:"tableBucketARN"`
+}
+
+type GetTableBucketMaintenanceConfigurationResponse struct {
+ TableBucketARN string `json:"tableBucketARN"`
+ Configuration MaintenanceConfiguration `json:"configuration"`
+}
+
+type PutTableMaintenanceConfigurationRequest struct {
+ TableBucketARN string `json:"tableBucketARN"`
+ Namespace []string `json:"namespace"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Value *MaintenanceConfigurationValue `json:"value"`
+}
+
+type GetTableMaintenanceConfigurationRequest struct {
+ TableBucketARN string `json:"tableBucketARN"`
+ Namespace []string `json:"namespace"`
+ Name string `json:"name"`
+}
+
+type GetTableMaintenanceConfigurationResponse struct {
+ TableARN string `json:"tableARN"`
+ Namespace []string `json:"namespace"`
+ Name string `json:"name"`
+ Configuration MaintenanceConfiguration `json:"configuration"`
+}
+
+// Maintenance job status types
+
+const (
+ MaintenanceJobStatusNotYetRun = "Not_Yet_Run"
+ MaintenanceJobStatusSuccessful = "Successful"
+ MaintenanceJobStatusFailed = "Failed"
+ MaintenanceJobStatusDisabled = "Disabled"
+)
+
+type MaintenanceJobStatusValue struct {
+ Status string `json:"status"`
+ LastRunTimestamp *time.Time `json:"lastRunTimestamp,omitempty"`
+ FailureMessage string `json:"failureMessage,omitempty"`
+}
+
+// MaintenanceJobStatus maps a maintenance type to the outcome of its last run.
+// The worker writes it; the control plane only reads it.
+type MaintenanceJobStatus map[string]*MaintenanceJobStatusValue
+
+type GetTableMaintenanceJobStatusRequest struct {
+ TableBucketARN string `json:"tableBucketARN"`
+ Namespace []string `json:"namespace"`
+ Name string `json:"name"`
+}
+
+type GetTableMaintenanceJobStatusResponse struct {
+ TableARN string `json:"tableARN"`
+ Status MaintenanceJobStatus `json:"status"`
+}
+
// Tagging types
type TagResourceRequest struct {
diff --git a/weed/s3api/s3tables/utils.go b/weed/s3api/s3tables/utils.go
index d65c02de7e..302667e0de 100644
--- a/weed/s3api/s3tables/utils.go
+++ b/weed/s3api/s3tables/utils.go
@@ -23,9 +23,17 @@ const (
tableObjectRootDirName = ".objects"
)
+// ARNPartitionPatternStr matches any AWS partition, not just the commercial
+// one: aws-cn and aws-us-gov ARNs are valid and must reach the handlers.
+const ARNPartitionPatternStr = `aws[-a-z0-9]*`
+
+// ARNPrefixPatternStr is the leading, partition-tolerant part of every S3
+// Tables ARN. The HTTP router shares it so routes and parsing agree.
+const ARNPrefixPatternStr = `arn:` + ARNPartitionPatternStr + `:s3tables`
+
var (
- bucketARNPattern = regexp.MustCompile(`^arn:aws:s3tables:[^:]*:[^:]*:bucket/(` + bucketNamePatternStr + `)$`)
- tableARNPattern = regexp.MustCompile(`^arn:aws:s3tables:[^:]*:[^:]*:bucket/(` + bucketNamePatternStr + `)/table/(` + tableNamespacePatternStr + `)/(` + tableNamePatternStr + `)$`)
+ bucketARNPattern = regexp.MustCompile(`^` + ARNPrefixPatternStr + `:[^:]*:[^:]*:bucket/(` + bucketNamePatternStr + `)$`)
+ tableARNPattern = regexp.MustCompile(`^` + ARNPrefixPatternStr + `:[^:]*:[^:]*:bucket/(` + bucketNamePatternStr + `)/table/(` + tableNamespacePatternStr + `)/(` + tableNamePatternStr + `)$`)
tagPattern = regexp.MustCompile(`^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$`)
)
@@ -278,7 +286,30 @@ func BuildTableARN(region, accountID, bucketName, namespace, tableName string) (
}
func buildARN(region, accountID, resourcePath string) string {
- return fmt.Sprintf("arn:aws:s3tables:%s:%s:%s", region, accountID, resourcePath)
+ return fmt.Sprintf("arn:%s:s3tables:%s:%s:%s", arnPartitionForRegion(region), region, accountID, resourcePath)
+}
+
+// arnPartitionForRegion returns the ARN partition a region belongs to, so an
+// ARN this handler emits round-trips through a client in that partition.
+func arnPartitionForRegion(region string) string {
+ switch {
+ case strings.HasPrefix(region, "cn-"):
+ return "aws-cn"
+ case strings.HasPrefix(region, "us-gov-"):
+ return "aws-us-gov"
+ case strings.HasPrefix(region, "us-iso-"):
+ return "aws-iso"
+ case strings.HasPrefix(region, "us-isob-"):
+ return "aws-iso-b"
+ case strings.HasPrefix(region, "eu-isoe-"):
+ return "aws-iso-e"
+ case strings.HasPrefix(region, "us-isof-"):
+ return "aws-iso-f"
+ case strings.HasPrefix(region, "eusc-"):
+ return "aws-eusc"
+ default:
+ return "aws"
+ }
}
// ValidateTags validates tags for S3 Tables.
diff --git a/weed/worker/tasks/iceberg/config.go b/weed/worker/tasks/iceberg/config.go
index 2eaa8cc213..65e15ec976 100644
--- a/weed/worker/tasks/iceberg/config.go
+++ b/weed/worker/tasks/iceberg/config.go
@@ -25,6 +25,7 @@ const (
defaultDeleteMaxGroupSizeMB = 256
defaultDeleteMaxOutputFiles = 8
defaultRewriteStrategy = "binpack"
+ rewriteStrategyAuto = "auto"
defaultMinManifestsToRewrite = 5
minManifestsToRewrite = 2
defaultOperations = "all"
@@ -55,6 +56,44 @@ const msPerHour int64 = 3600 * 1000
// cutoff in the future and making every file look like an orphan.
const maxOrphanOlderThanHours = int64(math.MaxInt64 / int64(time.Hour))
+// mbToBytes converts megabytes to bytes, saturating instead of overflowing.
+func mbToBytes(mb int64) int64 {
+ if mb <= 0 {
+ return 0
+ }
+ if mb > math.MaxInt64/bytesPerMB {
+ return math.MaxInt64
+ }
+ return mb * bytesPerMB
+}
+
+// addDays sums two day counts, saturating instead of overflowing. Negative
+// inputs are treated as unset.
+func addDays(a, b int64) int64 {
+ if a < 0 {
+ a = 0
+ }
+ if b < 0 {
+ b = 0
+ }
+ if a > math.MaxInt64-b {
+ return math.MaxInt64
+ }
+ return a + b
+}
+
+// daysToHours converts days to hours, saturating instead of overflowing.
+// applyThresholdDefaults clamps the result down to a usable cutoff.
+func daysToHours(days int64) int64 {
+ if days <= 0 {
+ return 0
+ }
+ if days > math.MaxInt64/24 {
+ return math.MaxInt64
+ }
+ return days * 24
+}
+
// hoursToMs converts hours to milliseconds, saturating instead of overflowing.
func hoursToMs(hours int64) int64 {
if hours <= 0 {
@@ -82,6 +121,7 @@ type Config struct {
DeleteMaxOutputFiles int64
MinManifestsToRewrite int64
Operations string
+ TablePropertiesOverride bool
ApplyDeletes bool
Where string
RewriteStrategy string
@@ -104,6 +144,7 @@ func ParseConfig(values map[string]*plugin_pb.ConfigValue) Config {
DeleteMaxOutputFiles: readInt64Config(values, "delete_max_output_files", defaultDeleteMaxOutputFiles),
MinManifestsToRewrite: readInt64Config(values, "min_manifests_to_rewrite", defaultMinManifestsToRewrite),
Operations: readStringConfig(values, "operations", defaultOperations),
+ TablePropertiesOverride: readBoolConfig(values, "table_properties_override", true),
ApplyDeletes: readBoolConfig(values, "apply_deletes", true),
Where: strings.TrimSpace(readStringConfig(values, "where", "")),
RewriteStrategy: strings.TrimSpace(strings.ToLower(readStringConfig(values, "rewrite_strategy", defaultRewriteStrategy))),
@@ -152,7 +193,7 @@ func applyThresholdDefaults(cfg Config) Config {
if cfg.RewriteStrategy == "" {
cfg.RewriteStrategy = defaultRewriteStrategy
}
- if cfg.RewriteStrategy != "binpack" && cfg.RewriteStrategy != "sort" {
+ if cfg.RewriteStrategy != "binpack" && cfg.RewriteStrategy != "sort" && cfg.RewriteStrategy != rewriteStrategyAuto {
cfg.RewriteStrategy = defaultRewriteStrategy
}
if cfg.SortMaxInputBytes < 0 {
diff --git a/weed/worker/tasks/iceberg/detection.go b/weed/worker/tasks/iceberg/detection.go
index 3207095837..4faca8ab88 100644
--- a/weed/worker/tasks/iceberg/detection.go
+++ b/weed/worker/tasks/iceberg/detection.go
@@ -69,6 +69,11 @@ func (h *Handler) scanTablesForMaintenance(
if !wildcard.MatchesAnyWildcard(bucketMatchers, bucketName) {
continue
}
+ bucketMaintenance, err := parseMaintenanceConfiguration(bucketEntry.Extended, bucketName)
+ if err != nil {
+ glog.Warningf("iceberg maintenance: skipping bucket %s: %v", bucketName, err)
+ continue
+ }
// List namespaces within the bucket
bucketPath := path.Join(bucketsPath, bucketName)
@@ -127,9 +132,19 @@ func (h *Handler) scanTablesForMaintenance(
continue
}
- effective := resolveTableConfig(config, state.Metadata.Properties())
+ tableMaintenance, err := parseMaintenanceConfiguration(tableEntry.Extended, path.Join(bucketName, tablePath))
+ if err != nil {
+ glog.Warningf("iceberg maintenance: skipping %s/%s/%s: %v", bucketName, nsName, tblName, err)
+ continue
+ }
+ maintenance := mergeMaintenanceConfiguration(bucketMaintenance, tableMaintenance)
+ tableOps := filterDisabledOperations(ops, maintenance)
+ if len(tableOps) == 0 {
+ continue
+ }
+ effective := resolveTableConfig(config, state.Metadata.Properties(), maintenance)
- needsWork, err := h.tableNeedsMaintenance(ctx, filerClient, bucketName, tablePath, state, effective, ops)
+ needsWork, err := h.tableNeedsMaintenance(ctx, filerClient, bucketName, tablePath, state, effective, tableOps)
if err != nil {
glog.V(2).Infof("iceberg maintenance: skipping %s/%s/%s: cannot evaluate maintenance need: %v", bucketName, nsName, tblName, err)
continue
diff --git a/weed/worker/tasks/iceberg/filer_io.go b/weed/worker/tasks/iceberg/filer_io.go
index 7564659eb7..75fae1db0f 100644
--- a/weed/worker/tasks/iceberg/filer_io.go
+++ b/weed/worker/tasks/iceberg/filer_io.go
@@ -438,15 +438,16 @@ func updateTableMetadataXattr(ctx context.Context, client filer_pb.SeaweedFilerC
return fmt.Errorf("marshal updated xattr: %w", err)
}
- expectedVersionXattr := resp.Entry.Extended[s3tables.ExtendedKeyMetadataVersion]
+ // Assert the whole attribute set, not just the version: this rewrites the
+ // entry from the snapshot above, so a narrower precondition would delete an
+ // attribute a concurrent writer created, such as a maintenance configuration.
+ expectedExtended := s3tables.SnapshotExtended(resp.Entry.Extended)
resp.Entry.Extended[s3tables.ExtendedKeyMetadata] = updatedXattr
resp.Entry.Extended[s3tables.ExtendedKeyMetadataVersion] = metadataVersionXattr(newVersion)
_, err = client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
- Directory: parentDir,
- Entry: resp.Entry,
- ExpectedExtended: map[string][]byte{
- s3tables.ExtendedKeyMetadataVersion: expectedVersionXattr,
- },
+ Directory: parentDir,
+ Entry: resp.Entry,
+ ExpectedExtended: expectedExtended,
})
if err != nil {
if status.Code(err) == codes.FailedPrecondition {
diff --git a/weed/worker/tasks/iceberg/handler.go b/weed/worker/tasks/iceberg/handler.go
index 2830a4a497..0bc5e68d56 100644
--- a/weed/worker/tasks/iceberg/handler.go
+++ b/weed/worker/tasks/iceberg/handler.go
@@ -187,7 +187,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
{
Name: "rewrite_strategy",
Label: "Rewrite Strategy",
- Description: "binpack keeps the existing row order; sort rewrites each compaction bin using the Iceberg table sort order.",
+ Description: "binpack keeps the existing row order; sort rewrites each compaction bin using the Iceberg table sort order; auto sorts tables that declare one and bin-packs the rest.",
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_STRING,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TEXT,
Placeholder: "binpack or sort",
@@ -292,6 +292,13 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_STRING,
Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TEXT,
},
+ {
+ Name: "table_properties_override",
+ Label: "Table Properties Win",
+ Description: "Let a table's own Iceberg properties override these settings and its maintenance configuration. Clear to make the maintenance configuration authoritative.",
+ FieldType: plugin_pb.ConfigFieldType_CONFIG_FIELD_TYPE_BOOL,
+ Widget: plugin_pb.ConfigWidget_CONFIG_WIDGET_TOGGLE,
+ },
{
Name: "where",
Label: "Where Filter",
@@ -317,6 +324,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
"max_commit_retries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxCommitRetries}},
"operations": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultOperations}},
"apply_deletes": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
+ "table_properties_override": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"rewrite_strategy": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultRewriteStrategy}},
"sort_max_input_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
@@ -347,6 +355,7 @@ func (h *Handler) Descriptor() *plugin_pb.JobTypeDescriptor {
"max_commit_retries": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: defaultMaxCommitRetries}},
"operations": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultOperations}},
"apply_deletes": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
+ "table_properties_override": {Kind: &plugin_pb.ConfigValue_BoolValue{BoolValue: true}},
"rewrite_strategy": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: defaultRewriteStrategy}},
"sort_max_input_mb": {Kind: &plugin_pb.ConfigValue_Int64Value{Int64Value: 0}},
"where": {Kind: &plugin_pb.ConfigValue_StringValue{StringValue: ""}},
@@ -520,21 +529,31 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
filerClient := filer_pb.NewSeaweedFilerClient(conn)
// Resolve once for the whole job: compaction commits new metadata as it
- // runs, and a job should not change settings halfway through. Failing to
- // read the properties has to fail the job rather than fall back to the
- // plugin config, or the operations would rewrite the table to a size it
- // did not ask for.
+ // runs, and a job should not change settings halfway through. Both reads
+ // fail the job rather than fall back, since without the configuration a
+ // disabled operation would run anyway, and without the properties the
+ // operations would rewrite the table to a size it did not ask for.
+ maintenance, err := loadMaintenanceConfiguration(ctx, filerClient, bucketName, tablePath)
+ if err != nil {
+ return fmt.Errorf("read maintenance configuration for %s/%s: %w", bucketName, tablePath, err)
+ }
+ ops = filterDisabledOperations(ops, maintenance)
+
state, err := loadCurrentMetadata(ctx, filerClient, bucketName, tablePath)
if err != nil {
return fmt.Errorf("read table properties for %s/%s: %w", bucketName, tablePath, err)
}
- workerConfig = resolveTableConfig(workerConfig, state.Metadata.Properties())
+ workerConfig = resolveTableConfig(workerConfig, state.Metadata.Properties(), maintenance)
var results []string
+ if len(ops) == 0 {
+ results = append(results, "all maintenance operations are disabled for this table")
+ }
var lastErr error
totalOps := len(ops)
completedOps := 0
allMetrics := make(map[string]int64)
+ opErrors := make(map[string]error, totalOps)
// Execute operations in canonical maintenance order as defined by
// parseOperations.
@@ -596,6 +615,7 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
}
completedOps++
+ opErrors[op] = opErr
if opErr != nil {
glog.Warningf("iceberg maintenance %s failed for %s/%s/%s: %v", op, bucketName, namespace, tableName, opErr)
results = append(results, fmt.Sprintf("%s: error: %v", op, opErr))
@@ -605,6 +625,8 @@ func (h *Handler) Execute(ctx context.Context, request *plugin_pb.ExecuteJobRequ
}
}
+ recordJobStatus(ctx, filerClient, bucketName, tablePath, buildJobStatus(opErrors, time.Now().UTC()))
+
resultSummary := strings.Join(results, "; ")
success := lastErr == nil
diff --git a/weed/worker/tasks/iceberg/job_status.go b/weed/worker/tasks/iceberg/job_status.go
new file mode 100644
index 0000000000..d60b831824
--- /dev/null
+++ b/weed/worker/tasks/iceberg/job_status.go
@@ -0,0 +1,126 @@
+package iceberg
+
+import (
+ "context"
+ "encoding/json"
+ "path"
+ "time"
+
+ "github.com/seaweedfs/seaweedfs/weed/glog"
+ "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// jobStatusUpdateAttempts bounds the read-modify-write retry loop for the job
+// status attribute. Asserting the whole attribute set makes a lost race more
+// likely, so allow a couple of retries before giving up.
+const jobStatusUpdateAttempts = 3
+
+// buildJobStatus folds the operations this job ran into the AWS job types that
+// govern them. Operations that did not run are left out so a partial run does
+// not erase what an earlier one recorded.
+func buildJobStatus(opErrors map[string]error, ranAt time.Time) s3tables.MaintenanceJobStatus {
+ jobStatus := s3tables.MaintenanceJobStatus{}
+
+ for op, opErr := range opErrors {
+ jobType := maintenanceJobType(op)
+ if jobType == "" {
+ continue
+ }
+
+ value, ok := jobStatus[jobType]
+ if !ok {
+ timestamp := ranAt
+ value = &s3tables.MaintenanceJobStatusValue{
+ Status: s3tables.MaintenanceJobStatusSuccessful,
+ LastRunTimestamp: &timestamp,
+ }
+ jobStatus[jobType] = value
+ }
+
+ // Several operations can map to one job type; one failure fails the type.
+ if opErr != nil && value.Status != s3tables.MaintenanceJobStatusFailed {
+ value.Status = s3tables.MaintenanceJobStatusFailed
+ value.FailureMessage = opErr.Error()
+ }
+ }
+
+ return jobStatus
+}
+
+// recordJobStatus merges this job's outcome into the table's stored status.
+// Status is advisory, so a lost race is logged rather than failing a job whose
+// work already committed.
+func recordJobStatus(
+ ctx context.Context,
+ client filer_pb.SeaweedFilerClient,
+ bucketName, tablePath string,
+ jobStatus s3tables.MaintenanceJobStatus,
+) {
+ if len(jobStatus) == 0 {
+ return
+ }
+
+ tableDir := path.Join(s3tables.TablesPath, bucketName, tablePath)
+ dir, name := path.Dir(tableDir), path.Base(tableDir)
+
+ for attempt := 0; attempt < jobStatusUpdateAttempts; attempt++ {
+ resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
+ Directory: dir,
+ Name: name,
+ })
+ if err != nil {
+ glog.V(1).Infof("iceberg maintenance: cannot record job status for %s/%s: %v", bucketName, tablePath, err)
+ return
+ }
+ if resp == nil || resp.Entry == nil {
+ return
+ }
+
+ entry := resp.Entry
+ current := entry.Extended[s3tables.ExtendedKeyMaintenanceStatus]
+ // Assert every attribute, not just our own: UpdateEntry rewrites the
+ // whole entry, so a narrow assertion would let this write revert a
+ // maintenance configuration an operator just disabled.
+ expected := s3tables.SnapshotExtended(entry.Extended, s3tables.ExtendedKeyMaintenanceStatus)
+
+ merged := s3tables.MaintenanceJobStatus{}
+ if len(current) > 0 {
+ if err := json.Unmarshal(current, &merged); err != nil {
+ glog.V(1).Infof("iceberg maintenance: replacing unreadable job status on %s/%s: %v", bucketName, tablePath, err)
+ merged = s3tables.MaintenanceJobStatus{}
+ }
+ }
+ for jobType, value := range jobStatus {
+ merged[jobType] = value
+ }
+
+ data, err := json.Marshal(merged)
+ if err != nil {
+ glog.V(1).Infof("iceberg maintenance: cannot marshal job status for %s/%s: %v", bucketName, tablePath, err)
+ return
+ }
+
+ if entry.Extended == nil {
+ entry.Extended = make(map[string][]byte)
+ }
+ entry.Extended[s3tables.ExtendedKeyMaintenanceStatus] = data
+
+ _, err = client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
+ Directory: dir,
+ Entry: entry,
+ ExpectedExtended: expected,
+ })
+ if err == nil {
+ return
+ }
+ if status.Code(err) != codes.FailedPrecondition {
+ glog.V(1).Infof("iceberg maintenance: cannot record job status for %s/%s: %v", bucketName, tablePath, err)
+ return
+ }
+ }
+
+ glog.V(1).Infof("iceberg maintenance: gave up recording job status for %s/%s after %d attempts", bucketName, tablePath, jobStatusUpdateAttempts)
+}
diff --git a/weed/worker/tasks/iceberg/planning_index.go b/weed/worker/tasks/iceberg/planning_index.go
index 320cafda26..278bc691fe 100644
--- a/weed/worker/tasks/iceberg/planning_index.go
+++ b/weed/worker/tasks/iceberg/planning_index.go
@@ -257,12 +257,7 @@ func persistPlanningIndex(
return fmt.Errorf("marshal updated metadata xattr: %w", err)
}
- expectedExtended := map[string][]byte{
- s3tables.ExtendedKeyMetadata: existingXattr,
- }
- if expectedVersionXattr, ok := resp.Entry.Extended[s3tables.ExtendedKeyMetadataVersion]; ok && len(expectedVersionXattr) > 0 {
- expectedExtended[s3tables.ExtendedKeyMetadataVersion] = expectedVersionXattr
- }
+ expectedExtended := s3tables.SnapshotExtended(resp.Entry.Extended)
resp.Entry.Extended[s3tables.ExtendedKeyMetadata] = updatedXattr
_, err = client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
Directory: parentDir,
diff --git a/weed/worker/tasks/iceberg/sort_strategy.go b/weed/worker/tasks/iceberg/sort_strategy.go
index 9c42fe4610..aaa873df90 100644
--- a/weed/worker/tasks/iceberg/sort_strategy.go
+++ b/weed/worker/tasks/iceberg/sort_strategy.go
@@ -29,6 +29,16 @@ func resolveCompactionRewritePlan(config Config, meta table.Metadata) (*compacti
if strategy == defaultRewriteStrategy {
return &compactionRewritePlan{strategy: defaultRewriteStrategy}, nil
}
+ // "auto" sorts tables that declare a usable sort order and bin-packs the
+ // rest, so an unsorted table is not an error the way an explicit "sort" is.
+ if strategy == rewriteStrategyAuto {
+ sortFields, err := resolveCompactionSortFields(meta)
+ if err != nil {
+ glog.V(2).Infof("iceberg compact: auto strategy falling back to binpack: %v", err)
+ return &compactionRewritePlan{strategy: defaultRewriteStrategy}, nil
+ }
+ return &compactionRewritePlan{strategy: "sort", sortFields: sortFields}, nil
+ }
if strategy != "sort" {
return nil, fmt.Errorf("unsupported rewrite strategy %q", config.RewriteStrategy)
}
diff --git a/weed/worker/tasks/iceberg/table_config.go b/weed/worker/tasks/iceberg/table_config.go
index 457d4518e3..b220d6c216 100644
--- a/weed/worker/tasks/iceberg/table_config.go
+++ b/weed/worker/tasks/iceberg/table_config.go
@@ -1,11 +1,17 @@
package iceberg
import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path"
"strconv"
"strings"
"github.com/apache/iceberg-go"
"github.com/seaweedfs/seaweedfs/weed/glog"
+ "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
// Iceberg table properties that describe the physical layout maintenance has
@@ -17,11 +23,27 @@ const (
propMinSnapshotsToKeep = "history.expire.min-snapshots-to-keep"
)
-// resolveTableConfig layers a table's own properties over the worker config.
-// Properties win: a writer targeting 512 MiB and a compactor rewriting to
-// 256 MiB would rewrite each other's output forever.
-func resolveTableConfig(base Config, props iceberg.Properties) Config {
+// resolveTableConfig layers a table's own intent over the worker config, from
+// the maintenance configuration and from the table's Iceberg properties.
+//
+// Properties win by default: a writer targeting 512 MiB and a compactor
+// rewriting to 256 MiB would rewrite each other's output forever, and the
+// property is the signal every engine already honours. Operators who want the
+// control plane to be authoritative instead can clear
+// table_properties_override.
+func resolveTableConfig(base Config, props iceberg.Properties, maintenance s3tables.MaintenanceConfiguration) Config {
cfg := base
+ if base.TablePropertiesOverride {
+ cfg = applyMaintenanceConfig(cfg, maintenance)
+ cfg = applyTableProperties(cfg, props)
+ } else {
+ cfg = applyTableProperties(cfg, props)
+ cfg = applyMaintenanceConfig(cfg, maintenance)
+ }
+ return applyThresholdDefaults(cfg)
+}
+
+func applyTableProperties(cfg Config, props iceberg.Properties) Config {
if v, ok := propInt64(props, propTargetFileSize); ok {
cfg.TargetFileSizeBytes = v
}
@@ -34,7 +56,160 @@ func resolveTableConfig(base Config, props iceberg.Properties) Config {
if v, ok := propInt64(props, propMinSnapshotsToKeep); ok {
cfg.MaxSnapshotsToKeep = v
}
- return applyThresholdDefaults(cfg)
+ return cfg
+}
+
+func applyMaintenanceConfig(cfg Config, maintenance s3tables.MaintenanceConfiguration) Config {
+ if s := compactionSettings(maintenance); s != nil {
+ if v := settingValue(s.TargetFileSizeMB); v > 0 {
+ cfg.TargetFileSizeBytes = mbToBytes(v)
+ }
+ switch s.Strategy {
+ case s3tables.CompactionStrategyBinpack, s3tables.CompactionStrategySort, s3tables.CompactionStrategyAuto:
+ cfg.RewriteStrategy = s.Strategy
+ }
+ }
+ if s := snapshotSettings(maintenance); s != nil {
+ if v := settingValue(s.MaxSnapshotAgeHours); v > 0 {
+ cfg.SnapshotRetentionMs = hoursToMs(v)
+ }
+ if v := settingValue(s.MinSnapshotsToKeep); v > 0 {
+ cfg.MaxSnapshotsToKeep = v
+ }
+ }
+ // AWS marks a file non-current after unreferencedDays and deletes it a
+ // further nonCurrentDays later. remove_orphans deletes in one step, so the
+ // cutoff has to be the sum or the recovery window disappears.
+ if s := orphanSettings(maintenance); s != nil {
+ if days := addDays(settingValue(s.UnreferencedDays), settingValue(s.NonCurrentDays)); days > 0 {
+ cfg.OrphanOlderThanHours = daysToHours(days)
+ }
+ }
+ return cfg
+}
+
+// settingValue reads an optional maintenance setting, treating unset and
+// nonsensical values alike so the worker keeps its own configuration.
+func settingValue(v *int64) int64 {
+ if v == nil || *v < 0 {
+ return 0
+ }
+ return *v
+}
+
+func compactionSettings(maintenance s3tables.MaintenanceConfiguration) *s3tables.IcebergCompactionSettings {
+ if v := enabledSettings(maintenance, s3tables.MaintenanceTypeIcebergCompaction); v != nil {
+ return v.IcebergCompaction
+ }
+ return nil
+}
+
+func snapshotSettings(maintenance s3tables.MaintenanceConfiguration) *s3tables.IcebergSnapshotManagementSettings {
+ if v := enabledSettings(maintenance, s3tables.MaintenanceTypeIcebergSnapshotManagement); v != nil {
+ return v.IcebergSnapshotManagement
+ }
+ return nil
+}
+
+func orphanSettings(maintenance s3tables.MaintenanceConfiguration) *s3tables.IcebergUnreferencedFileRemovalSettings {
+ if v := enabledSettings(maintenance, s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval); v != nil {
+ return v.IcebergUnreferencedFileRemoval
+ }
+ return nil
+}
+
+// enabledSettings returns the settings for a maintenance type only when it is
+// switched on; a disabled type drops its operations instead of retuning them.
+func enabledSettings(maintenance s3tables.MaintenanceConfiguration, maintenanceType string) *s3tables.MaintenanceSettings {
+ value, ok := maintenance[maintenanceType]
+ if !ok || value == nil || value.Status == s3tables.MaintenanceStatusDisabled {
+ return nil
+ }
+ return value.Settings
+}
+
+var mergeMaintenanceConfiguration = s3tables.MergeMaintenanceConfiguration
+
+// maintenanceJobType maps a worker operation onto the AWS job type that governs
+// it. Manifest and delete-file rewrites have no AWS equivalent and ride along
+// with compaction, so disabling compaction stops all rewriting.
+func maintenanceJobType(op string) string {
+ switch op {
+ case "compact", "rewrite_position_delete_files", "rewrite_manifests":
+ return s3tables.MaintenanceTypeIcebergCompaction
+ case "expire_snapshots":
+ return s3tables.MaintenanceTypeIcebergSnapshotManagement
+ case "remove_orphans":
+ return s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval
+ }
+ return ""
+}
+
+// filterDisabledOperations drops the operations the maintenance configuration
+// switched off. No table property can re-enable them.
+func filterDisabledOperations(ops []string, maintenance s3tables.MaintenanceConfiguration) []string {
+ if len(maintenance) == 0 {
+ return ops
+ }
+
+ filtered := make([]string, 0, len(ops))
+ for _, op := range ops {
+ value, ok := maintenance[maintenanceJobType(op)]
+ if ok && value != nil && value.Status == s3tables.MaintenanceStatusDisabled {
+ continue
+ }
+ filtered = append(filtered, op)
+ }
+ return filtered
+}
+
+// loadMaintenanceConfiguration reads the bucket and table maintenance
+// configuration and overlays the table's on the bucket's. Detection gets both
+// from entries it already listed; execution has to look them up.
+func loadMaintenanceConfiguration(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName, tablePath string) (s3tables.MaintenanceConfiguration, error) {
+ bucketDir := path.Join(s3tables.TablesPath, bucketName)
+ tableDir := path.Join(bucketDir, tablePath)
+
+ bucket, err := lookupMaintenanceConfiguration(ctx, client, bucketDir, bucketName)
+ if err != nil {
+ return nil, err
+ }
+ table, err := lookupMaintenanceConfiguration(ctx, client, tableDir, path.Join(bucketName, tablePath))
+ if err != nil {
+ return nil, err
+ }
+ return mergeMaintenanceConfiguration(bucket, table), nil
+}
+
+func lookupMaintenanceConfiguration(ctx context.Context, client filer_pb.SeaweedFilerClient, dir, resource string) (s3tables.MaintenanceConfiguration, error) {
+ resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
+ Directory: path.Dir(dir),
+ Name: path.Base(dir),
+ })
+ if err != nil {
+ return nil, fmt.Errorf("look up %s: %w", resource, err)
+ }
+ if resp == nil || resp.Entry == nil {
+ return nil, nil
+ }
+ return parseMaintenanceConfiguration(resp.Entry.Extended, resource)
+}
+
+// parseMaintenanceConfiguration reads the maintenance configuration stored on a
+// filer entry. An unreadable attribute is an error rather than an empty
+// configuration: treating it as empty would run operations the operator
+// disabled.
+func parseMaintenanceConfiguration(extended map[string][]byte, resource string) (s3tables.MaintenanceConfiguration, error) {
+ data, ok := extended[s3tables.ExtendedKeyMaintenance]
+ if !ok || len(data) == 0 {
+ return nil, nil
+ }
+
+ var config s3tables.MaintenanceConfiguration
+ if err := json.Unmarshal(data, &config); err != nil {
+ return nil, fmt.Errorf("parse maintenance configuration on %s: %w", resource, err)
+ }
+ return config, nil
}
// propInt64 reads a positive integer table property. Anything unset,
diff --git a/weed/worker/tasks/iceberg/table_config_test.go b/weed/worker/tasks/iceberg/table_config_test.go
index c94a8fb6cc..451ea73299 100644
--- a/weed/worker/tasks/iceberg/table_config_test.go
+++ b/weed/worker/tasks/iceberg/table_config_test.go
@@ -1,29 +1,34 @@
package iceberg
import (
+ "errors"
"math"
"testing"
"time"
"github.com/apache/iceberg-go"
+ "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
)
+func settingPtr(v int64) *int64 { return &v }
+
func baseTestConfig() Config {
return applyThresholdDefaults(Config{
- SnapshotRetentionMs: hoursToMs(defaultSnapshotRetentionHours),
- MaxSnapshotsToKeep: defaultMaxSnapshotsToKeep,
+ SnapshotRetentionMs: hoursToMs(defaultSnapshotRetentionHours),
+ MaxSnapshotsToKeep: defaultMaxSnapshotsToKeep,
+ TablePropertiesOverride: true,
})
}
func TestResolveTableConfigNoProperties(t *testing.T) {
base := baseTestConfig()
- got := resolveTableConfig(base, iceberg.Properties{})
+ got := resolveTableConfig(base, iceberg.Properties{}, nil)
if got != base {
t.Errorf("expected config untouched, got %+v", got)
}
- if got := resolveTableConfig(base, nil); got != base {
+ if got := resolveTableConfig(base, nil, nil); got != base {
t.Errorf("expected config untouched for nil properties, got %+v", got)
}
}
@@ -35,7 +40,7 @@ func TestResolveTableConfigPropertiesWin(t *testing.T) {
propDeleteTargetFileSize: "33554432",
propMaxSnapshotAgeMs: "432000000",
propMinSnapshotsToKeep: "1",
- })
+ }, nil)
if got.TargetFileSizeBytes != 536870912 {
t.Errorf("expected TargetFileSizeBytes=536870912, got %d", got.TargetFileSizeBytes)
@@ -54,7 +59,7 @@ func TestResolveTableConfigPropertiesWin(t *testing.T) {
// A sub-hour retention has to survive resolution; truncating it to whole hours
// would round down to zero and get clamped back up to the default.
func TestResolveTableConfigSubHourRetention(t *testing.T) {
- got := resolveTableConfig(baseTestConfig(), iceberg.Properties{propMaxSnapshotAgeMs: "1"})
+ got := resolveTableConfig(baseTestConfig(), iceberg.Properties{propMaxSnapshotAgeMs: "1"}, nil)
if got.SnapshotRetentionMs != 1 {
t.Errorf("expected SnapshotRetentionMs=1, got %d", got.SnapshotRetentionMs)
}
@@ -71,7 +76,7 @@ func TestResolveTableConfigIgnoresUnusableValues(t *testing.T) {
"overflow": "99999999999999999999",
} {
t.Run(name, func(t *testing.T) {
- got := resolveTableConfig(base, iceberg.Properties{propTargetFileSize: value})
+ got := resolveTableConfig(base, iceberg.Properties{propTargetFileSize: value}, nil)
if got.TargetFileSizeBytes != base.TargetFileSizeBytes {
t.Errorf("expected fallback to %d, got %d", base.TargetFileSizeBytes, got.TargetFileSizeBytes)
}
@@ -80,7 +85,7 @@ func TestResolveTableConfigIgnoresUnusableValues(t *testing.T) {
}
func TestResolveTableConfigTrimsWhitespace(t *testing.T) {
- got := resolveTableConfig(baseTestConfig(), iceberg.Properties{propTargetFileSize: " 536870912\n"})
+ got := resolveTableConfig(baseTestConfig(), iceberg.Properties{propTargetFileSize: " 536870912\n"}, nil)
if got.TargetFileSizeBytes != 536870912 {
t.Errorf("expected TargetFileSizeBytes=536870912, got %d", got.TargetFileSizeBytes)
}
@@ -92,7 +97,7 @@ func TestResolveTableConfigLeavesOtherFields(t *testing.T) {
base.Where = "day = 3"
base.MinInputFiles = 9
- got := resolveTableConfig(base, iceberg.Properties{propTargetFileSize: "536870912"})
+ got := resolveTableConfig(base, iceberg.Properties{propTargetFileSize: "536870912"}, nil)
if got.Operations != "compact" || got.Where != "day = 3" || got.MinInputFiles != 9 {
t.Errorf("expected unrelated fields preserved, got %+v", got)
}
@@ -113,3 +118,289 @@ func TestApplyThresholdDefaultsClampsOrphanCutoff(t *testing.T) {
t.Errorf("expected a normal cutoff untouched, got %d", got.OrphanOlderThanHours)
}
}
+
+func maintenanceConfig(entries map[string]*s3tables.MaintenanceConfigurationValue) s3tables.MaintenanceConfiguration {
+ return s3tables.MaintenanceConfiguration(entries)
+}
+
+func TestResolveTableConfigAppliesMaintenanceConfig(t *testing.T) {
+ got := resolveTableConfig(baseTestConfig(), nil, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{IcebergCompaction: &s3tables.IcebergCompactionSettings{TargetFileSizeMB: settingPtr(512)}},
+ },
+ s3tables.MaintenanceTypeIcebergSnapshotManagement: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{IcebergSnapshotManagement: &s3tables.IcebergSnapshotManagementSettings{
+ MinSnapshotsToKeep: settingPtr(2),
+ MaxSnapshotAgeHours: settingPtr(120),
+ }},
+ },
+ }))
+
+ if got.TargetFileSizeBytes != 512*bytesPerMB {
+ t.Errorf("expected TargetFileSizeBytes=%d, got %d", 512*bytesPerMB, got.TargetFileSizeBytes)
+ }
+ if got.MaxSnapshotsToKeep != 2 {
+ t.Errorf("expected MaxSnapshotsToKeep=2, got %d", got.MaxSnapshotsToKeep)
+ }
+ if got.SnapshotRetentionMs != hoursToMs(120) {
+ t.Errorf("expected SnapshotRetentionMs=%d, got %d", hoursToMs(120), got.SnapshotRetentionMs)
+ }
+}
+
+// The default: a table declaring its own layout beats the control plane, so a
+// writer and the compactor cannot disagree about target file size.
+func TestResolveTableConfigPropertyBeatsMaintenanceConfig(t *testing.T) {
+ maintenance := maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{IcebergCompaction: &s3tables.IcebergCompactionSettings{TargetFileSizeMB: settingPtr(128)}},
+ },
+ })
+ props := iceberg.Properties{propTargetFileSize: "536870912"}
+
+ got := resolveTableConfig(baseTestConfig(), props, maintenance)
+ if got.TargetFileSizeBytes != 536870912 {
+ t.Errorf("expected the property to win with 536870912, got %d", got.TargetFileSizeBytes)
+ }
+
+ base := baseTestConfig()
+ base.TablePropertiesOverride = false
+ got = resolveTableConfig(base, props, maintenance)
+ if got.TargetFileSizeBytes != 128*bytesPerMB {
+ t.Errorf("expected the maintenance config to win with %d, got %d", 128*bytesPerMB, got.TargetFileSizeBytes)
+ }
+}
+
+// A disabled type drops its operations rather than contributing settings.
+func TestResolveTableConfigIgnoresDisabledSettings(t *testing.T) {
+ base := baseTestConfig()
+ got := resolveTableConfig(base, nil, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {
+ Status: s3tables.MaintenanceStatusDisabled,
+ Settings: &s3tables.MaintenanceSettings{IcebergCompaction: &s3tables.IcebergCompactionSettings{TargetFileSizeMB: settingPtr(512)}},
+ },
+ }))
+
+ if got.TargetFileSizeBytes != base.TargetFileSizeBytes {
+ t.Errorf("expected disabled settings ignored, got %d", got.TargetFileSizeBytes)
+ }
+}
+
+func TestFilterDisabledOperations(t *testing.T) {
+ all := []string{"compact", "rewrite_position_delete_files", "expire_snapshots", "remove_orphans", "rewrite_manifests"}
+
+ if got := filterDisabledOperations(all, nil); len(got) != len(all) {
+ t.Errorf("expected no filtering without a configuration, got %v", got)
+ }
+
+ got := filterDisabledOperations(all, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {Status: s3tables.MaintenanceStatusDisabled},
+ s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval: {Status: s3tables.MaintenanceStatusDisabled},
+ }))
+ want := []string{"expire_snapshots"}
+ if len(got) != len(want) || got[0] != want[0] {
+ t.Errorf("expected %v, got %v", want, got)
+ }
+
+ if got := filterDisabledOperations(all, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {Status: s3tables.MaintenanceStatusEnabled},
+ })); len(got) != len(all) {
+ t.Errorf("expected an enabled type to filter nothing, got %v", got)
+ }
+}
+
+func TestMergeMaintenanceConfigurationTableWins(t *testing.T) {
+ bucket := maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval: {Status: s3tables.MaintenanceStatusEnabled},
+ s3tables.MaintenanceTypeIcebergCompaction: {Status: s3tables.MaintenanceStatusEnabled},
+ })
+ table := maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {Status: s3tables.MaintenanceStatusDisabled},
+ })
+
+ merged := mergeMaintenanceConfiguration(bucket, table)
+ if merged[s3tables.MaintenanceTypeIcebergCompaction].Status != s3tables.MaintenanceStatusDisabled {
+ t.Error("expected the table entry to win")
+ }
+ if merged[s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval].Status != s3tables.MaintenanceStatusEnabled {
+ t.Error("expected the bucket-only entry retained")
+ }
+
+ if got := mergeMaintenanceConfiguration(nil, table); len(got) != 1 {
+ t.Errorf("expected the table configuration passed through, got %v", got)
+ }
+ if got := mergeMaintenanceConfiguration(bucket, nil); len(got) != 2 {
+ t.Errorf("expected the bucket configuration passed through, got %v", got)
+ }
+}
+
+func TestParseMaintenanceConfiguration(t *testing.T) {
+ got, err := parseMaintenanceConfiguration(nil, "bucket")
+ if err != nil || got != nil {
+ t.Errorf("expected nil for a missing attribute, got %v (%v)", got, err)
+ }
+
+ // Unreadable must be an error, not an empty configuration: empty would run
+ // operations the operator disabled.
+ if _, err := parseMaintenanceConfiguration(map[string][]byte{s3tables.ExtendedKeyMaintenance: []byte("{")}, "bucket"); err == nil {
+ t.Error("expected an error for a malformed attribute")
+ }
+
+ data := []byte(`{"icebergCompaction":{"status":"disabled"}}`)
+ got, err = parseMaintenanceConfiguration(map[string][]byte{s3tables.ExtendedKeyMaintenance: data}, "bucket")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got[s3tables.MaintenanceTypeIcebergCompaction].Status != s3tables.MaintenanceStatusDisabled {
+ t.Errorf("expected compaction disabled, got %v", got)
+ }
+}
+
+// unreferencedDays large enough to overflow must not land a cutoff in the future.
+func TestResolveTableConfigClampsUnreferencedDays(t *testing.T) {
+ got := resolveTableConfig(baseTestConfig(), nil, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{
+ IcebergUnreferencedFileRemoval: &s3tables.IcebergUnreferencedFileRemovalSettings{UnreferencedDays: settingPtr(math.MaxInt64)},
+ },
+ },
+ }))
+
+ if got.OrphanOlderThanHours != maxOrphanOlderThanHours {
+ t.Fatalf("expected the cutoff clamped to %d, got %d", maxOrphanOlderThanHours, got.OrphanOlderThanHours)
+ }
+ if cutoff := time.Duration(got.OrphanOlderThanHours) * time.Hour; cutoff <= 0 {
+ t.Errorf("expected a positive cutoff duration, got %v", cutoff)
+ }
+
+ got = resolveTableConfig(baseTestConfig(), nil, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{
+ IcebergUnreferencedFileRemoval: &s3tables.IcebergUnreferencedFileRemovalSettings{UnreferencedDays: settingPtr(3)},
+ },
+ },
+ }))
+ if got.OrphanOlderThanHours != 72 {
+ t.Errorf("expected 3 days to be 72 hours, got %d", got.OrphanOlderThanHours)
+ }
+}
+
+// AWS marks a file non-current after unreferencedDays and deletes it
+// nonCurrentDays later; deleting in one step has to wait for both.
+func TestResolveTableConfigAddsNonCurrentWindow(t *testing.T) {
+ orphan := func(unreferenced, nonCurrent int64) Config {
+ return resolveTableConfig(baseTestConfig(), nil, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{
+ IcebergUnreferencedFileRemoval: &s3tables.IcebergUnreferencedFileRemovalSettings{
+ UnreferencedDays: settingPtr(unreferenced),
+ NonCurrentDays: settingPtr(nonCurrent),
+ },
+ },
+ },
+ }))
+ }
+
+ if got := orphan(3, 10); got.OrphanOlderThanHours != 13*24 {
+ t.Errorf("expected 3+10 days to be %d hours, got %d", 13*24, got.OrphanOlderThanHours)
+ }
+ if got := orphan(0, 10); got.OrphanOlderThanHours != 10*24 {
+ t.Errorf("expected nonCurrentDays alone to apply, got %d", got.OrphanOlderThanHours)
+ }
+ if got := orphan(math.MaxInt64, math.MaxInt64); got.OrphanOlderThanHours != maxOrphanOlderThanHours {
+ t.Errorf("expected the sum clamped, got %d", got.OrphanOlderThanHours)
+ }
+}
+
+func TestBuildJobStatus(t *testing.T) {
+ ranAt := time.Unix(1755250000, 0).UTC()
+
+ jobStatus := buildJobStatus(map[string]error{
+ "compact": nil,
+ "expire_snapshots": nil,
+ }, ranAt)
+
+ compaction := jobStatus[s3tables.MaintenanceTypeIcebergCompaction]
+ if compaction == nil || compaction.Status != s3tables.MaintenanceJobStatusSuccessful {
+ t.Fatalf("expected compaction successful, got %+v", compaction)
+ }
+ if compaction.LastRunTimestamp == nil || !compaction.LastRunTimestamp.Equal(ranAt) {
+ t.Errorf("expected lastRunTimestamp %v, got %v", ranAt, compaction.LastRunTimestamp)
+ }
+ if _, ok := jobStatus[s3tables.MaintenanceTypeIcebergUnreferencedFileRemoval]; ok {
+ t.Error("expected an operation that did not run to be left out")
+ }
+}
+
+// Several operations share one AWS job type, so one failure fails the type.
+func TestBuildJobStatusFailureWins(t *testing.T) {
+ jobStatus := buildJobStatus(map[string]error{
+ "compact": nil,
+ "rewrite_manifests": errors.New("commit conflict"),
+ }, time.Unix(1755250000, 0).UTC())
+
+ compaction := jobStatus[s3tables.MaintenanceTypeIcebergCompaction]
+ if compaction.Status != s3tables.MaintenanceJobStatusFailed {
+ t.Errorf("expected compaction failed, got %q", compaction.Status)
+ }
+ if compaction.FailureMessage != "commit conflict" {
+ t.Errorf("expected the failure message carried, got %q", compaction.FailureMessage)
+ }
+}
+
+func TestBuildJobStatusEmpty(t *testing.T) {
+ if got := buildJobStatus(nil, time.Now()); len(got) != 0 {
+ t.Errorf("expected an empty status, got %v", got)
+ }
+}
+
+func TestResolveTableConfigAppliesCompactionStrategy(t *testing.T) {
+ withStrategy := func(strategy string) Config {
+ return resolveTableConfig(baseTestConfig(), nil, maintenanceConfig(map[string]*s3tables.MaintenanceConfigurationValue{
+ s3tables.MaintenanceTypeIcebergCompaction: {
+ Status: s3tables.MaintenanceStatusEnabled,
+ Settings: &s3tables.MaintenanceSettings{IcebergCompaction: &s3tables.IcebergCompactionSettings{Strategy: strategy}},
+ },
+ }))
+ }
+
+ if got := withStrategy(s3tables.CompactionStrategySort); got.RewriteStrategy != "sort" {
+ t.Errorf("expected sort, got %q", got.RewriteStrategy)
+ }
+ if got := withStrategy(s3tables.CompactionStrategyBinpack); got.RewriteStrategy != "binpack" {
+ t.Errorf("expected binpack, got %q", got.RewriteStrategy)
+ }
+
+ // "auto" is carried through so the plan can pick per table.
+ if got := withStrategy(s3tables.CompactionStrategyAuto); got.RewriteStrategy != rewriteStrategyAuto {
+ t.Errorf("expected auto preserved, got %q", got.RewriteStrategy)
+ }
+}
+
+// AWS defines auto as sorting tables that declare a sort order and bin-packing
+// the rest, so it must not collapse to the worker default.
+func TestResolveCompactionRewritePlanAuto(t *testing.T) {
+ cfg := baseTestConfig()
+ cfg.RewriteStrategy = rewriteStrategyAuto
+
+ unsorted := buildTestMetadata(t, nil)
+ plan, err := resolveCompactionRewritePlan(cfg, unsorted)
+ if err != nil {
+ t.Fatalf("auto must not fail on an unsorted table: %v", err)
+ }
+ if plan.strategy != defaultRewriteStrategy {
+ t.Errorf("expected binpack for an unsorted table, got %q", plan.strategy)
+ }
+
+ // An explicit sort request on the same table is still an error, so auto is
+ // doing something the existing strategies did not.
+ cfg.RewriteStrategy = "sort"
+ if _, err := resolveCompactionRewritePlan(cfg, unsorted); err == nil {
+ t.Error("expected explicit sort to fail without a table sort order")
+ }
+}