From 8bb5c069ecc2e18e8271ec795384e5e201fd845a Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Mon, 30 Nov 2026 11:47:29 -0800 Subject: [PATCH] iceberg, s3tables: new tables take only fresh locations (#13160) * s3tables, iceberg, lance: the catalog assigns every new location; an existing name answers only a reader A REST create without a location gets /- (#12475) and a location another record holds is refused (#12473), but a location a client names is still taken: the REST create's location field and warehouse property, S3 Tables CreateTable and CreateView with a MetadataLocation, the Lance declare's location. A free location a client picks can be one another caller holds staged write credentials for (stage markers are not claims), or files no record claims any more. Separately, CreateTable of a name that already holds a table returns that table (ARN, version token, metadata location) to any caller who may create, including one who may not read it. - A REST create or create view naming a location (field or property, stage-create or not, the bare bucket included) is refused with 400 before anything is written; the location is always placeNewEntry's: /- in the bucket, or under the operator's ICEBERG_WAREHOUSE (no longer under a client's warehouse property). - A create commit uses a stage marker only when its assign-uuid matches the staged table's UUID (PyIceberg and Java send it); any other create commit is placed at a fresh -, never at the bare name path and never at another caller's staged location. Its updates may not set another location than the one assigned (400). - S3 Tables CreateTable and CreateView naming a MetadataLocation are refused with 400 (ErrClientTableLocation) unless the call is the process's own (WithCatalogAssignedLocation: the REST create, create view and create commit at the location they placed; the Lance declare at the dataset's name path and register at an existing dataset). AWS's CreateTable takes no location either. - A Lance declare naming a location is refused with 400 (register is for existing datasets). - CreateTable of an existing name answers the table only to a caller who may GetTable it; a caller who may only create gets 409 TableAlreadyExists and nothing about it. Tests: TestAClientCreateNamesNoLocation (positive controls: a client create without a location, the catalog's own create with one), TestARESTCreateNamesNoLocation, TestACreateCommitCannotSetAnotherLocation, TestACreateCommitTakesOnlyItsOwnStage (the stager's own commit is the positive control), TestCreateExistingTableAnswersOnlyAReaderWithIt (a reader gets the table). Existing tests adapted: the s3tables fixtures and request helpers run as the catalog's own calls (assignedCtx), as do the iceberg tests that seed tables through the manager; iceberg_create_table_conflict_test.go's creates send no location and newConflictEnv points placeNewEntry at conflictLocation, so its races still collide on one location; TestCreatePathsRefuseAnotherTablesLocation expects 400 for the three create paths and 409 for the register; TestCreateTableWithoutLocationUsesItsOwnDirectory drops the bare-bucket body; lance TestIcebergTablesAreInvisible seeds its Iceberg table as the catalog; TestDeclareOfAnExistingTableKeepsItsLocation expects 400 for a declare naming the index's location; TestDeregisterAndReregisterNeedUpdateTable (#12552) expects 409 instead of 404 for the register and the declare of a caller without GetTable: the table stays deregistered and nothing is vended. Each rule is red with it undone. Co-Authored-By: Claude Opus 5.5 * iceberg: a create may name a fresh location A REST CreateTable naming a location (Trino always sends one built from the namespace location, Spark LOCATION, PyIceberg location=) is accepted again when nothing is stored under it and no live stage holds it; a used or staged location answers 400. The check runs after the create's authorization and before anything is written. A bare-bucket location still gets the assigned -. CreateView always uses the assigned location: a view holds only metadata files. Co-Authored-By: Claude Opus 5.5 * lance: a declare may restate its name path as its location pylance and other namespace clients may send the location they expect; the dataset's own name path is accepted, any other location still answers 400. Co-Authored-By: Claude Opus 5.5 * iceberg: a commit cannot set another location on an existing table CommitTable and CommitTransaction applied a set-location update, so a table's metadata could name a location outside the directory its record holds. Such a commit now answers 400 and nothing is written. Co-Authored-By: Claude Opus 5.5 * iceberg: the fresh-location check pages through every stage marker Co-Authored-By: Claude Opus 5.5 * iceberg: a fresh location stays apart from stages and tables above or under it Co-Authored-By: Claude Opus 5.5 * iceberg: a create checks its location again after claiming it Co-Authored-By: Claude Opus 5.5 * s3tables, iceberg: a live stage holds its location against every create The catalog counts each live stage-create as a root of the record it would commit to, so a native create, register, rename or move over a stage's location is refused. The fresh-location check reads the same roots, so a stage also backs out of a record that claimed an ancestor after its first check. A location held by a record or stage answers 409, as the create gate already did. Co-Authored-By: Claude Opus 5.5 * iceberg: a create removes only the stages its location covers A create or commit used to drop every stage marker of its name, which freed the location of a stage whose credentials were still live. Expired markers now go with their staged metadata. Co-Authored-By: Claude Opus 5.5 * iceberg: an assigned stage location checks its claim again too Co-Authored-By: Claude Opus 5.5 * iceberg: a stage marker lasts as long as its vended credentials Co-Authored-By: Claude Opus 5.5 * iceberg: test a create that runs while a stage checks its claim Co-Authored-By: Claude Opus 5.5 * iceberg: a stage holds its location against a create of the same name A live stage-create now counts under its marker rather than under the record of its name, so a same-name create over its location is refused and a stage refuses a same-name table created over its location. Only a staged commit takes the location its own stage holds. Co-Authored-By: Claude Opus 5.5 * s3tables: a stage holds only its location against its own record's create A live stage keeps the path of the record it would commit to away from other records' files, but a create of that same record writes it: the stage then holds only its location against it. A stage at its name path can commit while a later stage of its name, elsewhere, is live. Co-Authored-By: Claude Opus 5.5 * iceberg: a staged commit's create gate reads its location as a create does The gate maps a metadata file's location to its table directory, so the bare location of a stage under a metadata directory resolved to the namespace and conflicted with the stage's own claim. Co-Authored-By: Claude Opus 5.5 * iceberg, lance: tests from master create through the catalog's own call Their creates name a location, which only the catalog's own calls may, and a caller who may only create gets 409 for an existing name whatever location its register names. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Javier de la Torre Co-authored-by: Claude Opus 5.5 --- weed/s3api/iceberg/commit_helpers.go | 19 +- weed/s3api/iceberg/handlers_commit.go | 28 +- weed/s3api/iceberg/handlers_table.go | 83 ++- weed/s3api/iceberg/handlers_transaction.go | 3 + weed/s3api/iceberg/handlers_view.go | 30 +- .../iceberg_create_table_conflict_test.go | 31 +- .../iceberg/iceberg_location_owner_test.go | 5 - .../iceberg/iceberg_register_table_test.go | 4 +- .../iceberg/iceberg_table_location_test.go | 635 ++++++++++++++++++ .../s3api/iceberg/iceberg_transaction_test.go | 8 +- weed/s3api/iceberg/stage_create.go | 191 +++++- weed/s3api/iceberg/vector_namespace_test.go | 2 +- weed/s3api/lance/handlers_table.go | 9 +- weed/s3api/lance/handlers_test.go | 37 +- weed/s3api/lance/vector_namespace_test.go | 9 +- weed/s3api/s3tables/filer_ops.go | 107 ++- weed/s3api/s3tables/filer_ops_race_test.go | 2 +- weed/s3api/s3tables/filer_ops_test.go | 2 +- weed/s3api/s3tables/handler.go | 2 + .../s3tables/handler_bind_authorized_test.go | 2 +- weed/s3api/s3tables/handler_bind_tags_test.go | 2 +- .../s3tables/handler_bucket_format_test.go | 7 +- .../handler_delete_create_race_test.go | 4 +- .../s3tables/handler_delete_decouple_test.go | 3 +- .../handler_delete_keeps_uploads_test.go | 2 +- .../s3tables/handler_existence_hiding_test.go | 35 +- .../s3tables/handler_location_owner_test.go | 85 +++ .../handler_namespace_keeps_data_test.go | 2 +- weed/s3api/s3tables/handler_ownerless_test.go | 7 +- .../s3tables/handler_policy_deny_test.go | 3 +- weed/s3api/s3tables/handler_rename_test.go | 6 +- weed/s3api/s3tables/handler_table.go | 36 + .../handler_update_after_rename_test.go | 6 +- .../s3api/s3tables/handler_update_cas_test.go | 7 +- weed/s3api/s3tables/handler_view.go | 4 + .../s3tables/handler_view_rename_test.go | 4 +- .../handler_warehouse_location_test.go | 2 +- weed/s3api/s3tables/manager_test.go | 4 +- weed/s3api/s3tables/vector_namespace_test.go | 10 +- 39 files changed, 1266 insertions(+), 172 deletions(-) diff --git a/weed/s3api/iceberg/commit_helpers.go b/weed/s3api/iceberg/commit_helpers.go index 65cac5a4ee..22e9f963a1 100644 --- a/weed/s3api/iceberg/commit_helpers.go +++ b/weed/s3api/iceberg/commit_helpers.go @@ -231,6 +231,13 @@ func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommi } } + if strings.TrimSuffix(newMetadata.Location(), "/") != strings.TrimSuffix(input.location, "/") { + return nil, &icebergRequestError{ + status: http.StatusBadRequest, + errType: "BadRequestException", + message: s3tables.ErrClientTableLocation.Error(), + } + } metadataBucket, metadataPath, err := parseS3Location(input.location) if err != nil { return nil, &icebergRequestError{ @@ -279,7 +286,7 @@ func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommi } createErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { mgrClient := s3tables.NewManagerClient(client) - return s.tablesManager.Execute(createCtx, mgrClient, "CreateTable", createReq, &createResp, input.identityName) + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(createCtx), mgrClient, "CreateTable", createReq, &createResp, input.identityName) }) tableCreatedConcurrently := &icebergRequestError{ status: http.StatusConflict, @@ -312,7 +319,7 @@ func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommi if markerBucket == "" { markerBucket = metadataBucket } - if markerErr := s.deleteStageCreateMarkers(ctx, markerBucket, input.namespace, input.tableName); markerErr != nil { + if markerErr := s.deleteStageCreateMarkers(ctx, markerBucket, input.namespace, input.tableName, input.location); markerErr != nil { glog.V(1).Infof("Iceberg: failed to cleanup stage-create markers for %s.%s after finalize: %v", flattenNamespacePath(input.namespace), input.tableName, markerErr) } @@ -396,3 +403,11 @@ func (s *Server) authorizeViewCommit(ctx context.Context, bucketARN string, name glog.V(1).Infof("Iceberg: view commit authorization for %s failed: %v", viewName, err) return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to authorize commit: " + err.Error()} } + +// keepsLocation refuses a commit whose set-location would move an existing table. +func keepsLocation(base, updated table.Metadata) *icebergRequestError { + if strings.TrimSuffix(updated.Location(), "/") != strings.TrimSuffix(base.Location(), "/") { + return &icebergRequestError{http.StatusBadRequest, "BadRequestException", "a table's location cannot be changed"} + } + return nil +} diff --git a/weed/s3api/iceberg/handlers_commit.go b/weed/s3api/iceberg/handlers_commit.go index c6b4c42c65..6feb05e867 100644 --- a/weed/s3api/iceberg/handlers_commit.go +++ b/weed/s3api/iceberg/handlers_commit.go @@ -111,16 +111,17 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { }) if err != nil { if isS3TablesNotFound(err) { - location := fmt.Sprintf("s3://%s/%s", bucketName, path.Join(flattenNamespacePath(namespace), tableName)) + location := placeNewEntry(bucketName, path.Join(flattenNamespacePath(namespace), tableName+"-"+uuid.New().String())) tableUUID := generatedLegacyUUID baseMetadataVersion := 0 baseMetadataLocation := "" var baseMetadata table.Metadata var latestMarker *stageCreateMarker - if stageCreateEnabled { + // only the caller's own stage, matched by its assign-uuid + if stagedUUID := assignedTableUUID(raw.Updates); stageCreateEnabled && stagedUUID != "" { var markerErr error - latestMarker, markerErr = s.loadLatestStageCreateMarker(r.Context(), bucketName, namespace, tableName, assignedTableUUID(raw.Updates)) + latestMarker, markerErr = s.loadLatestStageCreateMarker(r.Context(), bucketName, namespace, tableName, stagedUUID) if markerErr != nil { writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to load stage-create marker: "+markerErr.Error()) return @@ -180,9 +181,18 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName)) return } + var stagedAt time.Time + if latestMarker != nil { + stagedAt, _ = time.Parse(time.RFC3339Nano, latestMarker.CreatedAt) + } + authCtx := r.Context() + if !stagedAt.IsZero() { + authCtx = s3tables.WithTableStagedAt(authCtx, stagedAt) + } // From here the commit creates the table, writing its metadata - // file before the create that authorizes it. - if authErr := s.authorizeCreateTable(r.Context(), bucketARN, namespace, tableName, identityName, location); authErr != nil { + // file before the create that authorizes it. The gate takes a + // metadata file's location, as that create passes it. + if authErr := s.authorizeCreateTable(authCtx, bucketARN, namespace, tableName, identityName, location+"/metadata/v1.metadata.json"); authErr != nil { writeManagerError(w, authErr) return } @@ -219,10 +229,6 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { repairManifests(location) - var stagedAt time.Time - if latestMarker != nil { - stagedAt, _ = time.Parse(time.RFC3339Nano, latestMarker.CreatedAt) - } result, reqErr := s.finalizeCreateOnCommit(r.Context(), createOnCommitInput{ bucketARN: bucketARN, markerBucket: bucketName, @@ -338,6 +344,10 @@ func (s *Server) handleUpdateTable(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "BadRequestException", "Failed to build new metadata: "+err.Error()) return } + if reqErr := keepsLocation(currentMetadata, newMetadata); reqErr != nil { + writeError(w, reqErr.status, reqErr.errType, reqErr.message) + return + } metadataVersion := getResp.MetadataVersion + 1 metadataFileName := fmt.Sprintf("v%d.metadata.json", metadataVersion) diff --git a/weed/s3api/iceberg/handlers_table.go b/weed/s3api/iceberg/handlers_table.go index 136fc5fd55..010d1d1eb1 100644 --- a/weed/s3api/iceberg/handlers_table.go +++ b/weed/s3api/iceberg/handlers_table.go @@ -124,6 +124,15 @@ func (s *Server) authorizeCreateTable(ctx context.Context, bucketARN string, nam }) } +// placeNewEntry is the catalog-assigned location of a new table or view; a +// variable so tests can make two creates collide. +var placeNewEntry = func(bucketName, entryPath string) string { + if warehouse := strings.TrimSuffix(os.Getenv("ICEBERG_WAREHOUSE"), "/"); warehouse != "" { + return fmt.Sprintf("%s/%s", warehouse, entryPath) + } + return fmt.Sprintf("s3://%s/%s", bucketName, entryPath) +} + // handleCreateTable creates a new table. func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) @@ -159,29 +168,18 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { // A location the server picks is unique to the table, so its files never // sit under a name a rename can hand to another table. tablePath := path.Join(flattenNamespacePath(namespace), req.Name+"-"+tableUUID.String()) - location := strings.TrimSuffix(req.Location, "/") - if location == "" { - if req.Properties != nil { - if warehouse := strings.TrimSuffix(req.Properties["warehouse"], "/"); warehouse != "" { - location = fmt.Sprintf("%s/%s", warehouse, tablePath) - } - } - if location == "" { - if warehouse := strings.TrimSuffix(os.Getenv("ICEBERG_WAREHOUSE"), "/"); warehouse != "" { - location = fmt.Sprintf("%s/%s", warehouse, tablePath) - } - } - if location == "" { - location = fmt.Sprintf("s3://%s/%s", bucketName, tablePath) - } - } else { - parsedBucket, parsedPath, err := parseS3Location(location) + location := placeNewEntry(bucketName, tablePath) + clientLocation := strings.TrimSuffix(strings.TrimSpace(req.Location), "/") + if clientLocation != "" { + _, clientPath, err := parseS3Location(clientLocation) if err != nil { writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid table location: "+err.Error()) return } - if parsedPath == "" { - location = fmt.Sprintf("s3://%s/%s", parsedBucket, tablePath) + if clientPath == "" { + clientLocation = "" + } else { + location = clientLocation } } @@ -272,6 +270,12 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "BadRequestException", err.Error()) return } + if clientLocation != "" { + if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, metadataPath, location, "", true); reqErr != nil { + writeError(w, reqErr.status, reqErr.errType, reqErr.message) + return + } + } // Stage-create persists metadata in the internal staged area and skips S3Tables registration. if req.StageCreate { @@ -283,16 +287,24 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { return } stagedMetadataLocation := fmt.Sprintf("s3://%s/%s/metadata/%s", metadataBucket, stagedTablePath, metadataFileName) - // The marker is how the commit finds the location handed out here. - if markerErr := s.writeStageCreateMarker(r.Context(), bucketName, namespace, tableName, tableUUID, location, stagedMetadataLocation); markerErr != nil { - glog.V(1).Infof("Iceberg: failed to persist stage-create marker for %s.%s: %v", flattenNamespacePath(namespace), tableName, markerErr) - writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save stage-create marker") - return - } // The staged table is not registered yet, so there is nothing to // authorize an update against; the create gate above is the write // authority for the prefix the staged table will occupy. config, storageCredentials := s.buildFileIOConfig(r, location, func() bool { return true }) + // The marker is how the commit finds the location handed out here, and + // holds that location for as long as the credentials can write it. + if markerErr := s.writeStageCreateMarker(r.Context(), bucketName, namespace, tableName, tableUUID, location, stagedMetadataLocation, vendedUntil(config)); markerErr != nil { + glog.V(1).Infof("Iceberg: failed to persist stage-create marker for %s.%s: %v", flattenNamespacePath(namespace), tableName, markerErr) + writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save stage-create marker") + return + } + if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, metadataPath, location, tableUUID.String(), true); reqErr != nil { + if err := s.deleteStageCreate(r.Context(), bucketName, namespace, tableName, tableUUID); err != nil { + glog.V(1).Infof("Iceberg: failed to remove stage-create for %s.%s: %v", flattenNamespacePath(namespace), tableName, err) + } + writeError(w, reqErr.status, reqErr.errType, reqErr.message) + return + } result := LoadTableResult{ MetadataLocation: metadataLocation, Metadata: metadata, @@ -311,6 +323,13 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save metadata file: "+err.Error()) return } + if clientLocation != "" { + if reqErr := s.checkFreshLocation(r.Context(), bucketName, namespace, tableName, metadataPath, location, "", false); reqErr != nil { + s.discardStagedMetadata(r.Context(), metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken) + writeError(w, reqErr.status, reqErr.errType, reqErr.message) + return + } + } // Use S3 Tables manager to create table createReq := &s3tables.CreateTableRequest{ @@ -331,7 +350,7 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { mgrClient := s3tables.NewManagerClient(client) - return s.tablesManager.Execute(r.Context(), mgrClient, "CreateTable", createReq, &createResp, identityName) + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(r.Context()), mgrClient, "CreateTable", createReq, &createResp, identityName) }) if err == nil && createResp.MetadataLocation != metadataLocation { // Another create registered the name first. @@ -363,7 +382,7 @@ func (s *Server) handleCreateTable(w http.ResponseWriter, r *http.Request) { return } - if markerErr := s.deleteStageCreateMarkers(r.Context(), bucketName, namespace, tableName); markerErr != nil { + if markerErr := s.deleteStageCreateMarkers(r.Context(), bucketName, namespace, tableName, location); markerErr != nil { glog.V(1).Infof("Iceberg: failed to cleanup stage-create markers for %s.%s after create: %v", flattenNamespacePath(namespace), tableName, markerErr) } @@ -715,6 +734,16 @@ func (s *Server) vendCredentials(r *http.Request, location string, canWrite func return vended } +// vendedUntil returns when the credentials in config expire, or zero if it +// carries none. +func vendedUntil(config iceberg.Properties) time.Time { + ms, err := strconv.ParseInt(config["s3.session-token-expires-at-ms"], 10, 64) + if err != nil { + return time.Time{} + } + return time.UnixMilli(ms) +} + // mayUpdateTable reports whether the caller may commit to the table the // credentials would cover. The session stays read-only when it may not, so // the vend carries no more authority than the caller holds at the catalog. diff --git a/weed/s3api/iceberg/handlers_transaction.go b/weed/s3api/iceberg/handlers_transaction.go index 34dcf28a45..7160bc8e05 100644 --- a/weed/s3api/iceberg/handlers_transaction.go +++ b/weed/s3api/iceberg/handlers_transaction.go @@ -220,6 +220,9 @@ func (s *Server) prepareTableCommit(ctx context.Context, bucketName, bucketARN, if err != nil { return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "Failed to build new metadata: " + err.Error()} } + if reqErr := keepsLocation(currentMetadata, newMetadata); reqErr != nil { + return nil, reqErr + } metadataVersion := getResp.MetadataVersion + 1 metadataFileName := fmt.Sprintf("v%d.metadata.json", metadataVersion) diff --git a/weed/s3api/iceberg/handlers_view.go b/weed/s3api/iceberg/handlers_view.go index 634b01ccb6..f791a9b9d8 100644 --- a/weed/s3api/iceberg/handlers_view.go +++ b/weed/s3api/iceberg/handlers_view.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "net/http" - "os" "path" "strings" "time" @@ -102,31 +101,8 @@ func (s *Server) handleCreateView(w http.ResponseWriter, r *http.Request) { identityName := s3_constants.GetIdentityNameFromContext(r) viewPath := path.Join(flattenNamespacePath(namespace), req.Name+"-"+uuid.NewString()) - location := strings.TrimSuffix(req.Location, "/") - if location == "" { - if req.Properties != nil { - if warehouse := strings.TrimSuffix(req.Properties["warehouse"], "/"); warehouse != "" { - location = fmt.Sprintf("%s/%s", warehouse, viewPath) - } - } - if location == "" { - if warehouse := strings.TrimSuffix(os.Getenv("ICEBERG_WAREHOUSE"), "/"); warehouse != "" { - location = fmt.Sprintf("%s/%s", warehouse, viewPath) - } - } - if location == "" { - location = fmt.Sprintf("s3://%s/%s", bucketName, viewPath) - } - } else { - parsedBucket, parsedPath, err := parseS3Location(location) - if err != nil { - writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid view location: "+err.Error()) - return - } - if parsedPath == "" { - location = fmt.Sprintf("s3://%s/%s", parsedBucket, viewPath) - } - } + // a view holds only metadata files, so a client-named location is not used + location := placeNewEntry(bucketName, viewPath) metadataBucket, metadataPath, err := parseS3Location(location) if err != nil { @@ -187,7 +163,7 @@ func (s *Server) handleCreateView(w http.ResponseWriter, r *http.Request) { var createResp s3tables.CreateViewResponse err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { mgrClient := s3tables.NewManagerClient(client) - return s.tablesManager.Execute(r.Context(), mgrClient, "CreateView", createReq, &createResp, identityName) + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(r.Context()), mgrClient, "CreateView", createReq, &createResp, identityName) }) if err != nil { if isViewAlreadyExists(err) { diff --git a/weed/s3api/iceberg/iceberg_create_table_conflict_test.go b/weed/s3api/iceberg/iceberg_create_table_conflict_test.go index 12e5122688..b173b6db5e 100644 --- a/weed/s3api/iceberg/iceberg_create_table_conflict_test.go +++ b/weed/s3api/iceberg/iceberg_create_table_conflict_test.go @@ -14,6 +14,7 @@ import ( "strings" "sync" "testing" + "time" "github.com/apache/iceberg-go/table" "github.com/google/uuid" @@ -114,6 +115,12 @@ type conflictEnv struct { func newConflictEnv(t *testing.T) *conflictEnv { t.Helper() + // Every create lands on conflictLocation, as two creates naming one + // location did before client locations were refused, so the + // catalog's placement is what the races here share. + placed := placeNewEntry + placeNewEntry = func(string, string) string { return conflictLocation } + t.Cleanup(func() { placeNewEntry = placed }) filer := s3tablestest.Start(t) hooks := &filerHooks{} server := NewServer(hookedFiler{base: s3tables.NewManagerClient(filer.Client), hooks: hooks}, openAuthenticator{}) @@ -134,7 +141,7 @@ func newConflictEnv(t *testing.T) *conflictEnv { func (e *conflictEnv) adminDo(op string, req, resp interface{}) { e.t.Helper() - if err := e.admin.Execute(e.t.Context(), s3tables.NewManagerClient(e.filer.Client), op, req, resp, ""); err != nil { + if err := e.admin.Execute(s3tables.WithCatalogAssignedLocation(e.t.Context()), s3tables.NewManagerClient(e.filer.Client), op, req, resp, ""); err != nil { e.t.Fatalf("%s: %v", op, err) } } @@ -358,7 +365,7 @@ func TestCreateTableKeepsUnregisteredMetadataFile(t *testing.T) { t.Fatal(err) } - rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody("col", "")) if rec.Code != http.StatusOK { t.Fatalf("create = %d (%s)", rec.Code, rec.Body.String()) } @@ -399,7 +406,7 @@ func TestConcurrentCreateTableHasOneWinner(t *testing.T) { defer done.Done() ready.Done() <-start - rec := e.createTable(conflictTableBody(fmt.Sprintf("col_%d", i), `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody(fmt.Sprintf("col_%d", i), "")) codes[i] = rec.Code }() } @@ -450,7 +457,7 @@ func TestConcurrentCreateTableHasOneWinner(t *testing.T) { func TestOverlappingCreatesStageApart(t *testing.T) { e := newConflictEnv(t) body := func(column string) string { - return conflictTableBody(column, `"location":"`+conflictLocation+`"`) + return conflictTableBody(column, "") } isMetadataFile := func(in *filer_pb.CreateEntryRequest) bool { return !in.Entry.IsDirectory && strings.HasSuffix(in.Entry.Name, ".metadata.json") @@ -550,7 +557,7 @@ func TestCreateTableDiscardsFileWhenNameWasTakenMidFlight(t *testing.T) { e.registerWinner(winnerLocation, winnerUUID) } - rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody("col", "")) if !registered { t.Fatal("the competing registration never ran") } @@ -572,7 +579,7 @@ func TestCreateTableDiscardsFileWhenNameWasTakenMidFlight(t *testing.T) { func TestLosingCreateKeepsReplacementAtReusedPath(t *testing.T) { for name, create := range map[string]func(t *testing.T, e *conflictEnv){ "create table": func(t *testing.T, e *conflictEnv) { - if rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)); rec.Code != http.StatusConflict { + if rec := e.createTable(conflictTableBody("col", "")); rec.Code != http.StatusConflict { t.Fatalf("create = %d (%s), want 409", rec.Code, rec.Body.String()) } }, @@ -651,7 +658,7 @@ func TestCreateTableStagedFileOnRegistrationFailure(t *testing.T) { return nil } - rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody("col", "")) if rec.Code != http.StatusInternalServerError { t.Fatalf("create = %d (%s), want 500", rec.Code, rec.Body.String()) } @@ -672,7 +679,7 @@ func TestCreateTableStagedFileOnRegistrationFailure(t *testing.T) { e.adminDo("DeleteNamespace", &s3tables.DeleteNamespaceRequest{TableBucketARN: e.arn, Namespace: []string{conflictNamespace}}, nil) } - rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody("col", "")) if !revoked { t.Fatal("the namespace was never removed") } @@ -719,7 +726,7 @@ func (e *conflictEnv) armSurvivingConflict(compete func(e *conflictEnv)) *bool { func TestCreateKeepsFileOfRecordThatSurvivedConflict(t *testing.T) { creates := map[string]func(t *testing.T, e *conflictEnv) (int, string){ "create table": func(t *testing.T, e *conflictEnv) (int, string) { - rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody("col", "")) if rec.Code == http.StatusOK { return rec.Code, "" } @@ -829,7 +836,7 @@ func TestCreateFailingToUnmarkRecordAnotherAdopted(t *testing.T) { } } - rec := e.createTable(conflictTableBody("col", `"location":"`+conflictLocation+`"`)) + rec := e.createTable(conflictTableBody("col", "")) if !adopted { t.Fatal("the competing create never adopted the marked record") } @@ -902,7 +909,7 @@ func (e *conflictEnv) finalizeInput(tableUUID uuid.UUID) createOnCommitInput { // not the v1.metadata.json the winner's catalog record points at. func TestFinalizeCreateOnCommitLosesToExistingTable(t *testing.T) { e := newConflictEnv(t) - if rec := e.createTable(conflictTableBody("winner_col", `"location":"`+conflictLocation+`"`)); rec.Code != http.StatusOK { + if rec := e.createTable(conflictTableBody("winner_col", "")); rec.Code != http.StatusOK { t.Fatalf("create = %d (%s)", rec.Code, rec.Body.String()) } record := e.mustRecord() @@ -972,7 +979,7 @@ func TestStageCreateMarkerKeepsADirectoryCreatedSinceTheLookup(t *testing.T) { e.filer.Put(bucketDir, stageCreateMarkerDirName, attrs) } } - if err := e.server.writeStageCreateMarker(t.Context(), conflictBucket, []string{conflictNamespace}, conflictTable, uuid.New(), conflictLocation, ""); err != nil { + if err := e.server.writeStageCreateMarker(t.Context(), conflictBucket, []string{conflictNamespace}, conflictTable, uuid.New(), conflictLocation, "", time.Time{}); err != nil { t.Fatalf("write stage-create marker: %v", err) } if got := e.filer.Get(bucketDir, stageCreateMarkerDirName); got == nil || string(got.Extended["probe"]) != "kept" { diff --git a/weed/s3api/iceberg/iceberg_location_owner_test.go b/weed/s3api/iceberg/iceberg_location_owner_test.go index 6438631857..ae3d0b2bc0 100644 --- a/weed/s3api/iceberg/iceberg_location_owner_test.go +++ b/weed/s3api/iceberg/iceberg_location_owner_test.go @@ -75,11 +75,6 @@ func TestCreatePathsRefuseAnotherTablesLocation(t *testing.T) { s.handleCreateTable(w, withActions(r, "mallory", creatorActions...)) return w }, - "create-view": func(s *Server, _ string) *httptest.ResponseRecorder { - w := httptest.NewRecorder() - s.handleCreateView(w, withActions(createViewAt(t, "alias", ordersLocation), "mallory", creatorActions...)) - return w - }, } for name, run := range cases { t.Run(name, func(t *testing.T) { diff --git a/weed/s3api/iceberg/iceberg_register_table_test.go b/weed/s3api/iceberg/iceberg_register_table_test.go index 788fc56816..117de37b86 100644 --- a/weed/s3api/iceberg/iceberg_register_table_test.go +++ b/weed/s3api/iceberg/iceberg_register_table_test.go @@ -162,7 +162,7 @@ func storedMetadata(t *testing.T, s *Server, fc *memFiler, name string) *s3table t.Helper() var getResp s3tables.GetTableResponse err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "GetTable", &s3tables.GetTableRequest{ + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(context.Background()), s3tables.NewManagerClient(client), "GetTable", &s3tables.GetTableRequest{ TableBucketARN: buildTableBucketARN(registerTestBucket), Namespace: []string{"finance"}, Name: name, @@ -239,7 +239,7 @@ func TestLoadTableReadsMetadataFileOfOlderRegistration(t *testing.T) { // The record an older RegisterTable left: the location and nothing else. err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(context.Background()), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ TableBucketARN: buildTableBucketARN(registerTestBucket), Namespace: []string{"finance"}, Name: "events", diff --git a/weed/s3api/iceberg/iceberg_table_location_test.go b/weed/s3api/iceberg/iceberg_table_location_test.go index a4d18d67c4..fc09479bc3 100644 --- a/weed/s3api/iceberg/iceberg_table_location_test.go +++ b/weed/s3api/iceberg/iceberg_table_location_test.go @@ -3,16 +3,20 @@ package iceberg import ( "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "path" "strings" "testing" + "time" "github.com/google/uuid" "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/s3api/s3tables" + "google.golang.org/grpc" ) // A table created without a location gets a directory named after it and its @@ -49,6 +53,66 @@ func TestCreateTableWithoutLocationUsesItsOwnDirectory(t *testing.T) { } } +// A REST create may name a location only while nothing is stored under it and +// no live stage holds it; a view always gets the location the catalog assigns. +func TestARESTCreateTakesOnlyAFreshLocation(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := &writeLogFiler{memFiler: newMemFiler()} + seedNamespace(fc.memFiler, bucket, "finance", "alice") + used := path.Join(s3tables.TablesPath, bucket, "finance", "used") + fc.entries[used] = &filer_pb.Entry{Name: "used", IsDirectory: true} + fc.entries[path.Join(used, "data")] = &filer_pb.Entry{Name: "data", IsDirectory: true} + s := NewServer(fc, nil) + create := func(body string) (int, string) { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice")) + var res struct { + Metadata struct { + Location string `json:"location"` + } `json:"metadata"` + } + _ = json.Unmarshal(w.Body.Bytes(), &res) + return w.Code, res.Metadata.Location + } + + if code, location := create(`{"name":"fresh","location":"s3://warehouse/finance/fresh"}`); code != http.StatusOK || location != "s3://warehouse/finance/fresh" { + t.Errorf("create at a fresh location: %d at %q, want 200 there", code, location) + } + _, staged := create(`{"name":"orders","stage-create":true}`) + if staged == "" { + t.Fatal("stage-create returned no location") + } + for name, c := range map[string]struct { + body string + want int + }{ + "location with files": {`{"name":"mine1","location":"s3://warehouse/finance/used"}`, http.StatusBadRequest}, + "another caller's stage": {`{"name":"mine2","location":"` + staged + `"}`, http.StatusConflict}, + "stage over a stage": {`{"name":"mine3","location":"` + staged + `","stage-create":true}`, http.StatusConflict}, + } { + fc.created = nil + if code, _ := create(c.body); code != c.want { + t.Errorf("%s: status = %d, want %d", name, code, c.want) + } + if len(fc.created) != 0 { + t.Errorf("%s: a refused create wrote %v", name, fc.created) + } + } + + w := httptest.NewRecorder() + s.handleCreateView(w, withActions(createViewAt(t, "v", "s3://warehouse/finance/used"), "alice", creatorActions...)) + var view struct { + Metadata struct { + Location string `json:"location"` + } `json:"metadata"` + } + _ = json.Unmarshal(w.Body.Bytes(), &view) + if w.Code != http.StatusOK || !strings.HasPrefix(view.Metadata.Location, "s3://warehouse/finance/v-") { + t.Errorf("create view naming a location: %d at %q, want 200 at an assigned location", w.Code, view.Metadata.Location) + } +} + func TestTableLocation(t *testing.T) { for name, tc := range map[string]struct { resp s3tables.GetTableResponse @@ -218,3 +282,574 @@ func raceAtSecondLookup(fc *memFiler, record string, create func()) { } } } + +// A create commit's metadata names the location the catalog assigned it: a +// set-location elsewhere would have the table's files claimed at one location +// and written at another, and is refused with 400. +func TestACreateCommitCannotSetAnotherLocation(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + s := NewServer(fc, nil) + commit := func(name, updates string) (int, string) { + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/"+name, + strings.NewReader(`{"requirements":[{"type":"assert-create"}],"updates":[`+updates+`]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": name}) + w := httptest.NewRecorder() + s.handleUpdateTable(w, withActions(r, "alice", "s3tables:CreateTable", "s3tables:UpdateTable", "s3tables:GetTable")) + return w.Code, w.Body.String() + } + if code, body := commit("moved", `{"action":"set-location","location":"s3://warehouse/finance/elsewhere"}`); code != http.StatusBadRequest { + t.Errorf("create commit with a set-location elsewhere: %d (%.200s), want 400", code, body) + } + if _, ok := fc.entries[s3tables.GetTablePath("warehouse", "finance", "moved")]; ok { + t.Error("a refused create commit left a catalog record") + } + // positive control: the same create commit without it + if code, body := commit("kept", ""); code != http.StatusOK { + t.Errorf("create commit: %d (%.200s), want 200", code, body) + } +} + +// A create commit picks up a stage only by the UUID that stage assigned: a +// commit without assign-uuid, or with another UUID, is placed at a fresh +// location of its own, never at a location another caller staged (and holds +// write credentials for). The stager's own commit, carrying the staged UUID +// as PyIceberg and Java send it, still lands on its stage. +func TestACreateCommitTakesOnlyItsOwnStage(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + s := NewServer(fc, nil) + stage := func(name string) (location, tableUUID string) { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, "warehouse", "finance", `{"name":"`+name+`","stage-create":true}`, "alice")) + if w.Code != http.StatusOK { + t.Fatalf("stage %s: %d (%.200s)", name, w.Code, w.Body.String()) + } + var res struct { + Metadata struct { + Location string `json:"location"` + TableUUID string `json:"table-uuid"` + } `json:"metadata"` + } + if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil || res.Metadata.Location == "" { + t.Fatalf("stage %s: no location in %.200s (%v)", name, w.Body.String(), err) + } + return strings.TrimSuffix(res.Metadata.Location, "/"), res.Metadata.TableUUID + } + commit := func(caller, name, updates string) (int, string) { + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/"+name, + strings.NewReader(`{"requirements":[{"type":"assert-create"}],"updates":[`+updates+`]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": name}) + w := httptest.NewRecorder() + s.handleUpdateTable(w, withActions(r, caller, "s3tables:CreateTable", "s3tables:UpdateTable", "s3tables:GetTable")) + var res struct { + MetadataLocation string `json:"metadata-location"` + } + _ = json.Unmarshal(w.Body.Bytes(), &res) + return w.Code, res.MetadataLocation + } + + staged, _ := stage("orders") + code, got := commit("bob", "orders", "") + if code != http.StatusOK { + t.Fatalf("bob's create commit: %d, want 200", code) + } + if strings.HasPrefix(got, staged+"/") { + t.Errorf("bob's create commit landed on alice's staged location %s", got) + } + if !strings.HasPrefix(got, "s3://warehouse/finance/orders-") { + t.Errorf("a create commit without a stage is placed at %s, want a fresh finance/orders-", got) + } + + // positive control: the stager's own commit names the staged UUID + staged, stagedUUID := stage("invoices") + code, got = commit("alice", "invoices", `{"action":"assign-uuid","uuid":"`+stagedUUID+`"}`) + if code != http.StatusOK || !strings.HasPrefix(got, staged+"/") { + t.Errorf("the stager's create commit: %d at %s, want 200 at %s", code, got, staged) + } +} + +// A commit or a transaction on an existing table cannot set another location. +func TestACommitCannotMoveATable(t *testing.T) { + fc := newMemFiler() + seedNamespace(fc, "warehouse", "finance", "alice") + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, "warehouse", "finance", `{"name":"orders"}`, "alice")) + if w.Code != http.StatusOK { + t.Fatalf("create: %d (%.200s)", w.Code, w.Body.String()) + } + before := string(fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")].Extended[s3tables.ExtendedKeyMetadata]) + commit := func(updates string) int { + r := httptest.NewRequest(http.MethodPost, "/v1/warehouse/namespaces/finance/tables/orders", + strings.NewReader(`{"requirements":[],"updates":[`+updates+`]}`)) + r = mux.SetURLVars(r, map[string]string{"prefix": "warehouse", "namespace": "finance", "table": "orders"}) + w := httptest.NewRecorder() + s.handleUpdateTable(w, withActions(r, "alice", "s3tables:UpdateTable", "s3tables:GetTable")) + return w.Code + } + moveTo := `{"action":"set-location","location":"s3://warehouse/finance/elsewhere"}` + if code := commit(moveTo); code != http.StatusBadRequest { + t.Errorf("commit with set-location elsewhere: %d, want 400", code) + } + tr := httptest.NewRequest(http.MethodPost, "/v1/warehouse/transactions/commit", strings.NewReader( + `{"table-changes":[{"identifier":{"namespace":["finance"],"name":"orders"},"requirements":[],"updates":[`+moveTo+`]}]}`)) + tr = mux.SetURLVars(tr, map[string]string{"prefix": "warehouse"}) + tw := httptest.NewRecorder() + s.handleCommitTransaction(tw, withActions(tr, "alice", "s3tables:UpdateTable", "s3tables:GetTable")) + if tw.Code != http.StatusBadRequest { + t.Errorf("transaction with set-location elsewhere: %d (%.200s), want 400", tw.Code, tw.Body.String()) + } + if after := string(fc.entries[s3tables.GetTablePath("warehouse", "finance", "orders")].Extended[s3tables.ExtendedKeyMetadata]); after != before { + t.Error("a refused move changed the table") + } + if code := commit(`{"action":"set-properties","updates":{"k":"v"}}`); code != http.StatusOK { + t.Errorf("plain commit: %d, want 200", code) + } +} + +// listingCapFiler answers a listing that names no limit with a few entries, +// as a filer's dirListLimit does. +type listingCapFiler struct{ *memFiler } + +func (f *listingCapFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error { + return fn(f) +} + +func (f *listingCapFiler) ListEntries(ctx context.Context, in *filer_pb.ListEntriesRequest, opts ...grpc.CallOption) (filer_pb.SeaweedFiler_ListEntriesClient, error) { + if in.Limit == 0 { + in = &filer_pb.ListEntriesRequest{Directory: in.Directory, Prefix: in.Prefix, StartFromFileName: in.StartFromFileName, InclusiveStartFrom: in.InclusiveStartFrom, Limit: 3} + } + return f.memFiler.ListEntries(ctx, in, opts...) +} + +func TestAFreshLocationCheckReadsEveryStage(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := &listingCapFiler{memFiler: newMemFiler()} + seedNamespace(fc.memFiler, bucket, "finance", "alice") + markers := seedStageDirs(fc.memFiler, bucket, "finance") + for i := 0; i <= stageListPageSize; i++ { + name := fmt.Sprintf("t%05d", i) + fc.seed(path.Join(markers, name), &filer_pb.Entry{Name: name, IsDirectory: true}) + } + live, _ := json.Marshal(stageCreateMarker{ + Location: "s3://warehouse/finance/held", + ExpiresAt: time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano), + }) + fc.seed(path.Join(markers, fmt.Sprintf("t%05d", stageListPageSize), "x.json"), &filer_pb.Entry{Name: "x.json", Content: live}) + + w := httptest.NewRecorder() + NewServer(fc, nil).handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"mine","location":"s3://warehouse/finance/held"}`, "alice")) + if w.Code != http.StatusConflict { + t.Fatalf("create at a location a stage past the first page holds: %d %s, want 409", w.Code, w.Body.String()) + } +} + +// seedStageDirs adds the directories a stage-create marker of namespace sits +// under and returns the namespace's marker directory. +func seedStageDirs(fc *memFiler, bucket, namespace string) string { + staged := path.Join(s3tables.TablesPath, bucket, stageCreateMarkerDirName) + markers := path.Join(staged, stageCreateMarkerNamespaceKey([]string{namespace})) + fc.seed(staged, &filer_pb.Entry{Name: stageCreateMarkerDirName, IsDirectory: true}) + fc.seed(markers, &filer_pb.Entry{Name: path.Base(markers), IsDirectory: true}) + return markers +} + +func TestAFreshLocationIsApartFromOtherTables(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := newMemFiler() + seedNamespace(fc, bucket, "finance", "alice") + pending := path.Join(s3tables.TablesPath, bucket, "finance", "pending") + fc.seed(pending, &filer_pb.Entry{Name: "pending", IsDirectory: true}) + fc.seed(path.Join(pending, "metadata"), &filer_pb.Entry{Name: "metadata", IsDirectory: true}) + fc.seed(path.Join(pending, "metadata", "v1.metadata.json"), &filer_pb.Entry{Name: "v1.metadata.json"}) + s := NewServer(fc, nil) + create := func(body string) int { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice")) + return w.Code + } + + if code := create(`{"name":"shared","location":"s3://warehouse/finance/shared","stage-create":true}`); code != http.StatusOK { + t.Fatalf("stage at a fresh location: %d", code) + } + if code := create(`{"name":"deep","location":"s3://warehouse/finance/deep/table","stage-create":true}`); code != http.StatusOK { + t.Fatalf("stage at a fresh nested location: %d", code) + } + tables := 0 + for name, c := range map[string]struct { + location string + want int + }{ + "under a stage": {"s3://warehouse/finance/shared/child", http.StatusConflict}, + "above a stage": {"s3://warehouse/finance/deep", http.StatusConflict}, + "under another table's files": {"s3://warehouse/finance/pending/child", http.StatusBadRequest}, + } { + for _, stage := range []string{"false", "true"} { + tables++ + if code := create(fmt.Sprintf(`{"name":"t%d","location":%q,"stage-create":%s}`, tables, c.location, stage)); code != c.want { + t.Errorf("%s (stage %s): status = %d, want %d", name, stage, code, c.want) + } + } + } + if code := create(`{"name":"sibling","location":"s3://warehouse/finance/shared2"}`); code != http.StatusOK { + t.Errorf("create beside a stage: %d, want 200", code) + } +} + +// claimRaceFiler runs onCreate once, right after the first write it matches. +type claimRaceFiler struct { + *memFiler + onCreate func(p string) bool +} + +func (f *claimRaceFiler) WithFilerClient(_ bool, fn func(client filer_pb.SeaweedFilerClient) error) error { + return fn(f) +} + +func (f *claimRaceFiler) CreateEntry(ctx context.Context, in *filer_pb.CreateEntryRequest, opts ...grpc.CallOption) (*filer_pb.CreateEntryResponse, error) { + resp, err := f.memFiler.CreateEntry(ctx, in, opts...) + if err == nil && f.onCreate != nil && f.onCreate(path.Join(in.Directory, in.Entry.Name)) { + f.onCreate = nil + } + return resp, err +} + +func TestARacingCreateBacksOutOfAnOverlappingLocation(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + markers := path.Join(s3tables.TablesPath, bucket, stageCreateMarkerDirName, stageCreateMarkerNamespaceKey([]string{"finance"})) + otherStage := func(fc *claimRaceFiler, location string) { + live, _ := json.Marshal(stageCreateMarker{ + TableUUID: uuid.NewString(), + Location: location, + ExpiresAt: time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano), + }) + seedStageDirs(fc.memFiler, bucket, "finance") + fc.seed(path.Join(markers, "other"), &filer_pb.Entry{Name: "other", IsDirectory: true}) + fc.seed(path.Join(markers, "other", "o.json"), &filer_pb.Entry{Name: "o.json", Content: live}) + } + cases := []struct { + name, body string + ownWrite string + want int + race func(fc *claimRaceFiler) + }{ + {"stage after a stage", `{"name":"a","location":"s3://warehouse/finance/shared","stage-create":true}`, path.Join(markers, "a"), http.StatusConflict, + func(fc *claimRaceFiler) { otherStage(fc, "s3://warehouse/finance/shared/child") }}, + {"create after a stage", `{"name":"a","location":"s3://warehouse/finance/shared"}`, path.Join(s3tables.TablesPath, bucket, "finance/shared/metadata"), http.StatusConflict, + func(fc *claimRaceFiler) { otherStage(fc, "s3://warehouse/finance/shared") }}, + {"stage after a native create", `{"name":"a","location":"s3://warehouse/finance/lance1/data","stage-create":true}`, path.Join(markers, "a"), http.StatusConflict, + func(fc *claimRaceFiler) { + fc.seed(path.Join(s3tables.TablesPath, bucket, "finance/lance1"), &filer_pb.Entry{Name: "lance1", IsDirectory: true, + Extended: map[string][]byte{s3tables.ExtendedKeyMetadata: []byte(`{"format":"LANCE"}`)}}) + }}, + {"stage after a create", `{"name":"a","location":"s3://warehouse/finance/shared/child","stage-create":true}`, path.Join(markers, "a"), http.StatusBadRequest, + func(fc *claimRaceFiler) { + dir := path.Join(s3tables.TablesPath, bucket, "finance/shared/metadata") + fc.seed(path.Dir(dir), &filer_pb.Entry{Name: "shared", IsDirectory: true}) + fc.seed(dir, &filer_pb.Entry{Name: "metadata", IsDirectory: true}) + fc.seed(path.Join(dir, "v1.metadata.json"), &filer_pb.Entry{Name: "v1.metadata.json"}) + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + fc := &claimRaceFiler{memFiler: newMemFiler()} + seedNamespace(fc.memFiler, bucket, "finance", "alice") + var written []string + fc.onCreate = func(p string) bool { + if path.Dir(p) != tc.ownWrite || !strings.HasSuffix(p, ".json") { + return false + } + written = append(written, p) + tc.race(fc) + return true + } + w := httptest.NewRecorder() + NewServer(fc, nil).handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", tc.body, "alice")) + if w.Code != tc.want { + t.Fatalf("status = %d %s, want %d", w.Code, w.Body.String(), tc.want) + } + if len(written) != 1 { + t.Fatalf("the race never ran") + } + for p := range fc.entries { + if strings.HasPrefix(p, tc.ownWrite+"/") { + t.Errorf("a create that backed out left %s", p) + } + } + }) + } +} + +// A create removes only the stages of its name that its own location covers; +// another stage keeps holding its location while its credentials are live. +func TestACreateKeepsTheStagesItDoesNotCover(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := newMemFiler() + seedNamespace(fc, bucket, "finance", "alice") + s := NewServer(fc, nil) + create := func(body string) int { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice")) + return w.Code + } + markers := func(table string) int { + n := 0 + for p := range fc.entries { + if path.Dir(p) == stageCreateMarkerDir(bucket, []string{"finance"}, table) && strings.HasSuffix(p, ".json") { + n++ + } + } + return n + } + + if code := create(`{"name":"t","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusOK { + t.Fatalf("stage: %d", code) + } + if code := create(`{"name":"t","location":"s3://warehouse/finance/y"}`); code != http.StatusOK { + t.Fatalf("create of the staged name elsewhere: %d", code) + } + if markers("t") != 1 { + t.Errorf("the create removed a stage it does not cover") + } + if code := create(`{"name":"u","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusConflict { + t.Errorf("stage at the location of a live stage whose name was taken: %d, want 409", code) + } + + stage := func() createdResult { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"v","stage-create":true}`, "alice")) + return decodeCreated(t, w) + } + first, second := stage(), stage() + body := `{"requirements":[{"type":"assert-create"}],"updates":[{"action":"assign-uuid","uuid":"` + first.Metadata.TableUUID + `"}]}` + r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/v", strings.NewReader(body)) + r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": "v"}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w := httptest.NewRecorder() + s.handleUpdateTable(w, r) + decodeCreated(t, w) + if markers("v") != 1 { + t.Fatalf("a commit left %d stages of its name, want only the other one", markers("v")) + } + if code := create(`{"name":"w","location":"` + second.Metadata.Location + `","stage-create":true}`); code != http.StatusConflict { + t.Errorf("stage at the location of the stage a commit did not take: %d, want 409", code) + } +} + +func TestAnAssignedStageBacksOutOfARacingStage(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := &claimRaceFiler{memFiler: newMemFiler()} + seedNamespace(fc.memFiler, bucket, "finance", "alice") + s := NewServer(fc, nil) + create := func(body string) int { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice")) + return w.Code + } + if code := create(`{"name":"a","stage-create":true}`); code != http.StatusOK { + t.Fatalf("stage at an assigned location: %d", code) + } + if code := create(`{"name":"b","stage-create":true}`); code != http.StatusOK { + t.Fatalf("second stage at an assigned location: %d", code) + } + + t.Setenv("ICEBERG_WAREHOUSE", "s3://warehouse/finance/base") + markers := seedStageDirs(fc.memFiler, bucket, "finance") + raced := false + fc.onCreate = func(p string) bool { + if path.Dir(p) != path.Join(markers, "orders") { + return false + } + live, _ := json.Marshal(stageCreateMarker{ + TableUUID: uuid.NewString(), + Location: "s3://warehouse/finance/base", + ExpiresAt: time.Now().UTC().Add(time.Hour).Format(time.RFC3339Nano), + }) + fc.seed(path.Join(markers, "outer"), &filer_pb.Entry{Name: "outer", IsDirectory: true}) + fc.seed(path.Join(markers, "outer", "o.json"), &filer_pb.Entry{Name: "o.json", Content: live}) + raced = true + return true + } + if code := create(`{"name":"orders","stage-create":true}`); code != http.StatusConflict { + t.Errorf("stage assigned under a racing stage: %d, want 409", code) + } + if !raced { + t.Fatal("the race never ran") + } + for p := range fc.entries { + if strings.HasPrefix(p, path.Join(markers, "orders")+"/") { + t.Errorf("a stage that backed out left %s", p) + } + } +} + +func TestAStageHoldsItsLocationWhileItsCredentialsLast(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := newMemFiler() + seedNamespace(fc, bucket, "finance", "alice") + s := NewServer(fc, nil) + s.s3Endpoint = "http://s3.example:8333" + expiry := time.Now().Add(stageCreateMarkerTTL + 96*time.Hour).Truncate(time.Millisecond) + s.SetCredentialVendor(&stubVendor{credentials: &VendedCredentials{AccessKeyID: "ASIA", SecretAccessKey: "s", SessionToken: "t", Expiration: expiry}}) + + r := newCreateTableRequest(t, bucket, "finance", `{"name":"t","location":"s3://warehouse/finance/x","stage-create":true}`, "alice") + r.Header.Set(accessDelegationHeader, "vended-credentials") + w := httptest.NewRecorder() + s.handleCreateTable(w, r) + decodeCreated(t, w) + + found := false + for p, e := range fc.entries { + if path.Dir(p) != stageCreateMarkerDir(bucket, []string{"finance"}, "t") || !strings.HasSuffix(p, ".json") { + continue + } + var marker stageCreateMarker + if err := json.Unmarshal(e.Content, &marker); err != nil { + t.Fatal(err) + } + expiresAt, err := time.Parse(time.RFC3339Nano, marker.ExpiresAt) + if err != nil { + t.Fatal(err) + } + if expiresAt.Before(expiry) { + t.Errorf("stage marker expires at %v, before its credentials at %v", expiresAt, expiry) + } + found = true + } + if !found { + t.Fatal("no stage marker") + } +} + +func TestACreateDuringAStageLeavesItsClaim(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := &claimRaceFiler{memFiler: newMemFiler()} + seedNamespace(fc.memFiler, bucket, "finance", "alice") + s := NewServer(fc, nil) + create := func(body string) int { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice")) + return w.Code + } + raced := false + fc.onCreate = func(p string) bool { + if raced || path.Dir(p) != stageCreateMarkerDir(bucket, []string{"finance"}, "t") || !strings.HasSuffix(p, ".json") { + return false + } + raced = true + if code := create(`{"name":"t","location":"s3://warehouse/finance/y"}`); code != http.StatusOK { + t.Errorf("create of the staged name elsewhere: %d", code) + } + return true + } + if code := create(`{"name":"t","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusOK { + t.Fatalf("stage: %d", code) + } + if !raced { + t.Fatal("the race never ran") + } + if code := create(`{"name":"u","location":"s3://warehouse/finance/x","stage-create":true}`); code != http.StatusConflict { + t.Errorf("stage at the location of a live stage: %d, want 409", code) + } +} + +func TestAStageBacksOutOfASameNameCreateOverItsLocation(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := &claimRaceFiler{memFiler: newMemFiler()} + seedNamespace(fc.memFiler, bucket, "finance", "alice") + s := NewServer(fc, nil) + raced := false + fc.onCreate = func(p string) bool { + if raced || !strings.Contains(p, "/"+stageCreateMarkerDirName+"/") || !strings.HasSuffix(p, "/metadata/v1.metadata.json") { + return false + } + raced = true + err := s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(fc), "CreateTable", &s3tables.CreateTableRequest{ + TableBucketARN: buildTableBucketARN(bucket), + Namespace: []string{"finance"}, + Name: "t", + Format: s3tables.FormatLance, + }, &s3tables.CreateTableResponse{}, "alice") + if err != nil { + t.Errorf("lance create of the staged name: %v", err) + } + return true + } + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"t","location":"s3://warehouse/finance/t/data","stage-create":true}`, "alice")) + if !raced { + t.Fatal("the race never ran") + } + if w.Code != http.StatusConflict { + t.Errorf("stage under a same-name table: %d, want 409 (body: %s)", w.Code, w.Body.String()) + } + markerDir := stageCreateMarkerDir(bucket, []string{"finance"}, "t") + for p := range fc.entries { + if path.Dir(p) == markerDir && strings.HasSuffix(p, ".json") { + t.Errorf("stage marker %s left behind", p) + } + } +} + +// commitStage commits the stage of table that handed out uuid. +func commitStage(t *testing.T, s *Server, bucket, table, uuid string) *httptest.ResponseRecorder { + t.Helper() + body := `{"requirements":[{"type":"assert-create"}],"updates":[{"action":"assign-uuid","uuid":"` + uuid + `"}]}` + r := httptest.NewRequest(http.MethodPost, "/v1/"+bucket+"/namespaces/finance/tables/"+table, strings.NewReader(body)) + r = mux.SetURLVars(r, map[string]string{"prefix": bucket, "namespace": "finance", "table": table}) + r = r.WithContext(s3_constants.SetIdentityNameInContext(r.Context(), "alice")) + w := httptest.NewRecorder() + s.handleUpdateTable(w, r) + return w +} + +// Another live stage of the same name holds its own location, not the record +// path this commit writes. +func TestAStageAtItsNamePathCommitsBesideASameNameStage(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := newMemFiler() + seedNamespace(fc, bucket, "finance", "alice") + s := NewServer(fc, nil) + stage := func(body string) createdResult { + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", body, "alice")) + return decodeCreated(t, w) + } + first := stage(`{"name":"t","location":"s3://warehouse/finance/t","stage-create":true}`) + second := stage(`{"name":"t","stage-create":true}`) + if second.Metadata.Location == first.Metadata.Location { + t.Fatalf("both stages at %s", first.Metadata.Location) + } + committed := decodeCreated(t, commitStage(t, s, bucket, "t", first.Metadata.TableUUID)) + if committed.Metadata.Location != first.Metadata.Location { + t.Errorf("commit at %s, want %s", committed.Metadata.Location, first.Metadata.Location) + } +} + +// A stage whose location has a metadata segment of its own commits there. +func TestAStageUnderAMetadataDirectoryCommits(t *testing.T) { + t.Setenv("ICEBERG_ENABLE_STAGE_CREATE", "true") + const bucket = "warehouse" + fc := newMemFiler() + seedNamespace(fc, bucket, "finance", "alice") + s := NewServer(fc, nil) + w := httptest.NewRecorder() + s.handleCreateTable(w, newCreateTableRequest(t, bucket, "finance", `{"name":"t","location":"s3://warehouse/finance/metadata/t","stage-create":true}`, "alice")) + staged := decodeCreated(t, w) + committed := decodeCreated(t, commitStage(t, s, bucket, "t", staged.Metadata.TableUUID)) + if committed.Metadata.Location != staged.Metadata.Location { + t.Errorf("commit at %s, want %s", committed.Metadata.Location, staged.Metadata.Location) + } +} diff --git a/weed/s3api/iceberg/iceberg_transaction_test.go b/weed/s3api/iceberg/iceberg_transaction_test.go index 4d43748ced..0a7314799a 100644 --- a/weed/s3api/iceberg/iceberg_transaction_test.go +++ b/weed/s3api/iceberg/iceberg_transaction_test.go @@ -275,7 +275,7 @@ func TestCommitTransactionReadsMetadataFileOfOlderRegistration(t *testing.T) { location, registered := seedRegistrableMetadata(t, fc, "events") err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(context.Background()), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ TableBucketARN: buildTableBucketARN(registerTestBucket), Namespace: []string{"finance"}, Name: "events", @@ -354,7 +354,7 @@ func TestCommitTransactionRefreshesNameMapping(t *testing.T) { location := seedMetadataFile(fc, "events", "00001-7c1e2f4a.metadata.json", raw) err = fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(context.Background()), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ TableBucketARN: buildTableBucketARN(registerTestBucket), Namespace: []string{"finance"}, Name: "events", @@ -415,7 +415,7 @@ func TestCommitTransactionRollbackRestoresOlderRegistration(t *testing.T) { location, registered := seedRegistrableMetadata(t, fc.memFiler, "events") err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(context.Background()), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ TableBucketARN: buildTableBucketARN(registerTestBucket), Namespace: []string{"finance"}, Name: "events", @@ -467,7 +467,7 @@ func TestCommitTransactionOnOversizedRegistration(t *testing.T) { location, registered := seedOversizedMetadata(t, fc, "events") err := fc.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - return s.tablesManager.Execute(context.Background(), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ + return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(context.Background()), s3tables.NewManagerClient(client), "RegisterTable", &s3tables.RegisterTableRequest{ TableBucketARN: buildTableBucketARN(registerTestBucket), Namespace: []string{"finance"}, Name: "events", diff --git a/weed/s3api/iceberg/stage_create.go b/weed/s3api/iceberg/stage_create.go index 7af71bc038..69f9758674 100644 --- a/weed/s3api/iceberg/stage_create.go +++ b/weed/s3api/iceberg/stage_create.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "net/http" "net/url" "os" "path" @@ -18,9 +19,10 @@ import ( ) const ( - stageCreateMarkerDirName = ".iceberg_staged" + stageCreateMarkerDirName = s3tables.StagedTablesDirName // Keep staged markers long enough to avoid deleting in-progress create transactions. stageCreateMarkerTTL = 72 * time.Hour + stageListPageSize = 1024 ) type stageCreateMarker struct { @@ -83,8 +85,10 @@ func (s *Server) pruneExpiredStageCreateMarkers(ctx context.Context, bucketName continue } - if err := filer_pb.DoRemove(opCtx, client, markerDir, resp.Entry.Name, true, false, true, false, nil); err != nil && !errors.Is(err, filer_pb.ErrNotFound) { - return err + for _, name := range []string{resp.Entry.Name, strings.TrimSuffix(resp.Entry.Name, ".json")} { + if err := filer_pb.DoRemove(opCtx, client, markerDir, name, true, true, true, false, nil); err != nil && !errors.Is(err, filer_pb.ErrNotFound) { + return err + } } } }) @@ -156,16 +160,21 @@ func (s *Server) loadLatestStageCreateMarker(ctx context.Context, bucketName str return latestMarker, nil } -func (s *Server) writeStageCreateMarker(ctx context.Context, bucketName string, namespace []string, tableName string, tableUUID uuid.UUID, location string, stagedMetadataLocation string) error { +func (s *Server) writeStageCreateMarker(ctx context.Context, bucketName string, namespace []string, tableName string, tableUUID uuid.UUID, location string, stagedMetadataLocation string, holdUntil time.Time) error { opCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() + now := time.Now().UTC() + expiresAt := now.Add(stageCreateMarkerTTL) + if holdUntil.After(expiresAt) { + expiresAt = holdUntil.UTC() + } marker := stageCreateMarker{ TableUUID: tableUUID.String(), Location: location, StagedMetadataLocation: stagedMetadataLocation, - CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), - ExpiresAt: time.Now().UTC().Add(stageCreateMarkerTTL).Format(time.RFC3339Nano), + CreatedAt: now.Format(time.RFC3339Nano), + ExpiresAt: expiresAt.Format(time.RFC3339Nano), } content, err := json.Marshal(marker) if err != nil { @@ -253,22 +262,88 @@ func (s *Server) writeStageCreateMarker(ctx context.Context, bucketName string, }) } -func (s *Server) deleteStageCreateMarkers(ctx context.Context, bucketName string, namespace []string, tableName string) error { +// deleteStageCreate removes one stage: its marker and its staged metadata. +func (s *Server) deleteStageCreate(ctx context.Context, bucketName string, namespace []string, tableName string, tableUUID uuid.UUID) error { opCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - parentDir := path.Dir(stageCreateMarkerDir(bucketName, namespace, tableName)) - targetName := path.Base(stageCreateMarkerDir(bucketName, namespace, tableName)) - + markerDir := stageCreateMarkerDir(bucketName, namespace, tableName) return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { - err := filer_pb.DoRemove(opCtx, client, parentDir, targetName, true, true, true, false, nil) - if errors.Is(err, filer_pb.ErrNotFound) { - return nil + for _, name := range []string{tableUUID.String() + ".json", tableUUID.String()} { + if err := filer_pb.DoRemove(opCtx, client, markerDir, name, true, true, true, false, nil); err != nil && !errors.Is(err, filer_pb.ErrNotFound) { + return err + } } - return err + return nil }) } +// deleteStageCreateMarkers removes the stages of the table that its record at +// location now covers. Any other stage keeps its location until it expires: +// its credentials are still live. +func (s *Server) deleteStageCreateMarkers(ctx context.Context, bucketName string, namespace []string, tableName, location string) error { + _, locationPath, err := parseS3Location(location) + if err != nil { + return err + } + locationPath = path.Clean(locationPath) + opCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + var covered []uuid.UUID + if err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + startFrom := "" + for { + stream, err := client.ListEntries(opCtx, &filer_pb.ListEntriesRequest{Directory: stageCreateMarkerDir(bucketName, namespace, tableName), Limit: stageListPageSize, StartFromFileName: startFrom}) + if err != nil { + if errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(strings.ToLower(err.Error()), "not found") { + return nil + } + return err + } + received := 0 + for { + resp, recvErr := stream.Recv() + if recvErr == io.EOF { + break + } + if recvErr != nil { + return recvErr + } + if resp.Entry == nil { + continue + } + received++ + startFrom = resp.Entry.Name + var marker stageCreateMarker + if resp.Entry.IsDirectory || json.Unmarshal(resp.Entry.Content, &marker) != nil { + continue + } + id, err := uuid.Parse(strings.TrimSuffix(resp.Entry.Name, ".json")) + if err != nil { + continue + } + if _, markerPath, err := parseS3Location(marker.Location); err == nil { + if markerPath = path.Clean(markerPath); markerPath == locationPath || strings.HasPrefix(markerPath, locationPath+"/") { + covered = append(covered, id) + } + } + } + if received < stageListPageSize { + return nil + } + } + }); err != nil { + return err + } + for _, id := range covered { + if err := s.deleteStageCreate(ctx, bucketName, namespace, tableName, id); err != nil { + return err + } + } + return nil +} + func isStageCreateEnabled() bool { value := strings.TrimSpace(strings.ToLower(os.Getenv("ICEBERG_ENABLE_STAGE_CREATE"))) if value == "" { @@ -295,3 +370,91 @@ func assignedTableUUID(updates []json.RawMessage) string { } return "" } + +// checkFreshLocation accepts a client-named table location only when no record +// and no live stage but ownStage holds a location at, above or under it and, +// with files set, nothing is stored under it and no table keeps its metadata +// above it. A create checks again once its own stage marker or metadata file +// is written: of two creates racing for overlapping locations, at least one +// sees the other. +func (s *Server) checkFreshLocation(ctx context.Context, bucketName string, namespace []string, tableName, locationPath, location, ownStage string, files bool) *icebergRequestError { + opCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + + stored, held := false, false + root := path.Join(s3tables.TablesPath, bucketName, locationPath) + err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + list := func(dir string, fn func(*filer_pb.Entry) bool) error { + startFrom := "" + for { + stream, err := client.ListEntries(opCtx, &filer_pb.ListEntriesRequest{Directory: dir, Limit: stageListPageSize, StartFromFileName: startFrom}) + if err != nil { + if errors.Is(err, filer_pb.ErrNotFound) || strings.Contains(strings.ToLower(err.Error()), "not found") { + return nil + } + return err + } + received := 0 + for { + resp, recvErr := stream.Recv() + if recvErr == io.EOF { + break + } + if recvErr != nil { + return recvErr + } + if resp.Entry == nil { + continue + } + received++ + startFrom = resp.Entry.Name + if !fn(resp.Entry) { + return nil + } + } + if received < stageListPageSize { + return nil + } + } + } + if files { + if err := list(root, func(*filer_pb.Entry) bool { + stored = true + return false + }); err != nil || stored { + return err + } + for dir := path.Dir(locationPath); strings.HasPrefix(dir, flattenNamespacePath(namespace)+"/"); dir = path.Dir(dir) { + if _, err := filer_pb.LookupEntry(opCtx, client, &filer_pb.LookupDirectoryEntryRequest{ + Directory: path.Join(s3tables.TablesPath, bucketName, dir), + Name: "metadata", + }); err == nil { + stored = true + return nil + } else if !errors.Is(err, filer_pb.ErrNotFound) { + return err + } + } + } + roots, err := s3tables.CatalogRecordRoots(opCtx, client, bucketName) + if err != nil { + return err + } + self := "" + if ownStage != "" { + self = path.Join(stageCreateMarkerDir(bucketName, namespace, tableName), ownStage+".json") + } + held = s3tables.RootClaimed(roots, self, root) + return nil + }) + if err != nil { + return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to check table location: " + err.Error()} + } + if held { + return &icebergRequestError{http.StatusConflict, "CommitFailedException", s3tables.ErrLocationInUse.Error()} + } + if stored { + return &icebergRequestError{http.StatusBadRequest, "BadRequestException", fmt.Sprintf("table location %s is not empty", location)} + } + return nil +} diff --git a/weed/s3api/iceberg/vector_namespace_test.go b/weed/s3api/iceberg/vector_namespace_test.go index 3a22f77b39..0d80a14ee8 100644 --- a/weed/s3api/iceberg/vector_namespace_test.go +++ b/weed/s3api/iceberg/vector_namespace_test.go @@ -155,7 +155,7 @@ func TestCatalogOnlyTableRefusesIcebergCommits(t *testing.T) { {"CreateTable", &s3tables.CreateTableRequest{TableBucketARN: arn, Namespace: []string{"ds"}, Name: "t", Format: s3tables.FormatLance, MetadataLocation: datasetRoot}}, } { - if err := admin.Execute(t.Context(), client, op.name, op.req, nil, ""); err != nil { + if err := admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), client, op.name, op.req, nil, ""); err != nil { t.Fatalf("%s: %v", op.name, err) } } diff --git a/weed/s3api/lance/handlers_table.go b/weed/s3api/lance/handlers_table.go index 9d4397105b..e84c4b51b1 100644 --- a/weed/s3api/lance/handlers_table.go +++ b/weed/s3api/lance/handlers_table.go @@ -128,11 +128,9 @@ func (s *Server) handleDeclareTable(w http.ResponseWriter, r *http.Request) { return } - location := strings.TrimSuffix(req.Location, "/") - if location == "" { - location = tableLocation(bucket, ns, name) - } else if err := confineLocation(bucket, location); err != nil { - writeError(w, r, http.StatusBadRequest, codeInvalidInput, err.Error()) + location := tableLocation(bucket, ns, name) + if requested := strings.TrimSuffix(strings.TrimSpace(req.Location), "/"); requested != "" && requested != location { + writeError(w, r, http.StatusBadRequest, codeInvalidInput, s3tables.ErrClientTableLocation.Error()) return } @@ -680,6 +678,7 @@ func (s *Server) createTable(r *http.Request, bucket string, ns []string, name, // is the dataset root itself. MetadataLocation: location, } + r = r.WithContext(s3tables.WithCatalogAssignedLocation(r.Context())) var resp s3tables.CreateTableResponse if err := s.execute(r, "CreateTable", req, &resp); err != nil { return "", err diff --git a/weed/s3api/lance/handlers_test.go b/weed/s3api/lance/handlers_test.go index b0eafbf524..55bcbd3ec3 100644 --- a/weed/s3api/lance/handlers_test.go +++ b/weed/s3api/lance/handlers_test.go @@ -348,7 +348,7 @@ func TestIcebergTablesAreInvisible(t *testing.T) { manager := h.admin var created s3tables.CreateTableResponse - err := manager.Execute(t.Context(), s3tables.NewManagerClient(h.filer.Client), "CreateTable", &s3tables.CreateTableRequest{ + err := manager.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), s3tables.NewManagerClient(h.filer.Client), "CreateTable", &s3tables.CreateTableRequest{ TableBucketARN: h.bucketARN(t, "analytics"), Namespace: []string{"sales"}, Name: "ledger", @@ -531,17 +531,18 @@ func TestDeregisterAndReregisterNeedUpdateTable(t *testing.T) { t.Fatal("a refused register brought the table back") } - // Without GetTable the table looks absent, but CreateTable still returns it. + // Without GetTable the table looks absent; CreateTable of a name that exists + // answers 409 to a caller who may not read it (it returns nothing about the + // table), so the register stops there and the table stays deregistered. blindServer := NewServer(s3tables.NewManagerClient(h.filer.Client), createOnlyAuthenticator{noRead: true}) blindServer.SetCredentialVendor(recordingVendor{}) blindRouter := mux.NewRouter().SkipClean(true) blindServer.RegisterRoutes(blindRouter) blind := &testHarness{router: blindRouter, filer: h.filer, admin: h.admin, server: blindServer} - blind.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/register", `{"location":"s3://lnc/ns/theirs"}`, http.StatusNotFound) - if got := blind.vendedKey(t, "/v1/table/lnc$ns$theirs/declare", ""); got == "read-write" { - t.Error("a declare that found an unreadable table vended write credentials") - } + blind.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/register", `{"location":"s3://lnc/ns/theirs"}`, http.StatusConflict) + // a declare that finds an unreadable table vends nothing: 409, no credentials + blind.mustDo(t, http.MethodPost, "/v1/table/lnc$ns$theirs/declare", `{}`, http.StatusConflict) if h.filer.Get("/buckets/lnc/ns/theirs", deregisteredMarker) == nil { t.Fatal("a caller without GetTable brought the table back") } @@ -608,6 +609,19 @@ func TestDescribeTableInternalVendsWriteForTheVectorNamespace(t *testing.T) { } } +// A declare may restate the dataset's own name path; any other location is refused. +func TestDeclareTakesOnlyItsNamePath(t *testing.T) { + h := newTestHarness(t) + h.createBucket(t, "analytics", s3tables.FormatLance) + h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK) + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$other/declare", `{"location":"s3://analytics/sales/elsewhere"}`, http.StatusBadRequest) + declared := decode[DeclareTableResponse](t, + h.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/declare", `{"location":"s3://analytics/sales/orders/"}`, http.StatusOK)) + if declared.Location != "s3://analytics/sales/orders" { + t.Fatalf("declared location = %q", declared.Location) + } +} + // actionsAuthenticator authenticates every request as name, holding actions. type actionsAuthenticator struct { name string @@ -686,7 +700,7 @@ func TestRegisterOfAnExistingName(t *testing.T) { h := newTestHarness(t) h.createBucket(t, "analytics", "") h.mustDo(t, http.MethodPost, "/v1/namespace/analytics$sales/create", `{}`, http.StatusOK) - if err := h.admin.Execute(t.Context(), s3tables.NewManagerClient(h.filer.Client), "CreateTable", &s3tables.CreateTableRequest{ + if err := h.admin.Execute(s3tables.WithCatalogAssignedLocation(t.Context()), s3tables.NewManagerClient(h.filer.Client), "CreateTable", &s3tables.CreateTableRequest{ TableBucketARN: h.bucketARN(t, "analytics"), Namespace: []string{"sales"}, Name: "ledger", @@ -709,10 +723,11 @@ func TestRegisterOfAnExistingName(t *testing.T) { router := mux.NewRouter().SkipClean(true) server.RegisterRoutes(router) creator := &testHarness{router: router, filer: h.filer, admin: h.admin, server: server} - got := decode[RegisterTableResponse](t, - creator.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register", `{"location":"s3://analytics/sales/ledger"}`, http.StatusOK)) - if got.Location != declared.Location { - t.Fatalf("register answered %q, want the record's own %q", got.Location, declared.Location) + for _, location := range []string{"s3://analytics/sales/ledger", "s3://analytics/sales/nothing", declared.Location} { + recorder := creator.mustDo(t, http.MethodPost, "/v1/table/analytics$sales$orders/register", `{"location":"`+location+`"}`, http.StatusConflict) + if got := decode[errorResponse](t, recorder); got.Code != codeTableAlreadyExists { + t.Fatalf("%s: error code = %d, want %d", location, got.Code, codeTableAlreadyExists) + } } }) } diff --git a/weed/s3api/lance/vector_namespace_test.go b/weed/s3api/lance/vector_namespace_test.go index f62e52c137..239bab4838 100644 --- a/weed/s3api/lance/vector_namespace_test.go +++ b/weed/s3api/lance/vector_namespace_test.go @@ -145,15 +145,18 @@ func TestVectorNamespaceVendsWriteCredentialsOnlyToTrustedCallers(t *testing.T) } // Declaring a name that already exists answers for that table, so naming the -// index's location on another table gets no credentials to the index. +// index's location on another table gets no credentials to the index. (A +// declare naming any location is refused with 400, before anything else; +// a declare without one answers for the existing table.) func TestDeclareOfAnExistingTableKeepsItsLocation(t *testing.T) { h := newTestHarness(t) h.server.SetCredentialVendor(recordingVendor{}) h.seedVectorIndex(t, "vec", s3tables.FormatLance) h.mustDo(t, http.MethodPost, "/v1/table/vec$other$tbl/declare", `{}`, http.StatusOK) - rec := h.mustDo(t, http.MethodPost, "/v1/table/vec$other$tbl/declare", - `{"location":"s3://vec/vector/idx","vend_credentials":true}`, http.StatusOK) + h.mustDo(t, http.MethodPost, "/v1/table/vec$other$tbl/declare", + `{"location":"s3://vec/vector/idx","vend_credentials":true}`, http.StatusBadRequest) + rec := h.mustDo(t, http.MethodPost, "/v1/table/vec$other$tbl/declare", `{"vend_credentials":true}`, http.StatusOK) resp := decode[DeclareTableResponse](t, rec) if resp.Location != "s3://vec/other/tbl" { t.Errorf("location = %q, want the table's own s3://vec/other/tbl", resp.Location) diff --git a/weed/s3api/s3tables/filer_ops.go b/weed/s3api/s3tables/filer_ops.go index 73fe371719..1713baba88 100644 --- a/weed/s3api/s3tables/filer_ops.go +++ b/weed/s3api/s3tables/filer_ops.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "path" "strings" @@ -23,11 +24,12 @@ import ( ) var ( - ErrAttributeNotFound = errors.New("attribute not found") - ErrConcurrentUpdate = errors.New("attribute changed concurrently") - ErrNameTaken = errors.New("catalog name is taken") - ErrLocationInUse = errors.New("location is in use by another table or view") - ErrLocationMove = errors.New("a table's or view's location cannot be changed; commits write under the location it has") + ErrAttributeNotFound = errors.New("attribute not found") + ErrConcurrentUpdate = errors.New("attribute changed concurrently") + ErrNameTaken = errors.New("catalog name is taken") + ErrLocationInUse = errors.New("location is in use by another table or view") + ErrClientTableLocation = errors.New("a new table's or view's location is assigned by the catalog; to use existing files, register their metadata") + ErrLocationMove = errors.New("a table's or view's location cannot be changed; commits write under the location it has") // ErrPublishedRecordChanged is the ErrConcurrentUpdate a create returns // when the record it wrote was already visible, and another caller changed // it — updated it, or renamed it away — before the create could back it @@ -1075,7 +1077,8 @@ func (m *tableMetadataInternal) root(bucketName, recordPath string) string { // CatalogRecordRoots maps every table and view record of the bucket, in any // namespace, to the directories it keeps its files under: the one its metadata // gives it and, while an update moves it, the one it moves to. A renamed record -// keeps the directory of its old name. +// keeps the directory of its old name. A live stage-create counts under its +// marker, holding its location and the path of the record it would commit to. func CatalogRecordRoots(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName string) (map[string][]string, error) { var namespaces []string if err := eachDirEntry(ctx, client, GetTableBucketPath(bucketName), func(entry *filer_pb.Entry) bool { @@ -1111,9 +1114,74 @@ func CatalogRecordRoots(ctx context.Context, client filer_pb.SeaweedFilerClient, return nil, err } } + if err := addStagedRoots(ctx, client, bucketName, roots); err != nil { + return nil, err + } return roots, nil } +// addStagedRoots adds every live Iceberg stage-create to roots, under its +// marker: its location and the record its commit would write. +func addStagedRoots(ctx context.Context, client filer_pb.SeaweedFilerClient, bucketName string, roots map[string][]string) error { + stagedDir := path.Join(GetTableBucketPath(bucketName), StagedTablesDirName) + var namespaceKeys []string + if err := eachDirEntry(ctx, client, stagedDir, func(entry *filer_pb.Entry) bool { + if entry.IsDirectory { + namespaceKeys = append(namespaceKeys, entry.Name) + } + return true + }); err != nil { + return err + } + bucketPath := GetTableBucketPath(bucketName) + "/" + now := time.Now().UTC() + for _, key := range namespaceKeys { + decoded, err := url.PathUnescape(key) + if err != nil { + continue + } + var parts []string + for _, part := range strings.Split(decoded, "\x1F") { + if part != "" { + parts = append(parts, part) + } + } + namespace := strings.Join(parts, ".") + var tableNames []string + if err := eachDirEntry(ctx, client, path.Join(stagedDir, key), func(entry *filer_pb.Entry) bool { + if entry.IsDirectory { + tableNames = append(tableNames, entry.Name) + } + return true + }); err != nil { + return err + } + for _, tableName := range tableNames { + recordPath := GetTablePath(bucketName, namespace, tableName) + markerDir := path.Join(stagedDir, key, tableName) + if err := eachDirEntry(ctx, client, markerDir, func(entry *filer_pb.Entry) bool { + var marker struct { + Location string `json:"location"` + ExpiresAt string `json:"expires_at"` + } + if entry.IsDirectory || json.Unmarshal(entry.Content, &marker) != nil { + return true + } + if expiresAt, err := time.Parse(time.RFC3339Nano, marker.ExpiresAt); err != nil || !expiresAt.After(now) { + return true + } + if root := warehouseDir(marker.Location); strings.HasPrefix(root, bucketPath) { + roots[path.Join(markerDir, entry.Name)] = []string{root, recordPath} + } + return true + }); err != nil { + return err + } + } + } + return nil +} + // PathsOverlap reports whether a and b are the same path or one holds the other. func PathsOverlap(a, b string) bool { return a == b || strings.HasPrefix(a, b+"/") || strings.HasPrefix(b, a+"/") @@ -1163,6 +1231,20 @@ func checkLocationUnclaimed(ctx context.Context, client filer_pb.SeaweedFilerCli if err != nil { return err } + stagedDir := path.Join(GetTableBucketPath(bucketName), StagedTablesDirName) + "/" + _, staged := ctx.Value(tableStagedAtKey{}).(time.Time) + for key, held := range roots { + if !strings.HasPrefix(key, stagedDir) || len(held) != 2 || held[1] != recordPath { + continue + } + if staged && held[0] == root { + // A staged create's commit takes the location its own stage holds. + delete(roots, key) + } else { + // Another stage of this record holds only its location against it. + roots[key] = held[:1] + } + } if RootClaimed(roots, recordPath, root) { return ErrLocationInUse } @@ -1462,3 +1544,16 @@ func (h *S3TablesHandler) entryExists(ctx context.Context, client filer_pb.Seawe }) return err == nil } + +type catalogAssignedLocationKey struct{} + +// WithCatalogAssignedLocation marks an in-process catalog call whose location +// the catalog assigned or checked; client CreateTable/CreateView may not name one. +func WithCatalogAssignedLocation(ctx context.Context) context.Context { + return context.WithValue(ctx, catalogAssignedLocationKey{}, true) +} + +func catalogAssignedLocation(ctx context.Context) bool { + v, _ := ctx.Value(catalogAssignedLocationKey{}).(bool) + return v +} diff --git a/weed/s3api/s3tables/filer_ops_race_test.go b/weed/s3api/s3tables/filer_ops_race_test.go index e1c75eba8d..c0ab645eb6 100644 --- a/weed/s3api/s3tables/filer_ops_race_test.go +++ b/weed/s3api/s3tables/filer_ops_race_test.go @@ -42,7 +42,7 @@ func runHandler(t *testing.T, m *Manager, client filer_pb.SeaweedFilerClient, op t.Helper() body, err := json.Marshal(input) require.NoError(t, err) - req, err := newManagerRequest(context.Background(), operation, body, "admin") + req, err := newManagerRequest(assignedCtx(), operation, body, "admin") require.NoError(t, err) recorder := httptest.NewRecorder() m.handler.HandleRequest(recorder, req, NewManagerClient(client)) diff --git a/weed/s3api/s3tables/filer_ops_test.go b/weed/s3api/s3tables/filer_ops_test.go index e29b81e196..8f89b8e8c9 100644 --- a/weed/s3api/s3tables/filer_ops_test.go +++ b/weed/s3api/s3tables/filer_ops_test.go @@ -120,7 +120,7 @@ func TestDeleteTableBucketReportsRejectedDirectoryDelete(t *testing.T) { m := NewManager() m.SetTrusted(true) - err = m.Execute(context.Background(), NewManagerClient(fs.Client), "DeleteTableBucket", + err = m.Execute(assignedCtx(), NewManagerClient(fs.Client), "DeleteTableBucket", &DeleteTableBucketRequest{TableBucketARN: mustBucketARN(t)}, nil, "") require.Error(t, err, "a bucket the filer refused to delete must not be reported as deleted") diff --git a/weed/s3api/s3tables/handler.go b/weed/s3api/s3tables/handler.go index 8f4ca689fc..9e5ef6d860 100644 --- a/weed/s3api/s3tables/handler.go +++ b/weed/s3api/s3tables/handler.go @@ -20,6 +20,8 @@ const ( TablesPath = s3_constants.DefaultBucketsPath DefaultAccountID = "000000000000" DefaultRegion = "us-east-1" + // StagedTablesDirName holds the Iceberg stage-create markers of a bucket. + StagedTablesDirName = ".iceberg_staged" // Extended entry attributes for metadata storage ExtendedKeyTableBucket = s3_constants.ExtS3TablesPrefix + "tableBucket" diff --git a/weed/s3api/s3tables/handler_bind_authorized_test.go b/weed/s3api/s3tables/handler_bind_authorized_test.go index 0544ec5406..535c3a6fe0 100644 --- a/weed/s3api/s3tables/handler_bind_authorized_test.go +++ b/weed/s3api/s3tables/handler_bind_authorized_test.go @@ -199,7 +199,7 @@ func TestUpdateViewRejectsLostUpdate(t *testing.T) { assert.Equal(t, http.StatusConflict, code, "%+v", resp) assert.Equal(t, ErrCodeConflict, resp.Type, "%+v", resp) got := &GetViewResponse{} - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "GetView", getViewRequest(t, "v"), got, "")) + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "GetView", getViewRequest(t, "v"), got, "")) assert.Equal(t, updateViewRequest(t, token, "v2-winner").MetadataLocation, got.MetadataLocation, "the first update must survive") } diff --git a/weed/s3api/s3tables/handler_bind_tags_test.go b/weed/s3api/s3tables/handler_bind_tags_test.go index cce363229e..bb20c159c3 100644 --- a/weed/s3api/s3tables/handler_bind_tags_test.go +++ b/weed/s3api/s3tables/handler_bind_tags_test.go @@ -20,7 +20,7 @@ func TestTagOperationsKeepToTheBoundBucket(t *testing.T) { tableARN, err := BuildTableARN(DefaultRegion, DefaultAccountID, renameTestBucket, "ns", "t") require.NoError(t, err) var bucket GetTableBucketResponse - require.NoError(t, m.Execute(context.Background(), client, "GetTableBucket", + require.NoError(t, m.Execute(assignedCtx(), client, "GetTableBucket", &GetTableBucketRequest{TableBucketARN: mustBucketARN(t)}, &bucket, "")) bound := WithTableBucketCreatedAt(context.Background(), bucket.CreatedAt) stale := WithTableBucketCreatedAt(context.Background(), bucket.CreatedAt.Add(-time.Hour)) diff --git a/weed/s3api/s3tables/handler_bucket_format_test.go b/weed/s3api/s3tables/handler_bucket_format_test.go index 7787b8c913..ae05b575c6 100644 --- a/weed/s3api/s3tables/handler_bucket_format_test.go +++ b/weed/s3api/s3tables/handler_bucket_format_test.go @@ -1,7 +1,6 @@ package s3tables import ( - "context" "encoding/json" "testing" @@ -40,7 +39,7 @@ func bucketWithFormat(t *testing.T, format string) (*s3tablestest.MemFiler, *Man func createTableOfFormat(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, name, format string) error { t.Helper() - return m.Execute(context.Background(), NewManagerClient(fs.Client), "CreateTable", &CreateTableRequest{ + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), "CreateTable", &CreateTableRequest{ TableBucketARN: "arn:aws:s3tables:::bucket/" + formatTestBucket, Namespace: []string{"ns"}, Name: name, @@ -81,7 +80,7 @@ func TestUndeclaredBucketAcceptsEitherFormat(t *testing.T) { func TestCreateViewRefusedInALanceBucket(t *testing.T) { fs, m := bucketWithFormat(t, FormatLance) - err := m.Execute(context.Background(), NewManagerClient(fs.Client), "CreateView", &CreateViewRequest{ + err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "CreateView", &CreateViewRequest{ TableBucketARN: "arn:aws:s3tables:::bucket/" + formatTestBucket, Namespace: []string{"ns"}, Name: "v", @@ -132,7 +131,7 @@ func TestCreateTableBucketNeedsSSES3ForADeclaredLanceBucket(t *testing.T) { m := NewManager() m.SetEncryptionChecker(func() bool { return false }) create := func(name, format string, cfg map[string]interface{}) error { - return m.Execute(context.Background(), NewManagerClient(fs.Client), "CreateTableBucket", + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), "CreateTableBucket", &CreateTableBucketRequest{Name: name, Format: format, EncryptionConfiguration: cfg}, nil, s3_constants.AccountAdminId) } aes := map[string]interface{}{"sseAlgorithm": "AES256"} diff --git a/weed/s3api/s3tables/handler_delete_create_race_test.go b/weed/s3api/s3tables/handler_delete_create_race_test.go index 7f51145d10..a187860a9d 100644 --- a/weed/s3api/s3tables/handler_delete_create_race_test.go +++ b/weed/s3api/s3tables/handler_delete_create_race_test.go @@ -470,7 +470,7 @@ func TestListingsSkipAnUnfinishedCreate(t *testing.T) { var names []string if op.operation == "CreateView" { list := &ListViewsResponse{} - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "ListViews", &ListViewsRequest{ + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "ListViews", &ListViewsRequest{ TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, }, list, "")) @@ -479,7 +479,7 @@ func TestListingsSkipAnUnfinishedCreate(t *testing.T) { } } else { list := &ListTablesResponse{} - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "ListTables", &ListTablesRequest{ + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "ListTables", &ListTablesRequest{ TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, }, list, "")) diff --git a/weed/s3api/s3tables/handler_delete_decouple_test.go b/weed/s3api/s3tables/handler_delete_decouple_test.go index 896ff730a3..3a5d87165a 100644 --- a/weed/s3api/s3tables/handler_delete_decouple_test.go +++ b/weed/s3api/s3tables/handler_delete_decouple_test.go @@ -1,7 +1,6 @@ package s3tables import ( - "context" "encoding/json" "net/http" "path" @@ -15,7 +14,7 @@ import ( func runDeleteTable(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, namespace, name string) error { t.Helper() - return m.Execute(context.Background(), NewManagerClient(fs.Client), "DeleteTable", &DeleteTableRequest{ + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), "DeleteTable", &DeleteTableRequest{ TableBucketARN: mustBucketARN(t), Namespace: []string{namespace}, Name: name, diff --git a/weed/s3api/s3tables/handler_delete_keeps_uploads_test.go b/weed/s3api/s3tables/handler_delete_keeps_uploads_test.go index fec004404c..2d123c5a5c 100644 --- a/weed/s3api/s3tables/handler_delete_keeps_uploads_test.go +++ b/weed/s3api/s3tables/handler_delete_keeps_uploads_test.go @@ -71,7 +71,7 @@ func TestDeleteKeepsFilesOlderThanTheRecord(t *testing.T) { fs, m := startRenameManager(t) stagedAt := time.Now().Add(-time.Minute) upload(fs, "t2", stagedAt.Add(30*time.Second)) - require.NoError(t, m.Execute(WithTableStagedAt(context.Background(), stagedAt), NewManagerClient(fs.Client), "CreateTable", + require.NoError(t, m.Execute(WithCatalogAssignedLocation(WithTableStagedAt(context.Background(), stagedAt)), NewManagerClient(fs.Client), "CreateTable", &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t2", Format: FormatIceberg, MetadataLocation: renameLocation("ns/t2/metadata/v1.metadata.json")}, nil, "admin")) diff --git a/weed/s3api/s3tables/handler_existence_hiding_test.go b/weed/s3api/s3tables/handler_existence_hiding_test.go index 63a912e4c5..0838dc4f13 100644 --- a/weed/s3api/s3tables/handler_existence_hiding_test.go +++ b/weed/s3api/s3tables/handler_existence_hiding_test.go @@ -1,7 +1,6 @@ package s3tables import ( - "context" "encoding/json" "fmt" "net/http/httptest" @@ -24,7 +23,7 @@ func runUnauthorizedRequest(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, body, err := json.Marshal(input) require.NoError(t, err) identity := &testIdentity{Name: "attacker", Account: &testIdentityAccount{Id: "attacker"}, Actions: []string{"Read"}} - ctx := s3_constants.SetIdentityInContext(context.Background(), identity) + ctx := s3_constants.SetIdentityInContext(assignedCtx(), identity) req, err := newManagerRequest(ctx, operation, body, "attacker") require.NoError(t, err) @@ -114,7 +113,7 @@ func TestTableAuthorizationDenialMatchesMissing(t *testing.T) { func TestDeleteTableAuthorizedVersionMismatchStillConflicts(t *testing.T) { fs, manager := startRenameManager(t) - err := manager.Execute(context.Background(), NewManagerClient(fs.Client), "DeleteTable", &DeleteTableRequest{ + err := manager.Execute(assignedCtx(), NewManagerClient(fs.Client), "DeleteTable", &DeleteTableRequest{ TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t", @@ -134,7 +133,7 @@ func runRequestAs(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, operation body, err := json.Marshal(input) require.NoError(t, err) identity := &testIdentity{Name: "reader", Account: &testIdentityAccount{Id: "reader"}, Actions: actions} - ctx := s3_constants.SetIdentityInContext(context.Background(), identity) + ctx := s3_constants.SetIdentityInContext(assignedCtx(), identity) req, err := newManagerRequest(ctx, operation, body, "reader") require.NoError(t, err) @@ -406,3 +405,31 @@ func TestCreateTableDenialMatchesMissingNamespace(t *testing.T) { }) } } + +// A CreateTable of a name that exists answers the existing table only to a +// caller who may read it (create-if-not-exists); a caller who may only create +// is told the name is taken, and nothing about the table (its location). +func TestCreateExistingTableAnswersOnlyAReaderWithIt(t *testing.T) { + fs, manager := startRenameManager(t) + manager.SetTrusted(false) + manager.SetDefaultAllow(false) + request := &CreateTableRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns"}, Name: "t", Format: FormatIceberg} + + got := runRequestAs(t, manager, fs, "CreateTable", request, []string{"s3tables:CreateTable"}) + assert.Equal(t, 409, got.status) + assert.Equal(t, ErrCodeTableAlreadyExists, got.body.Type) + assert.NotContains(t, got.body.Message, "metadata", "the refusal names no location") + + // positive control: a reader gets the existing table + body, err := json.Marshal(request) + require.NoError(t, err) + identity := &testIdentity{Name: "reader", Account: &testIdentityAccount{Id: "reader"}, Actions: []string{"s3tables:CreateTable", "s3tables:GetTable"}} + req, err := newManagerRequest(s3_constants.SetIdentityInContext(assignedCtx(), identity), "CreateTable", body, "reader") + require.NoError(t, err) + recorder := httptest.NewRecorder() + manager.handler.HandleRequest(recorder, req, NewManagerClient(fs.Client)) + require.Equal(t, 200, recorder.Code, recorder.Body.String()) + var created CreateTableResponse + require.NoError(t, json.NewDecoder(recorder.Body).Decode(&created)) + assert.Equal(t, "s3://"+renameTestBucket+"/ns/t/metadata/v3.metadata.json", created.MetadataLocation) +} diff --git a/weed/s3api/s3tables/handler_location_owner_test.go b/weed/s3api/s3tables/handler_location_owner_test.go index 55774ed52f..9dea8531c8 100644 --- a/weed/s3api/s3tables/handler_location_owner_test.go +++ b/weed/s3api/s3tables/handler_location_owner_test.go @@ -393,6 +393,91 @@ func TestRecordGoneDropsItsMoveReservation(t *testing.T) { }) } +// assignedCtx is the context of a catalog call this process makes: the +// Iceberg REST catalog and the Lance namespace pass the locations they were +// assigned (or, for a register, existing files), which a client's CreateTable +// or CreateView may not (WithCatalogAssignedLocation). Tests that are about +// another rule set up their tables through it. +func assignedCtx() context.Context { + return WithCatalogAssignedLocation(context.Background()) +} + +// A client's CreateTable or CreateView names no location: the catalog +// assigns one. Naming one is refused with 400 and nothing is created; only +// this process's own callers, which pass the location they were assigned, may. +func TestAClientCreateNamesNoLocation(t *testing.T) { + fs, m := startRenameManager(t) + bucketARN := mustBucketARN(t) + nsPath := GetNamespacePath(renameTestBucket, "ns") + client := func(op string, req interface{}) error { + return m.Execute(context.Background(), NewManagerClient(fs.Client), op, req, nil, "") + } + for name, c := range map[string]struct { + op string + req interface{} + }{ + "iceberg table": {"CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine", Format: FormatIceberg, + MetadataLocation: renameLocation("ns/mine/metadata/v1.metadata.json")}}, + "lance table": {"CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine2", Format: FormatLance, + MetadataLocation: renameLocation("ns/mine2")}}, + "view": {"CreateView", &CreateViewRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine3", + MetadataLocation: renameLocation("ns/mine3/metadata/v1.metadata.json")}}, + } { + var s3Err *S3TablesError + if assert.ErrorAs(t, client(c.op, c.req), &s3Err, name) { + assert.Equal(t, ErrCodeInvalidRequest, s3Err.Type, name) + } + } + for _, name := range []string{"mine", "mine2", "mine3"} { + assert.Nil(t, fs.Get(nsPath, name), name) + } + // positive controls: a client create without a location, and the catalog's own call with one + require.NoError(t, client("CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "plain", Format: FormatIceberg})) + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: "mine", Format: FormatIceberg, + MetadataLocation: renameLocation("ns/mine/metadata/v1.metadata.json")}, nil, "")) +} + +// A live Iceberg stage-create holds its location like the record it commits +// to: a create over it is refused, while a create of the stage's name at +// another location, and any create once the stage has expired, goes ahead. +func TestALiveStageHoldsItsLocation(t *testing.T) { + fs, m := startRenameManager(t) + bucketARN := mustBucketARN(t) + stage := func(t *testing.T, table, location string, expiresAt time.Time) { + t.Helper() + content, err := json.Marshal(map[string]string{"location": renameLocation(location), "expires_at": expiresAt.UTC().Format(time.RFC3339Nano)}) + require.NoError(t, err) + stagedDir := path.Join(GetTableBucketPath(renameTestBucket), StagedTablesDirName) + fs.Put(GetTableBucketPath(renameTestBucket), StagedTablesDirName, nil) + fs.Put(stagedDir, "ns", nil) + fs.Put(path.Join(stagedDir, "ns"), table, nil) + dir := path.Join(stagedDir, "ns", table) + _, err = fs.Client.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{Directory: dir, Entry: &filer_pb.Entry{Name: table + ".json", Content: content}}) + require.NoError(t, err) + } + create := func(name string) (int, S3TablesError) { + return runHandler(t, m, fs.Client, "CreateTable", &CreateTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: name, Format: FormatLance}) + } + + stage(t, "staged", "ns/lance1/data", time.Now().Add(time.Hour)) + status, resp := create("lance1") + assert.Equal(t, http.StatusConflict, status, "%+v", resp) + assert.Nil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "lance1")) + + stage(t, "lance2", "ns/lance2/data", time.Now().Add(time.Hour)) + status, resp = create("lance2") + assert.Equal(t, http.StatusConflict, status, "a stage of the same name: %+v", resp) + assert.Nil(t, fs.Get(GetNamespacePath(renameTestBucket, "ns"), "lance2")) + + stage(t, "lance4", "ns/lance4-x", time.Now().Add(time.Hour)) + status, resp = create("lance4") + assert.Equal(t, http.StatusOK, status, "a stage of the same name elsewhere: %+v", resp) + + stage(t, "expired", "ns/lance3/data", time.Now().Add(-time.Hour)) + status, resp = create("lance3") + assert.Equal(t, http.StatusOK, status, "%+v", resp) +} + // An update may not move a table's root: its older snapshots keep naming files // under the root it has, which a move would leave to no record. A table then // registered over that root would load them, and its drop would purge them. diff --git a/weed/s3api/s3tables/handler_namespace_keeps_data_test.go b/weed/s3api/s3tables/handler_namespace_keeps_data_test.go index f7b51098e3..b9b8e63e8f 100644 --- a/weed/s3api/s3tables/handler_namespace_keeps_data_test.go +++ b/weed/s3api/s3tables/handler_namespace_keeps_data_test.go @@ -49,7 +49,7 @@ func keptDataDir() string { func listedNamespaces(t *testing.T, m *Manager, fs *s3tablestest.MemFiler) []string { t.Helper() resp := &ListNamespacesResponse{} - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "ListNamespaces", + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "ListNamespaces", &ListNamespacesRequest{TableBucketARN: mustBucketARN(t)}, resp, "")) names := make([]string, 0, len(resp.Namespaces)) for _, namespace := range resp.Namespaces { diff --git a/weed/s3api/s3tables/handler_ownerless_test.go b/weed/s3api/s3tables/handler_ownerless_test.go index 97c2079196..b6beb3fdaa 100644 --- a/weed/s3api/s3tables/handler_ownerless_test.go +++ b/weed/s3api/s3tables/handler_ownerless_test.go @@ -1,7 +1,6 @@ package s3tables import ( - "context" "encoding/json" "net/http" "net/http/httptest" @@ -32,7 +31,7 @@ func TestCreateNamespaceOnAnOwnerlessBucket(t *testing.T) { body, err := json.Marshal(request) require.NoError(t, err) identity := &testIdentity{Name: "outsider", Account: &testIdentityAccount{Id: "outsider"}, Actions: []string{"Read"}} - req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "outsider") + req, err := newManagerRequest(s3_constants.SetIdentityInContext(assignedCtx(), identity), "CreateNamespace", body, "outsider") require.NoError(t, err) recorder := httptest.NewRecorder() @@ -52,7 +51,7 @@ func TestCreateNamespaceOnAnOwnerlessBucket(t *testing.T) { body, err := json.Marshal(request) require.NoError(t, err) identity := &testIdentity{Name: "svc", Account: &testIdentityAccount{Id: "svc"}, Actions: []string{"Read"}} - req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "svc") + req, err := newManagerRequest(s3_constants.SetIdentityInContext(assignedCtx(), identity), "CreateNamespace", body, "svc") require.NoError(t, err) recorder := httptest.NewRecorder() @@ -73,7 +72,7 @@ func TestCreateNamespaceOnAnOwnerlessBucket(t *testing.T) { body, err := json.Marshal(request) require.NoError(t, err) identity := &testIdentity{Name: "admin", Account: &testIdentityAccount{Id: s3_constants.AccountAdminId}, Actions: []string{"Admin"}} - req, err := newManagerRequest(s3_constants.SetIdentityInContext(context.Background(), identity), "CreateNamespace", body, "admin") + req, err := newManagerRequest(s3_constants.SetIdentityInContext(assignedCtx(), identity), "CreateNamespace", body, "admin") require.NoError(t, err) recorder := httptest.NewRecorder() diff --git a/weed/s3api/s3tables/handler_policy_deny_test.go b/weed/s3api/s3tables/handler_policy_deny_test.go index 3140559b55..6dce2a0f41 100644 --- a/weed/s3api/s3tables/handler_policy_deny_test.go +++ b/weed/s3api/s3tables/handler_policy_deny_test.go @@ -1,7 +1,6 @@ package s3tables import ( - "context" "encoding/json" "fmt" "path" @@ -71,7 +70,7 @@ func startPolicyDenyManager(t *testing.T) (*s3tablestest.MemFiler, *Manager) { func runPolicyOp(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, op string, req interface{}, identity string) error { t.Helper() - return m.Execute(context.Background(), NewManagerClient(fs.Client), op, req, nil, identity) + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), op, req, nil, identity) } func deniedTableReq(t *testing.T) (string, string, string) { diff --git a/weed/s3api/s3tables/handler_rename_test.go b/weed/s3api/s3tables/handler_rename_test.go index db3f7bae47..de86813303 100644 --- a/weed/s3api/s3tables/handler_rename_test.go +++ b/weed/s3api/s3tables/handler_rename_test.go @@ -66,13 +66,13 @@ func startRenameManager(t *testing.T) (*s3tablestest.MemFiler, *Manager) { func runRename(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, req *RenameTableRequest) error { t.Helper() - return m.Execute(context.Background(), NewManagerClient(fs.Client), "RenameTable", req, nil, "") + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), "RenameTable", req, nil, "") } func runGetTable(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, namespace, name string) (*GetTableResponse, error) { t.Helper() resp := &GetTableResponse{} - err := m.Execute(context.Background(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{ + err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{ TableBucketARN: mustBucketARN(t), Namespace: []string{namespace}, Name: name, @@ -260,7 +260,7 @@ func TestRenameTableDestNamespaceUnauthorized(t *testing.T) { fs.Put(GetTableBucketPath(renameTestBucket), "dest", map[string][]byte{ExtendedKeyMetadata: destNsMeta}) mover := &testIdentity{Name: "mover", Account: &testIdentityAccount{Id: "mover"}} - ctx := s3_constants.SetIdentityInContext(context.Background(), mover) + ctx := s3_constants.SetIdentityInContext(assignedCtx(), mover) err := m.Execute(ctx, NewManagerClient(fs.Client), "RenameTable", &RenameTableRequest{ TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, diff --git a/weed/s3api/s3tables/handler_table.go b/weed/s3api/s3tables/handler_table.go index 5d11a2781b..b3f9f3d700 100644 --- a/weed/s3api/s3tables/handler_table.go +++ b/weed/s3api/s3tables/handler_table.go @@ -39,6 +39,10 @@ func (h *S3TablesHandler) handleCreateTable(w http.ResponseWriter, r *http.Reque h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, fmt.Sprintf("unsupported format %q", req.Format)) return fmt.Errorf("invalid format") } + if req.MetadataLocation != "" && !catalogAssignedLocation(r.Context()) { + h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, ErrClientTableLocation.Error()) + return ErrClientTableLocation + } target, err := h.authorizeCreateTable(w, r, filerClient, req.TableBucketARN, req.Namespace, req.Name, req.Tags, false) if err != nil { @@ -90,6 +94,16 @@ func (h *S3TablesHandler) handleCreateTable(w http.ResponseWriter, r *http.Reque h.writeError(w, http.StatusConflict, ErrCodeTableAlreadyExists, fmt.Sprintf("a view named %s already exists", tableName)) return fmt.Errorf("view name conflict: %s", tableName) } + // only a caller who may read the existing table gets it back + readable, readErr := h.mayReadTable(r, filerClient, bucketName, namespaceName, tableName, tablePath, existingMetadata.OwnerAccountID) + if readErr != nil { + h.writeError(w, http.StatusInternalServerError, ErrCodeInternalError, "failed to check table") + return readErr + } + if !readable { + h.writeError(w, http.StatusConflict, ErrCodeTableAlreadyExists, fmt.Sprintf("table %s already exists", tableName)) + return fmt.Errorf("table %s already exists", tableName) + } // Creating a table that already exists is idempotent, but only for the // same format. Handing a Lance client an Iceberg table's location, or the // reverse, has it write one format's files into the other's directory. @@ -2486,3 +2500,25 @@ func (h *S3TablesHandler) refuseClaimedNamespace(w http.ResponseWriter, r *http. } return nil } + +// mayReadTable reports whether the caller may read (GetTable) the existing +// table at tablePath, under its own and its bucket's policies and tags. +func (h *S3TablesHandler) mayReadTable(r *http.Request, filerClient FilerClient, bucketName, namespaceName, tableName, tablePath, ownerAccountID string) (bool, error) { + tablePolicy, bucketPolicy, bucketTags, bucketMetadata, err := h.loadAuthContext(r, filerClient, tablePath, GetTableBucketPath(bucketName)) + if err != nil { + return false, err + } + var tableTags map[string]string + err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + var err error + tableTags, err = h.readTags(r.Context(), client, tablePath) + return err + }) + if err != nil { + return false, err + } + tableARN := h.generateTableARN(ownerAccountID, bucketName, namespaceName+"/"+tableName) + bucketARN := h.generateTableBucketARN(bucketMetadata.OwnerAccountID, bucketName) + return h.canReadEntry("GetTable", h.getAccountID(r), ownerAccountID, bucketMetadata.OwnerAccountID, tablePolicy, bucketPolicy, + tableARN, bucketARN, bucketName, namespaceName, tableName, bucketTags, tableTags, getIdentityActions(r), r), nil +} diff --git a/weed/s3api/s3tables/handler_update_after_rename_test.go b/weed/s3api/s3tables/handler_update_after_rename_test.go index 40470e2e8d..995376d4fa 100644 --- a/weed/s3api/s3tables/handler_update_after_rename_test.go +++ b/weed/s3api/s3tables/handler_update_after_rename_test.go @@ -154,7 +154,7 @@ func TestUpdateLocationIsCheckedAfterAuthorization(t *testing.T) { m.SetTrusted(false) m.SetDefaultAllow(false) stranger := &testIdentity{Name: "stranger", Account: &testIdentityAccount{Id: "stranger"}} - ctx := s3_constants.SetIdentityInContext(context.Background(), stranger) + ctx := s3_constants.SetIdentityInContext(assignedCtx(), stranger) err := updateTableAt(ctx, t, m, fs, "ns2", "s3://"+renameTestBucket+"/ns/elsewhere/metadata/v4.metadata.json") require.Error(t, err) @@ -167,14 +167,14 @@ func renameViewAcrossNamespaces(t *testing.T) (*s3tablestest.MemFiler, *Manager) fs, m := startRenameManager(t) seedView(t, fs, "v") addRenameNamespace(t, fs, "ns2") - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "RenameView", &RenameTableRequest{ + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "RenameView", &RenameTableRequest{ TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, SourceName: "v", DestNamespace: []string{"ns2"}, DestName: "v", }, nil, "")) return fs, m } func updateViewAt(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, location string) error { - return m.Execute(context.Background(), NewManagerClient(fs.Client), "UpdateView", &UpdateViewRequest{TableBucketARN: mustBucketARN(t), + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), "UpdateView", &UpdateViewRequest{TableBucketARN: mustBucketARN(t), Namespace: []string{"ns2"}, Name: "v", MetadataVersion: 2, MetadataLocation: location}, nil, "") } diff --git a/weed/s3api/s3tables/handler_update_cas_test.go b/weed/s3api/s3tables/handler_update_cas_test.go index aca6539fd9..a3b66a26e0 100644 --- a/weed/s3api/s3tables/handler_update_cas_test.go +++ b/weed/s3api/s3tables/handler_update_cas_test.go @@ -1,7 +1,6 @@ package s3tables import ( - "context" "encoding/json" "testing" @@ -43,7 +42,7 @@ func TestUpdateTableRejectsLostUpdate(t *testing.T) { } loserLocation := "s3://" + renameTestBucket + "/ns/t/metadata/v4-loser.metadata.json" - err := m.Execute(context.Background(), NewManagerClient(fs.Client), "UpdateTable", + err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "UpdateTable", updateTableRequest(t, loserLocation, 4), nil, "") require.Error(t, err) @@ -71,7 +70,7 @@ func TestUpdateTableRejectsWhenTheAuthorizingPolicyChanges(t *testing.T) { } location := "s3://" + renameTestBucket + "/ns/t/metadata/v4.metadata.json" - err := m.Execute(context.Background(), NewManagerClient(fs.Client), "UpdateTable", + err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "UpdateTable", updateTableRequest(t, location, 4), nil, "") require.Error(t, err) @@ -88,7 +87,7 @@ func TestUpdateTableAppliesWithoutContention(t *testing.T) { fs, m := startRenameManager(t) location := "s3://" + renameTestBucket + "/ns/t/metadata/v4.metadata.json" - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "UpdateTable", + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "UpdateTable", updateTableRequest(t, location, 4), nil, "")) got, err := runGetTable(t, m, fs, "ns", "t") diff --git a/weed/s3api/s3tables/handler_view.go b/weed/s3api/s3tables/handler_view.go index 7226136e05..bda15f483b 100644 --- a/weed/s3api/s3tables/handler_view.go +++ b/weed/s3api/s3tables/handler_view.go @@ -29,6 +29,10 @@ func (h *S3TablesHandler) handleCreateView(w http.ResponseWriter, r *http.Reques h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, "tableBucketARN is required") return fmt.Errorf("tableBucketARN is required") } + if req.MetadataLocation != "" && !catalogAssignedLocation(r.Context()) { + h.writeError(w, http.StatusBadRequest, ErrCodeInvalidRequest, ErrClientTableLocation.Error()) + return ErrClientTableLocation + } namespaceName, err := validateNamespace(req.Namespace) if err != nil { diff --git a/weed/s3api/s3tables/handler_view_rename_test.go b/weed/s3api/s3tables/handler_view_rename_test.go index 3f7149a0aa..76358081a6 100644 --- a/weed/s3api/s3tables/handler_view_rename_test.go +++ b/weed/s3api/s3tables/handler_view_rename_test.go @@ -39,7 +39,7 @@ func seedView(t *testing.T, fs *s3tablestest.MemFiler, name string) { func runRenameView(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, sourceName, destName string) error { t.Helper() - return m.Execute(context.Background(), NewManagerClient(fs.Client), "RenameView", &RenameTableRequest{ + return m.Execute(assignedCtx(), NewManagerClient(fs.Client), "RenameView", &RenameTableRequest{ TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, SourceName: sourceName, @@ -148,7 +148,7 @@ func TestRenameViewAuthorizesAgainstTheViewARN(t *testing.T) { require.NotNil(t, namespace) namespace.Extended[ExtendedKeyPolicy] = []byte(namespacePolicy) - err := m.Execute(context.Background(), NewManagerClient(fs.Client), "RenameView", &RenameTableRequest{ + err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "RenameView", &RenameTableRequest{ TableBucketARN: mustBucketARN(t), SourceNamespace: []string{"ns"}, SourceName: "v", diff --git a/weed/s3api/s3tables/handler_warehouse_location_test.go b/weed/s3api/s3tables/handler_warehouse_location_test.go index 852060223e..2ee712e816 100644 --- a/weed/s3api/s3tables/handler_warehouse_location_test.go +++ b/weed/s3api/s3tables/handler_warehouse_location_test.go @@ -133,7 +133,7 @@ func TestBackedOutCreateRemovesItsDirectory(t *testing.T) { func getTable(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, bucketARN, name string, out *GetTableResponse) { t.Helper() - require.NoError(t, m.Execute(context.Background(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: name}, out, "")) + require.NoError(t, m.Execute(assignedCtx(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{TableBucketARN: bucketARN, Namespace: []string{"ns"}, Name: name}, out, "")) } type noListClient struct { diff --git a/weed/s3api/s3tables/manager_test.go b/weed/s3api/s3tables/manager_test.go index b7f90c9115..6bc71bd160 100644 --- a/weed/s3api/s3tables/manager_test.go +++ b/weed/s3api/s3tables/manager_test.go @@ -45,7 +45,7 @@ func TestManagerCreateTableBucketAuthorization(t *testing.T) { { name: "authenticated identity struct is enforced", defaultAllow: true, - ctx: s3_constants.SetIdentityInContext(context.Background(), lowPriv), + ctx: s3_constants.SetIdentityInContext(assignedCtx(), lowPriv), identity: "alice", wantFiler: false, }, @@ -120,7 +120,7 @@ func TestManagerCreateTableBucketRejectsCustomerKeys(t *testing.T) { t.Run(tc.name, func(t *testing.T) { m := NewManager() fc := &recordingFilerClient{} - err := m.Execute(context.Background(), fc, "CreateTableBucket", &CreateTableBucketRequest{ + err := m.Execute(assignedCtx(), fc, "CreateTableBucket", &CreateTableBucketRequest{ Name: "testbucket", EncryptionConfiguration: tc.cfg, }, nil, s3_constants.AccountAdminId) diff --git a/weed/s3api/s3tables/vector_namespace_test.go b/weed/s3api/s3tables/vector_namespace_test.go index 2fe9056439..d13204dade 100644 --- a/weed/s3api/s3tables/vector_namespace_test.go +++ b/weed/s3api/s3tables/vector_namespace_test.go @@ -30,7 +30,7 @@ func seedVectorBucket(t *testing.T, fs *s3tablestest.MemFiler, format string) *M trusted.SetTrusted(true) run := func(operation string, req interface{}) { t.Helper() - require.NoError(t, trusted.Execute(context.Background(), NewManagerClient(fs.Client), operation, req, nil, "")) + require.NoError(t, trusted.Execute(assignedCtx(), NewManagerClient(fs.Client), operation, req, nil, "")) } arn := vectorTestARN(t) run("CreateTableBucket", &CreateTableBucketRequest{Name: vectorTestBucket, Format: format}) @@ -50,7 +50,7 @@ func seedVectorBucket(t *testing.T, fs *s3tablestest.MemFiler, format string) *M func getTestTable(t *testing.T, m *Manager, fs *s3tablestest.MemFiler, namespace, name string) (*GetTableResponse, error) { t.Helper() var resp GetTableResponse - err := m.Execute(context.Background(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{ + err := m.Execute(assignedCtx(), NewManagerClient(fs.Client), "GetTable", &GetTableRequest{ TableBucketARN: vectorTestARN(t), Namespace: []string{namespace}, Name: name}, &resp, "") return &resp, err } @@ -132,7 +132,7 @@ func TestVectorNamespaceRefusesUntrustedWrites(t *testing.T) { assert.Error(t, err, "%s/%s should not exist", absent[0], absent[1]) } var tags ListTagsForResourceResponse - require.NoError(t, trusted.Execute(context.Background(), NewManagerClient(fs.Client), "ListTagsForResource", + require.NoError(t, trusted.Execute(assignedCtx(), NewManagerClient(fs.Client), "ListTagsForResource", &ListTagsForResourceRequest{ResourceARN: before.TableARN}, &tags, "")) assert.Equal(t, map[string]string{"k": "v"}, tags.Tags) } @@ -191,7 +191,7 @@ func TestVectorNamespaceAllowsReadsAndExistingCreate(t *testing.T) { require.NoError(t, err) assert.Equal(t, before.VersionToken, after.VersionToken) - require.NoError(t, trusted.Execute(context.Background(), NewManagerClient(fs.Client), "DeleteTable", + require.NoError(t, trusted.Execute(assignedCtx(), NewManagerClient(fs.Client), "DeleteTable", &DeleteTableRequest{TableBucketARN: arn, Namespace: vector, Name: "idx"}, nil, ""), "the trusted path stays writable") } @@ -252,7 +252,7 @@ func TestVectorNamespaceDenialHidesBucketFormat(t *testing.T) { // its gate refuses the vector namespace as the create itself would. func TestAuthorizeCreateTableRefusesVectorNamespace(t *testing.T) { identity := &testIdentity{Name: "reader", Account: &testIdentityAccount{Id: "reader"}, Actions: []string{"s3tables:*"}} - ctx := s3_constants.SetIdentityInContext(context.Background(), identity) + ctx := s3_constants.SetIdentityInContext(assignedCtx(), identity) req := &CreateTableRequest{TableBucketARN: vectorTestARN(t), Namespace: []string{VectorIndexNamespace}, Name: "fresh"} lanceFS := s3tablestest.Start(t)