mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
* mq: add a table option to topic configuration
ConfigureTopicRequest, ConfigureTopicResponse and
GetTopicConfigurationResponse carry a TopicTable: the table bucket ARN,
namespace and name of the Iceberg table that holds the topic's compacted
history. A request without it keeps whatever the topic has; one with an
empty table bucket ARN asks to detach it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq: map a topic's record type to an Iceberg table layout
The topictable package lays out the table a topic's compacted history
goes into. Its columns are _partition, _offset, _ts_ns, _ts (a
timestamptz copy of _ts_ns to partition on) and _key, then the record's
fields, or _value for a schemaless topic. Scalars map to their Iceberg
counterparts, TIMESTAMP to timestamptz, records to structs and repeated
fields or list types to lists, with required-ness taken from the field.
A DECIMAL field has no precision or scale of its own, so it takes the
decimal(38, 18) the topic's parquet files already use.
The spec is identity(_partition) and day(_ts), the sort order _partition
then _offset, and the seaweedfs.mq.topic property names the owning topic.
CheckSchema says whether an existing table can hold a topic's rows,
matching columns by name so the ids a table assigns do not matter.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* iceberg: create and load a table in process
The create handler splits into planCreateTable, which checks the name,
authorizes the create and builds the first metadata, and
registerCreateTable, which stages the metadata file and registers the
table, with stage-create still handled between them in the handler.
Server.CreateTable runs both for a caller inside the cluster, and
Server.LoadTable answers what a load does, sharing the GetTable call and
the metadata parse with the handler. A server-side component that needs
its own table now gets the same location, metadata file, exclusive
staging and cleanup as a REST client, rather than writing metadata by
hand.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: keep a topic's table in topic.conf
ConfigureTopic stores the requested table with the rest of the topic's
configuration, so it survives restarts and moves to another balancer. A
request that does not name a table keeps the stored one, including one
that changes the partition count, and an empty table bucket ARN detaches
it. GetTopicConfiguration returns it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: create or adopt a topic's table on ConfigureTopic
When a configure names a table, or changes the schema of a topic that
has one, the balancer loads the table through the Iceberg catalog the
broker now keeps over its filers. A missing table is created through the
catalog's own create path with the topic's layout and the
seaweedfs.mq.topic property; the table bucket and namespace must already
exist. An existing table is accepted only if that property names this
topic, its location is inside its table bucket, and its columns can hold
the topic's rows, so a topic never takes over a table it did not create
and a schema change the table cannot follow is refused.
The broker creates the table with no caller identity, as trusted
cluster tooling, so the table is owned by its namespace's owner like any
other table there. Deleting a topic only removes /topics and leaves the
table.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: refuse to leave a topic table that holds data
A configure that detaches a topic from its table, or points it at
another one, first loads the current table, and is refused while that
table has any snapshot: its history would be left with no topic to read
or trim it. A table that is still empty, or that its owner has dropped,
can be left, and stays where it is with its property. Detaching a table
that holds data is left to an explicit command.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: pass the table catalog's answers through the filer accessor
The filer accessor treats any error as a failed filer: it records the
failure, asks the next filer and wraps the last error with %v. A catalog
answer such as NoSuchTable then reached ConfigureTopic as an opaque
string, so a missing table was reported instead of created. The catalog
now goes through an adapter that returns the catalog's own answers
unwrapped and leaves failover to real filer failures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: a table hidden by its policy still holds the topic's history
GetTable answers NoSuchTable both for a table that is gone and for one a
policy denies the caller, so a topic whose table carried snapshots under
a policy denying GetTable could detach as if the table had been
dropped. When the catalog says the table is missing, the broker now
looks for its record in the filer with the new s3tables.TableRegistered,
which finds what GetTable finds before policy, and refuses to leave a
table that is registered but unreadable.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: fail over the table catalog's internal errors
The adapter between the table catalog and the filer accessor passed
every S3TablesError back as a successful filer call. An InternalError is
what the catalog answers when its own read of the filer fails, so a
broken filer was recorded healthy and no other filer was asked. Only
the catalog's refusals pass through now; an internal error goes back to
the accessor, which marks the filer failed and tries the next one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq: name a table's owning topic by its path under /topics
The seaweedfs.mq.topic property was <namespace>.<topic>, and topic names
may hold dots, so a.b/c and a/b.c wrote the same value and either could
adopt the other's table. The value is now <namespace>/<topic>, the
topic's directory under /topics: two topics that write the same value
already share one topic.conf, so they are the same topic.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq: reserve the day partition field's name in a topic's table layout
The spec partitions by day(_ts) under the name _ts_day, and Iceberg only
lets a partition field share a column's name when it is that column's
identity. A topic with its own _ts_day field mapped fine and then failed
the table create with an invalid partition spec. Schema now refuses the
name up front, with the system columns, saying it is reserved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: let the table catalog fail over to every discovered filer
The broker's filer accessor lists only the current filer, so the
failover the catalog adapter relies on had nowhere to go: an internal
error from the current filer failed the catalog call even with another
healthy filer discovered. The catalog now gets an accessor of its own
over every filer the broker has discovered, the current one first, read
under the lock that guards them. The broker's shared accessor stays on
the current filer, so topic.conf, offsets and the subscriber coordinator
keep reading one filer as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: a topic leaves a table that no longer names it
A table dropped and replaced under the same name by one that does not
carry the topic's property holds none of the topic's history, so its
snapshots no longer keep the topic from detaching, switching tables, or
following a schema change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* s3tables: keep tableMetadata's doc comment on tableMetadata
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: walk the table catalog's filers in order, current first
FilerClientAccessor shuffles the filers it is given, so the catalog's
create, load and registration calls each went to a random discovered
filer even while the current one answered. A filer with its own store
may not yet hold what another just wrote. Try the current filer first
and move on to the others only when it fails, as the S3 gateway does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Revert "mq broker: a topic leaves a table that no longer names it"
The property alone does not show the table was replaced: a
set-properties commit on the same table changes it and keeps the
snapshots, and the topic would then leave its history behind. Telling a
replacement apart needs the table's identity stored with the topic.
This reverts commit ddeb10a89b.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* mq broker: tell a replaced topic table from its own by UUID
A topic could not leave a table that was dropped and replaced at its
name by an unrelated table holding data: the snapshot guard refused to
detach or switch, and the ownership check refused to adopt. A changed
seaweedfs.mq.topic property does not prove a replacement, since a
set-properties commit keeps the same table and its snapshots.
TopicTable now carries the Iceberg table UUID, which the broker records
in topic.conf after it creates or adopts the table; a request cannot set
it. Requests are compared by bucket ARN, namespace and name only. When
the topic leaves its table, a loaded table whose UUID differs from the
recorded one is a replacement and is let go without the snapshot guard.
A matching UUID, or a topic.conf written before the UUID was recorded,
stays under the guard. Taking a table at the name still goes through
the ownership and schema checks.
Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1203 lines
47 KiB
Go
1203 lines
47 KiB
Go
package iceberg
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/apache/iceberg-go"
|
|
"github.com/apache/iceberg-go/table"
|
|
"github.com/google/uuid"
|
|
"github.com/gorilla/mux"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
|
)
|
|
|
|
var errTableNameRequired = errors.New("table name is required")
|
|
|
|
func validateCreateTableRequest(req CreateTableRequest) error {
|
|
if req.Name == "" {
|
|
return errTableNameRequired
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// partitionSpec returns the requested spec with the client's source IDs, which
|
|
// newTableMetadata resolves through the request schema before assigning fresh
|
|
// IDs.
|
|
func (req CreateTableRequest) partitionSpec() *iceberg.PartitionSpec {
|
|
if req.PartitionSpec == nil {
|
|
return nil
|
|
}
|
|
return &req.PartitionSpec.PartitionSpec
|
|
}
|
|
|
|
// writeOrder returns the requested sort order with the client's source IDs; see
|
|
// partitionSpec.
|
|
func (req CreateTableRequest) writeOrder() *table.SortOrder {
|
|
if req.WriteOrder == nil {
|
|
return nil
|
|
}
|
|
return &req.WriteOrder.SortOrder
|
|
}
|
|
|
|
// handleListTables lists tables in a namespace.
|
|
func (s *Server) handleListTables(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
namespace := parseNamespace(vars["namespace"])
|
|
if len(namespace) == 0 {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
bucketARN := buildTableBucketARN(bucketName)
|
|
|
|
// Extract identity from context
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
pageToken, pageSize, err := parsePagination(r)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
|
return
|
|
}
|
|
|
|
listReq := &s3tables.ListTablesRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
ContinuationToken: pageToken,
|
|
MaxTables: pageSize,
|
|
}
|
|
var listResp s3tables.ListTablesResponse
|
|
|
|
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(r.Context(), mgrClient, "ListTables", listReq, &listResp, identityName)
|
|
})
|
|
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "not found") {
|
|
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", fmt.Sprintf("Namespace does not exist: %v", namespace))
|
|
return
|
|
}
|
|
glog.V(1).Infof("Iceberg: ListTables error: %v", err)
|
|
writeManagerError(w, err)
|
|
return
|
|
}
|
|
|
|
// Convert to Iceberg format
|
|
identifiers := make([]TableIdentifier, 0, len(listResp.Tables))
|
|
for _, t := range listResp.Tables {
|
|
identifiers = append(identifiers, TableIdentifier{
|
|
Namespace: namespace,
|
|
Name: t.Name,
|
|
})
|
|
}
|
|
|
|
result := ListTablesResponse{
|
|
NextPageToken: listResp.ContinuationToken,
|
|
Identifiers: identifiers,
|
|
}
|
|
writeJSON(w, http.StatusOK, result)
|
|
}
|
|
|
|
// authorizeCreateTable checks the caller may create the table at location, for
|
|
// the create paths that touch the bucket before the catalog registers it.
|
|
func (s *Server) authorizeCreateTable(ctx context.Context, bucketARN string, namespace []string, tableName, identityName, location string) error {
|
|
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
return s.tablesManager.AuthorizeCreateTable(ctx, s3tables.NewManagerClient(client), &s3tables.CreateTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
MetadataLocation: location,
|
|
}, identityName)
|
|
})
|
|
}
|
|
|
|
// 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)
|
|
namespace := parseNamespace(vars["namespace"])
|
|
if len(namespace) == 0 {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
|
return
|
|
}
|
|
|
|
var req CreateTableRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid request body: "+err.Error())
|
|
return
|
|
}
|
|
|
|
if err := validateCreateTableRequest(req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", err.Error())
|
|
return
|
|
}
|
|
if req.StageCreate && !isStageCreateEnabled() {
|
|
writeError(w, http.StatusNotImplemented, "NotImplementedException", "stage-create is disabled")
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
|
|
// Extract identity from context
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
plan, reqErr := s.planCreateTable(r.Context(), bucketName, namespace, req, identityName)
|
|
if reqErr != nil {
|
|
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
|
return
|
|
}
|
|
tableName := req.Name
|
|
|
|
// Stage-create persists metadata in the internal staged area and skips S3Tables registration.
|
|
if req.StageCreate {
|
|
stagedTablePath := stageCreateStagedTablePath(namespace, tableName, plan.tableUUID)
|
|
// The staged path carries the table UUID, so the name cannot already be
|
|
// taken; exclusive keeps it that way if it ever is.
|
|
if err := s.saveMetadataFile(r.Context(), plan.metadataBucket, stagedTablePath, plan.metadataFileName, plan.metadataBytes, true); err != nil {
|
|
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to save staged metadata file: "+err.Error())
|
|
return
|
|
}
|
|
stagedMetadataLocation := fmt.Sprintf("s3://%s/%s/metadata/%s", plan.metadataBucket, stagedTablePath, plan.metadataFileName)
|
|
// 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, plan.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, plan.tableUUID, plan.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, plan.metadataPath, plan.location, plan.tableUUID.String(), true); reqErr != nil {
|
|
if err := s.deleteStageCreate(r.Context(), bucketName, namespace, tableName, plan.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: plan.metadataLocation,
|
|
Metadata: plan.metadata,
|
|
Config: config,
|
|
StorageCredentials: storageCredentials,
|
|
}
|
|
writeLoadResult(w, http.StatusOK, result)
|
|
return
|
|
}
|
|
if reqErr := s.registerCreateTable(r.Context(), plan, identityName); reqErr != nil {
|
|
writeError(w, reqErr.status, reqErr.errType, reqErr.message)
|
|
return
|
|
}
|
|
|
|
config, storageCredentials := s.buildFileIOConfig(r, plan.location, func() bool {
|
|
return s.mayUpdateTable(r, bucketName, namespace, req.Name)
|
|
})
|
|
result := LoadTableResult{
|
|
MetadataLocation: plan.metadataLocation,
|
|
Metadata: plan.metadata,
|
|
Config: config,
|
|
StorageCredentials: storageCredentials,
|
|
}
|
|
writeLoadResult(w, http.StatusOK, result)
|
|
}
|
|
|
|
// CreateTable creates and registers a table the way a create request without
|
|
// stage-create does, for a caller inside the cluster rather than an HTTP
|
|
// client. It returns the table's metadata location and metadata.
|
|
func (s *Server) CreateTable(ctx context.Context, bucketName string, namespace []string, req CreateTableRequest, identityName string) (string, table.Metadata, error) {
|
|
if err := validateCreateTableRequest(req); err != nil {
|
|
return "", nil, err
|
|
}
|
|
if req.StageCreate {
|
|
return "", nil, errors.New("stage-create needs a commit to register the table")
|
|
}
|
|
plan, reqErr := s.planCreateTable(ctx, bucketName, namespace, req, identityName)
|
|
if reqErr != nil {
|
|
return "", nil, reqErr
|
|
}
|
|
if reqErr := s.registerCreateTable(ctx, plan, identityName); reqErr != nil {
|
|
return "", nil, reqErr
|
|
}
|
|
return plan.metadataLocation, plan.metadata, nil
|
|
}
|
|
|
|
// createTablePlan is a create the catalog has authorized and built the
|
|
// metadata for, ready to stage or register.
|
|
type createTablePlan struct {
|
|
bucketName string
|
|
bucketARN string
|
|
namespace []string
|
|
tableName string
|
|
tableUUID uuid.UUID
|
|
tablePath string
|
|
location string
|
|
clientLocation string
|
|
metadata table.Metadata
|
|
metadataBytes []byte
|
|
metadataFileName string
|
|
metadataLocation string
|
|
metadataBucket string
|
|
metadataPath string
|
|
}
|
|
|
|
// planCreateTable checks a create of req.Name in namespace and builds the
|
|
// table's first metadata, writing nothing.
|
|
func (s *Server) planCreateTable(ctx context.Context, bucketName string, namespace []string, req CreateTableRequest, identityName string) (*createTablePlan, *icebergRequestError) {
|
|
bucketARN := buildTableBucketARN(bucketName)
|
|
|
|
// Generate UUID for the new table
|
|
tableUUID := uuid.New()
|
|
// 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 := placeNewEntry(bucketName, tablePath)
|
|
clientLocation := strings.TrimSuffix(strings.TrimSpace(req.Location), "/")
|
|
if clientLocation != "" {
|
|
_, clientPath, err := parseS3Location(clientLocation)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "Invalid table location: " + err.Error()}
|
|
}
|
|
if clientPath == "" {
|
|
clientLocation = ""
|
|
} else {
|
|
location = clientLocation
|
|
}
|
|
}
|
|
|
|
// Build proper Iceberg table metadata using iceberg-go types
|
|
metadata, err := newTableMetadata(tableUUID, location, req.Schema, req.partitionSpec(), req.writeOrder(), req.Properties)
|
|
if err != nil {
|
|
glog.V(1).Infof("Iceberg: CreateTable %s metadata error: %v", req.Name, err)
|
|
// Everything the metadata is built from comes from the request, so a
|
|
// spec or order that does not resolve against its schema is the
|
|
// client's error, not a server fault.
|
|
if errors.Is(err, table.ErrInvalidMetadata) || errors.Is(err, table.ErrInvalidSortSourceID) {
|
|
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", err.Error()}
|
|
}
|
|
return nil, managerRequestError(err)
|
|
}
|
|
|
|
// Serialize metadata to JSON
|
|
metadataBytes, err := json.Marshal(metadata)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to serialize metadata: " + err.Error()}
|
|
}
|
|
// Backfill Iceberg spec-required fields that iceberg-go v0.5.0 omits when
|
|
// empty (e.g. current-snapshot-id), so the persisted v*.metadata.json is
|
|
// readable by strict clients (Java/Spark/Trino) that go directly to S3.
|
|
metadataBytes = ensureMetadataSpecCompliance(metadataBytes)
|
|
|
|
tableName := req.Name
|
|
metadataFileName := "v1.metadata.json" // Initial version is always 1
|
|
metadataLocation := fmt.Sprintf("%s/metadata/%s", location, metadataFileName)
|
|
metadataBucket, metadataPath, err := parseS3Location(location)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Invalid table location: " + err.Error()}
|
|
}
|
|
|
|
// location/name are client-supplied; confine the metadata write to the
|
|
// authorized catalog bucket and reject traversal segments so path.Join in
|
|
// saveMetadataFile cannot escape into another bucket.
|
|
if metadataBucket != bucketName {
|
|
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "table location must be within bucket " + bucketName}
|
|
}
|
|
if !isValidTablePath(metadataPath) {
|
|
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", "invalid table location path"}
|
|
}
|
|
|
|
// Authoritative existence check: ask the catalog whether a table is registered
|
|
// at this name. If it is, refuse with 409 as the Iceberg REST spec requires;
|
|
// clients that want create-if-not-exists catch the 409 and load the table.
|
|
// Any leftover objects at the target path from a previous lifecycle of the
|
|
// same name are purged by handleDropTable on the way out — we deliberately do
|
|
// not clean storage here to keep CreateTable free of destructive side
|
|
// effects. See issue #9074.
|
|
existsReq := &s3tables.GetTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
}
|
|
var existsResp s3tables.GetTableResponse
|
|
existsErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(ctx, mgrClient, "GetTable", existsReq, &existsResp, identityName)
|
|
})
|
|
if existsErr == nil {
|
|
return nil, tableAlreadyExists(namespace, tableName)
|
|
}
|
|
if !isNoSuchTableError(existsErr) {
|
|
glog.V(1).Infof("Iceberg: CreateTable existence check failed for %s.%s: %v", flattenNamespacePath(namespace), tableName, existsErr)
|
|
return nil, managerRequestError(existsErr)
|
|
}
|
|
|
|
// Both branches below write into the table bucket, and stage-create never
|
|
// reaches the registration that carries the authorization, so the caller has
|
|
// to pass the CreateTable gate here.
|
|
if authErr := s.authorizeCreateTable(ctx, bucketARN, namespace, tableName, identityName, metadataLocation); authErr != nil {
|
|
return nil, managerRequestError(authErr)
|
|
}
|
|
// Registration confines the location to the table's namespace, but both
|
|
// branches write, and stage-create vends credentials, before it runs.
|
|
if err := s3tables.ValidateMetadataLocation(metadataLocation, bucketName, flattenNamespacePath(namespace)); err != nil {
|
|
return nil, &icebergRequestError{http.StatusBadRequest, "BadRequestException", err.Error()}
|
|
}
|
|
if clientLocation != "" {
|
|
if reqErr := s.checkFreshLocation(ctx, bucketName, namespace, tableName, metadataPath, location, "", true); reqErr != nil {
|
|
return nil, reqErr
|
|
}
|
|
}
|
|
return &createTablePlan{
|
|
bucketName: bucketName,
|
|
bucketARN: bucketARN,
|
|
namespace: namespace,
|
|
tableName: tableName,
|
|
tableUUID: tableUUID,
|
|
tablePath: tablePath,
|
|
location: location,
|
|
clientLocation: clientLocation,
|
|
metadata: metadata,
|
|
metadataBytes: metadataBytes,
|
|
metadataFileName: metadataFileName,
|
|
metadataLocation: metadataLocation,
|
|
metadataBucket: metadataBucket,
|
|
metadataPath: metadataPath,
|
|
}, nil
|
|
}
|
|
|
|
// registerCreateTable writes plan's metadata file and registers the table in
|
|
// the catalog, recording in plan where the file landed.
|
|
func (s *Server) registerCreateTable(ctx context.Context, plan *createTablePlan, identityName string) *icebergRequestError {
|
|
bucketName, namespace, tableName := plan.bucketName, plan.namespace, plan.tableName
|
|
metadataBucket, metadataPath, location := plan.metadataBucket, plan.metadataPath, plan.location
|
|
// The location may already hold a v1.metadata.json: a table created there
|
|
// earlier and since dropped, an unregistered file, or a request racing this
|
|
// one for the same name. Writing it exclusively keeps this request from
|
|
// replacing that file, and from deleting it below if registration fails.
|
|
metadataFileName, metadataLocation, stageToken, err := s.stageOwnedMetadata(ctx, metadataBucket, metadataPath, location, plan.metadataFileName, plan.metadataBytes)
|
|
if err != nil {
|
|
return &icebergRequestError{http.StatusInternalServerError, "InternalServerError", "Failed to save metadata file: " + err.Error()}
|
|
}
|
|
plan.metadataFileName, plan.metadataLocation = metadataFileName, metadataLocation
|
|
if plan.clientLocation != "" {
|
|
if reqErr := s.checkFreshLocation(ctx, bucketName, namespace, tableName, metadataPath, location, "", false); reqErr != nil {
|
|
s.discardStagedMetadata(ctx, metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken)
|
|
return reqErr
|
|
}
|
|
}
|
|
|
|
// Use S3 Tables manager to create table
|
|
createReq := &s3tables.CreateTableRequest{
|
|
TableBucketARN: plan.bucketARN,
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
Format: "ICEBERG",
|
|
Metadata: &s3tables.TableMetadata{
|
|
Iceberg: &s3tables.IcebergMetadata{
|
|
TableUUID: plan.tableUUID.String(),
|
|
},
|
|
FullMetadata: plan.metadataBytes,
|
|
},
|
|
MetadataLocation: metadataLocation,
|
|
MetadataVersion: 1,
|
|
}
|
|
var createResp s3tables.CreateTableResponse
|
|
|
|
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(s3tables.WithCatalogAssignedLocation(ctx), mgrClient, "CreateTable", createReq, &createResp, identityName)
|
|
})
|
|
if err == nil && createResp.MetadataLocation != metadataLocation {
|
|
// Another create registered the name first.
|
|
err = &s3tables.S3TablesError{Type: s3tables.ErrCodeTableAlreadyExists, Message: fmt.Sprintf("table %s already exists", tableName)}
|
|
}
|
|
if err != nil {
|
|
// The file is named by this request alone, so it can go once the
|
|
// catalog refused the registration before a record naming it became
|
|
// visible. After a failure that may have left one (a conflict on a
|
|
// record already published, transport, 5xx) it stays: the record,
|
|
// under this name or one it was renamed to, could point at it, and
|
|
// removing it would leave the table unreadable.
|
|
if registrationRefused(err) {
|
|
s.discardStagedMetadata(ctx, metadataBucket, metadataPath, metadataFileName, metadataLocation, stageToken)
|
|
}
|
|
if isS3TablesAlreadyExists(err) {
|
|
if strings.HasSuffix(metadataPath, plan.tablePath) {
|
|
// The name went to another table before this request wrote a
|
|
// record, so nothing names the directory the server picked.
|
|
if cleanupErr := s.cleanupStaleTableLocation(ctx, metadataBucket, metadataPath, nil); cleanupErr != nil {
|
|
glog.V(1).Infof("Iceberg: CreateTable cleanup %s: %v", metadataPath, cleanupErr)
|
|
}
|
|
}
|
|
return tableAlreadyExists(namespace, tableName)
|
|
}
|
|
glog.V(1).Infof("Iceberg: CreateTable error: %v", err)
|
|
return managerRequestError(err)
|
|
}
|
|
|
|
if markerErr := s.deleteStageCreateMarkers(ctx, 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)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// handleRegisterTable registers an existing metadata.json under a new catalog
|
|
// entry without generating new metadata.
|
|
func (s *Server) handleRegisterTable(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
namespace := parseNamespace(vars["namespace"])
|
|
if len(namespace) == 0 {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace is required")
|
|
return
|
|
}
|
|
|
|
var req RegisterTableRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid request body")
|
|
return
|
|
}
|
|
if req.Name == "" {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", errTableNameRequired.Error())
|
|
return
|
|
}
|
|
if req.MetadataLocation == "" {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "metadata-location is required")
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
bucketARN := buildTableBucketARN(bucketName)
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
// The location is checked without reading anything (in the bucket, no
|
|
// traversal, a file directly in a table's metadata directory), then the
|
|
// caller's right to create the table and the location's owner, and only
|
|
// then is anything read: the file read (and, in a mounted bucket, fetched)
|
|
// on a caller's word would otherwise tell a caller without rights whether a
|
|
// file exists and is metadata.
|
|
if _, err := metadataLocationPath(bucketName, req.MetadataLocation); err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid metadata-location: "+err.Error())
|
|
return
|
|
}
|
|
if authErr := s.authorizeCreateTable(r.Context(), bucketARN, namespace, req.Name, identityName, req.MetadataLocation); authErr != nil {
|
|
writeManagerError(w, authErr)
|
|
return
|
|
}
|
|
|
|
// A table migrated in has its metadata uploaded through the S3 gateway,
|
|
// which stores it in chunks rather than inline; in a remote-mounted bucket
|
|
// it may be held only remotely. metadataAtLocation reads both.
|
|
metadataBytes, err := s.metadataAtLocation(r.Context(), bucketName, req.MetadataLocation)
|
|
if err != nil {
|
|
glog.V(1).Infof("Iceberg: RegisterTable load metadata at %s: %v", req.MetadataLocation, err)
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Cannot read metadata at "+req.MetadataLocation)
|
|
return
|
|
}
|
|
registered, err := table.ParseMetadataBytes(metadataBytes)
|
|
if err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", fmt.Sprintf("Invalid metadata at %s: %v", req.MetadataLocation, err))
|
|
return
|
|
}
|
|
// the metadata describes the table at this location, not another one: a
|
|
// file copied from another table names that table's files
|
|
if want := tableLocationFromMetadataLocation(req.MetadataLocation); strings.TrimSuffix(registered.Location(), "/") != strings.TrimSuffix(want, "/") {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", fmt.Sprintf("the metadata's location %s is not %s", registered.Location(), want))
|
|
return
|
|
}
|
|
|
|
registeredMetadata := &s3tables.TableMetadata{
|
|
Iceberg: &s3tables.IcebergMetadata{TableUUID: registered.TableUUID().String()},
|
|
FullMetadata: metadataBytes,
|
|
}
|
|
registerReq := &s3tables.RegisterTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
Name: req.Name,
|
|
MetadataLocation: req.MetadataLocation,
|
|
Metadata: registeredMetadata,
|
|
}
|
|
// The manager refuses a request larger than s3tables.MaxRequestBodySize.
|
|
// A file too large to travel with the registration is registered by its
|
|
// location and UUID alone; loads and commits read it from that location.
|
|
if body, marshalErr := json.Marshal(registerReq); marshalErr == nil && len(body) > s3tables.MaxRequestBodySize {
|
|
registerReq.Metadata = &s3tables.TableMetadata{Iceberg: registeredMetadata.Iceberg}
|
|
}
|
|
var registerResp s3tables.RegisterTableResponse
|
|
err = s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(r.Context(), mgrClient, "RegisterTable", registerReq, ®isterResp, identityName)
|
|
})
|
|
if err != nil {
|
|
var tableErr *s3tables.S3TablesError
|
|
if errors.As(err, &tableErr) {
|
|
switch tableErr.Type {
|
|
case s3tables.ErrCodeNoSuchNamespace:
|
|
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", fmt.Sprintf("Namespace does not exist: %v", namespace))
|
|
return
|
|
case s3tables.ErrCodeTableAlreadyExists:
|
|
writeError(w, http.StatusConflict, "AlreadyExistsException", fmt.Sprintf("Table already exists: %s", req.Name))
|
|
return
|
|
}
|
|
}
|
|
glog.V(1).Infof("Iceberg: RegisterTable error: %v", err)
|
|
writeManagerError(w, err)
|
|
return
|
|
}
|
|
|
|
getResp := s3tables.GetTableResponse{
|
|
MetadataLocation: req.MetadataLocation,
|
|
Metadata: registeredMetadata,
|
|
}
|
|
result, buildErr := s.buildLoadTableResult(r, getResp, bucketName, namespace, req.Name)
|
|
if buildErr != nil {
|
|
glog.Errorf("Iceberg: RegisterTable %s: %v", req.Name, buildErr)
|
|
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to build table metadata")
|
|
return
|
|
}
|
|
writeLoadResult(w, http.StatusOK, result)
|
|
}
|
|
|
|
// handleLoadTable loads table metadata.
|
|
func (s *Server) handleLoadTable(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
namespace := parseNamespace(vars["namespace"])
|
|
tableName := vars["table"]
|
|
|
|
if len(namespace) == 0 || tableName == "" {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace and table name are required")
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
|
|
// Extract identity from context
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
getResp, err := s.getTable(r.Context(), bucketName, namespace, tableName, identityName)
|
|
if err != nil {
|
|
|
|
if strings.Contains(err.Error(), "not found") {
|
|
writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName))
|
|
return
|
|
}
|
|
glog.V(1).Infof("Iceberg: LoadTable error: %v", err)
|
|
writeManagerError(w, err)
|
|
return
|
|
}
|
|
|
|
result, buildErr := s.buildLoadTableResult(r, getResp, bucketName, namespace, tableName)
|
|
if buildErr == nil {
|
|
// Only LoadTable defines ?snapshots=; a create response always carries
|
|
// the metadata it just wrote.
|
|
result.Metadata, buildErr = applySnapshotsParam(r, result.Metadata)
|
|
}
|
|
if buildErr != nil {
|
|
glog.Errorf("Iceberg: LoadTable %s: %v", tableName, buildErr)
|
|
writeError(w, http.StatusInternalServerError, "InternalServerError", "Failed to build table metadata")
|
|
return
|
|
}
|
|
writeLoadResult(w, http.StatusOK, result)
|
|
}
|
|
|
|
// LoadTable returns the metadata location and current metadata of a table,
|
|
// as a load request does, for a caller inside the cluster.
|
|
func (s *Server) LoadTable(ctx context.Context, bucketName string, namespace []string, tableName, identityName string) (string, table.Metadata, error) {
|
|
getResp, err := s.getTable(ctx, bucketName, namespace, tableName, identityName)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
metadata, _, err := s.loadTableMetadata(ctx, getResp, bucketName, namespace, tableName)
|
|
if err != nil {
|
|
return "", nil, err
|
|
}
|
|
return getResp.MetadataLocation, metadata, nil
|
|
}
|
|
|
|
func (s *Server) getTable(ctx context.Context, bucketName string, namespace []string, tableName, identityName string) (s3tables.GetTableResponse, error) {
|
|
getReq := &s3tables.GetTableRequest{
|
|
TableBucketARN: buildTableBucketARN(bucketName),
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
}
|
|
var getResp s3tables.GetTableResponse
|
|
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(ctx, mgrClient, "GetTable", getReq, &getResp, identityName)
|
|
})
|
|
return getResp, err
|
|
}
|
|
|
|
func (s *Server) buildLoadTableResult(r *http.Request, getResp s3tables.GetTableResponse, bucketName string, namespace []string, tableName string) (LoadTableResult, error) {
|
|
location := tableLocation(getResp, bucketName, namespace, tableName)
|
|
metadata, cached, err := s.loadTableMetadata(r.Context(), getResp, bucketName, namespace, tableName)
|
|
if err != nil {
|
|
return LoadTableResult{}, err
|
|
}
|
|
|
|
catalogOnly := s3tables.IsCatalogOnlyFormat(getResp.Format)
|
|
config, storageCredentials := s.buildFileIOConfig(r, location, func() bool {
|
|
return !catalogOnly && s.mayUpdateTable(r, bucketName, namespace, tableName)
|
|
})
|
|
return LoadTableResult{
|
|
MetadataLocation: getResp.MetadataLocation,
|
|
Metadata: metadata,
|
|
Config: config,
|
|
StorageCredentials: storageCredentials,
|
|
cached: cached,
|
|
}, nil
|
|
}
|
|
|
|
// loadTableMetadata is the current metadata of the table GetTable answered
|
|
// with, parsed once per version.
|
|
func (s *Server) loadTableMetadata(ctx context.Context, getResp s3tables.GetTableResponse, bucketName string, namespace []string, tableName string) (table.Metadata, *cachedMetadata, error) {
|
|
location := tableLocation(getResp, bucketName, namespace, tableName)
|
|
tableUUID := uuid.Nil
|
|
if getResp.Metadata != nil && getResp.Metadata.Iceberg != nil && getResp.Metadata.Iceberg.TableUUID != "" {
|
|
if parsed, err := uuid.Parse(getResp.Metadata.Iceberg.TableUUID); err == nil {
|
|
tableUUID = parsed
|
|
}
|
|
}
|
|
// Use Nil UUID if not found in storage (legacy table)
|
|
// Stability is guaranteed by not generating random UUIDs on read
|
|
|
|
metadataBytes, err := s.currentMetadataBytes(ctx, getResp, bucketName)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("load metadata for %s: %w", tableName, err)
|
|
}
|
|
var metadata table.Metadata
|
|
var cached *cachedMetadata
|
|
if len(metadataBytes) > 0 {
|
|
// metadata that does not parse fails the load: an empty table in its
|
|
// place reads as no rows, and a writer could commit over it
|
|
cached, err = tableMetadataCache.parse(bucketName, getResp.MetadataLocation, metadataBytes)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("read metadata of %s at %s: %w", tableName, getResp.MetadataLocation, err)
|
|
}
|
|
metadata = cached.parsed
|
|
} else {
|
|
// No full metadata, create synthetic
|
|
// TODO: If we had stored schema in IcebergMetadata, we would pass it here
|
|
metadata, err = newTableMetadata(tableUUID, location, nil, nil, nil, nil)
|
|
}
|
|
// A nil metadata would serialize as "metadata":null under HTTP 200, which no
|
|
// Iceberg client can parse. Fail the request instead.
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("build metadata for %s: %w", tableName, err)
|
|
}
|
|
return metadata, cached, nil
|
|
}
|
|
|
|
// applySnapshotsParam honours ?snapshots=refs, which asks for only the
|
|
// snapshots that branches and tags point at. Clients use it to avoid pulling a
|
|
// long snapshot history they will not read. Anything else, including the
|
|
// default, returns the metadata untouched.
|
|
func applySnapshotsParam(r *http.Request, metadata table.Metadata) (table.Metadata, error) {
|
|
if !strings.EqualFold(strings.TrimSpace(r.URL.Query().Get("snapshots")), "refs") {
|
|
return metadata, nil
|
|
}
|
|
if metadata == nil {
|
|
return metadata, nil
|
|
}
|
|
|
|
referenced := make(map[int64]struct{})
|
|
for _, ref := range metadata.Refs() {
|
|
referenced[ref.SnapshotID] = struct{}{}
|
|
}
|
|
if current := metadata.CurrentSnapshot(); current != nil {
|
|
referenced[current.SnapshotID] = struct{}{}
|
|
}
|
|
|
|
var unreferenced []int64
|
|
for _, snapshot := range metadata.Snapshots() {
|
|
if _, keep := referenced[snapshot.SnapshotID]; !keep {
|
|
unreferenced = append(unreferenced, snapshot.SnapshotID)
|
|
}
|
|
}
|
|
if len(unreferenced) == 0 {
|
|
return metadata, nil
|
|
}
|
|
|
|
builder, err := table.MetadataBuilderFromBase(metadata, "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := builder.RemoveSnapshots(unreferenced, false); err != nil {
|
|
return nil, err
|
|
}
|
|
return builder.Build()
|
|
}
|
|
|
|
// buildFileIOConfig returns the FileIO properties to advertise to catalog
|
|
// clients so they can read the table's data files directly from S3 without
|
|
// separately discovering the endpoint. The region defaults to the same
|
|
// value baked into table bucket ARNs so clients like DuckDB that require
|
|
// a region on attach don't need to be told it out-of-band. See issue #9103.
|
|
// It also returns, for a client that asked for credential vending, the
|
|
// credentials scoped to this table.
|
|
func (s *Server) buildFileIOConfig(r *http.Request, location string, canWrite func() bool) (iceberg.Properties, []StorageCredential) {
|
|
config := make(iceberg.Properties)
|
|
if s.s3Endpoint == "" {
|
|
return config, nil
|
|
}
|
|
|
|
vended := iceberg.Properties(nil)
|
|
if wantsVendedCredentials(r) {
|
|
vended = s.vendCredentials(r, location, canWrite)
|
|
// A client asking for vended credentials builds its storage credential
|
|
// out of whatever comes back here and stops using the one it was
|
|
// configured with. With nothing to vend, an endpoint on its own leaves
|
|
// it sending unsigned requests; say nothing instead and let it keep its
|
|
// own credentials.
|
|
if vended == nil {
|
|
return config, nil
|
|
}
|
|
}
|
|
|
|
config["s3.endpoint"] = s.s3Endpoint
|
|
config["s3.path-style-access"] = "true"
|
|
config["s3.region"] = s3tables.DefaultRegion
|
|
if vended == nil {
|
|
return config, nil
|
|
}
|
|
|
|
credentialConfig := make(iceberg.Properties, len(config)+len(vended))
|
|
for key, value := range config {
|
|
credentialConfig[key] = value
|
|
}
|
|
for key, value := range vended {
|
|
config[key] = value
|
|
credentialConfig[key] = value
|
|
}
|
|
return config, []StorageCredential{{Prefix: location, Config: credentialConfig}}
|
|
}
|
|
|
|
// vendCredentials mints credentials limited to this table's prefix. It returns
|
|
// nil when the deployment has no vending configured or the mint failed, which
|
|
// leaves the caller withholding the endpoint so the client keeps its own
|
|
// credentials rather than falling back to unsigned requests.
|
|
func (s *Server) vendCredentials(r *http.Request, location string, canWrite func() bool) iceberg.Properties {
|
|
if s.credentialVendor == nil || location == "" {
|
|
return nil
|
|
}
|
|
|
|
bucket, prefix, err := parseS3Location(location)
|
|
if err != nil {
|
|
glog.V(1).Infof("Iceberg: cannot vend credentials for %s: %v", location, err)
|
|
return nil
|
|
}
|
|
|
|
principal := s3_constants.GetIdentityNameFromContext(r)
|
|
credentials, err := s.credentialVendor.VendTableCredentials(r.Context(), principal, bucket, prefix, canWrite == nil || !canWrite(), requestedCredentialDuration(r))
|
|
if err != nil {
|
|
glog.Warningf("Iceberg: failed to vend credentials for %s: %v", location, err)
|
|
return nil
|
|
}
|
|
if credentials == nil {
|
|
return nil
|
|
}
|
|
|
|
vended := iceberg.Properties{
|
|
"s3.access-key-id": credentials.AccessKeyID,
|
|
"s3.secret-access-key": credentials.SecretAccessKey,
|
|
"s3.session-token": credentials.SessionToken,
|
|
}
|
|
if !credentials.Expiration.IsZero() {
|
|
vended["s3.session-token-expires-at-ms"] = strconv.FormatInt(credentials.Expiration.UnixMilli(), 10)
|
|
}
|
|
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.
|
|
func (s *Server) mayUpdateTable(r *http.Request, bucketName string, namespace []string, tableName string) bool {
|
|
updateReq := &s3tables.UpdateTableRequest{
|
|
TableBucketARN: buildTableBucketARN(bucketName),
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
}
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
return s.tablesManager.AuthorizeUpdateTable(r.Context(), s3tables.NewManagerClient(client), updateReq, identityName)
|
|
})
|
|
if err == nil {
|
|
err = s.tablesManager.CheckVectorNamespaceWrite(r.Context(), s.filerClient, bucketName, namespace)
|
|
}
|
|
if err != nil {
|
|
glog.V(1).Infof("Iceberg: UpdateTable check for %s/%s failed, vending read-only: %v", bucketName, tableName, err)
|
|
}
|
|
return err == nil
|
|
}
|
|
|
|
// mayUpdateView is mayUpdateTable for a view, whose commit path is UpdateView.
|
|
func (s *Server) mayUpdateView(r *http.Request, bucketName string, namespace []string, viewName string) bool {
|
|
updateReq := &s3tables.UpdateViewRequest{
|
|
TableBucketARN: buildTableBucketARN(bucketName),
|
|
Namespace: namespace,
|
|
Name: viewName,
|
|
}
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
return s.tablesManager.AuthorizeUpdateView(r.Context(), s3tables.NewManagerClient(client), updateReq, identityName)
|
|
})
|
|
if err != nil {
|
|
glog.V(1).Infof("Iceberg: UpdateView check for %s/%s failed, vending read-only: %v", bucketName, viewName, err)
|
|
}
|
|
return err == nil
|
|
}
|
|
|
|
// handleTableExists checks if a table exists.
|
|
func (s *Server) handleTableExists(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
namespace := parseNamespace(vars["namespace"])
|
|
tableName := vars["table"]
|
|
|
|
if len(namespace) == 0 || tableName == "" {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
bucketARN := buildTableBucketARN(bucketName)
|
|
|
|
// Extract identity from context
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
getReq := &s3tables.GetTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
}
|
|
var getResp s3tables.GetTableResponse
|
|
|
|
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", getReq, &getResp, identityName)
|
|
})
|
|
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// handleDropTable deletes a table.
|
|
func (s *Server) handleDropTable(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
namespace := parseNamespace(vars["namespace"])
|
|
tableName := vars["table"]
|
|
|
|
if len(namespace) == 0 || tableName == "" {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Namespace and table name are required")
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
bucketARN := buildTableBucketARN(bucketName)
|
|
|
|
// Extract identity from context
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
// Resolve the table's storage location from the catalog before the
|
|
// delete, so we can purge data files afterwards. The catalog is the
|
|
// authoritative owner of this mapping — if the table is not registered,
|
|
// there is nothing to clean up and DeleteTable will return NoSuchTable.
|
|
var storedMetadataLocation, storedVersionToken string
|
|
var storedCreatedAt time.Time
|
|
lookupReq := &s3tables.GetTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
}
|
|
var lookupResp s3tables.GetTableResponse
|
|
lookupErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(r.Context(), mgrClient, "GetTable", lookupReq, &lookupResp, identityName)
|
|
})
|
|
if lookupErr == nil {
|
|
storedMetadataLocation = lookupResp.MetadataLocation
|
|
storedCreatedAt = lookupResp.CreatedAt
|
|
storedVersionToken = lookupResp.VersionToken
|
|
}
|
|
|
|
deleteReq := &s3tables.DeleteTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
Namespace: namespace,
|
|
Name: tableName,
|
|
VersionToken: storedVersionToken,
|
|
}
|
|
|
|
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(r.Context(), mgrClient, "DeleteTable", deleteReq, nil, identityName)
|
|
})
|
|
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "not found") {
|
|
writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", tableName))
|
|
return
|
|
}
|
|
glog.V(1).Infof("Iceberg: DropTable error: %v", err)
|
|
writeManagerError(w, err)
|
|
return
|
|
}
|
|
|
|
// Purge data files that lived under the dropped table's location, so a
|
|
// subsequent CREATE TABLE at the same name (issue #9074) does not trip
|
|
// Trino's "non-empty location" pre-check. We only purge when the catalog
|
|
// told us a location: if GetTable above failed, there is no mapping to
|
|
// trust and we leave storage alone.
|
|
if storedMetadataLocation != "" {
|
|
if tableLoc := tableLocationFromMetadataLocation(storedMetadataLocation); tableLoc != "" {
|
|
if dataBucket, dataPath, parseErr := parseS3Location(tableLoc); parseErr == nil {
|
|
var holdsFiles func(filer_pb.SeaweedFilerClient, string) (bool, error)
|
|
if !storedCreatedAt.IsZero() {
|
|
holdsFiles = func(client filer_pb.SeaweedFilerClient, dir string) (bool, error) {
|
|
return s3tables.DirHoldsFiles(r.Context(), client, dir, storedCreatedAt)
|
|
}
|
|
}
|
|
if cleanupErr := s.cleanupStaleTableLocation(r.Context(), dataBucket, dataPath, holdsFiles); cleanupErr != nil {
|
|
glog.V(1).Infof("Iceberg: failed to purge dropped table location s3://%s/%s: %v", dataBucket, dataPath, cleanupErr)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// handleRenameTable moves a table's catalog pointer to a new namespace/name.
|
|
func (s *Server) handleRenameTable(w http.ResponseWriter, r *http.Request) {
|
|
var req RenameTableRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "Invalid request body")
|
|
return
|
|
}
|
|
|
|
source := parseNamespace(encodeNamespace(req.Source.Namespace))
|
|
dest := parseNamespace(encodeNamespace(req.Destination.Namespace))
|
|
if len(source) == 0 || req.Source.Name == "" || len(dest) == 0 || req.Destination.Name == "" {
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", "source and destination namespace and name are required")
|
|
return
|
|
}
|
|
|
|
bucketName := getBucketFromPrefix(r)
|
|
bucketARN := buildTableBucketARN(bucketName)
|
|
identityName := s3_constants.GetIdentityNameFromContext(r)
|
|
|
|
renameReq := &s3tables.RenameTableRequest{
|
|
TableBucketARN: bucketARN,
|
|
SourceNamespace: source,
|
|
SourceName: req.Source.Name,
|
|
DestNamespace: dest,
|
|
DestName: req.Destination.Name,
|
|
}
|
|
|
|
err := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(r.Context(), mgrClient, "RenameTable", renameReq, nil, identityName)
|
|
})
|
|
|
|
if err != nil {
|
|
var tableErr *s3tables.S3TablesError
|
|
if errors.As(err, &tableErr) {
|
|
switch tableErr.Type {
|
|
case s3tables.ErrCodeNoSuchTable:
|
|
writeError(w, http.StatusNotFound, "NoSuchTableException", fmt.Sprintf("Table does not exist: %s", req.Source.Name))
|
|
return
|
|
case s3tables.ErrCodeNoSuchNamespace:
|
|
writeError(w, http.StatusNotFound, "NoSuchNamespaceException", fmt.Sprintf("Namespace does not exist: %v", dest))
|
|
return
|
|
case s3tables.ErrCodeTableAlreadyExists:
|
|
writeError(w, http.StatusConflict, "AlreadyExistsException", fmt.Sprintf("Table already exists: %s", req.Destination.Name))
|
|
return
|
|
case s3tables.ErrCodeInvalidRequest:
|
|
writeError(w, http.StatusBadRequest, "BadRequestException", tableErr.Message)
|
|
return
|
|
}
|
|
}
|
|
glog.V(1).Infof("Iceberg: RenameTable error: %v", err)
|
|
writeManagerError(w, err)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// tableAlreadyExists answers a create for a name that holds a table with the
|
|
// 409 the Iceberg REST spec defines for it.
|
|
func tableAlreadyExists(namespace []string, tableName string) *icebergRequestError {
|
|
return &icebergRequestError{http.StatusConflict, "AlreadyExistsException", fmt.Sprintf("Table already exists: %s.%s", strings.Join(namespace, "."), tableName)}
|
|
}
|
|
|
|
// isNoSuchTableError reports whether an error from the S3 Tables manager
|
|
// indicates the target table is not registered in the catalog.
|
|
func isNoSuchTableError(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
var tableErr *s3tables.S3TablesError
|
|
if errors.As(err, &tableErr) {
|
|
return tableErr.Type == s3tables.ErrCodeNoSuchTable || tableErr.Type == s3tables.ErrCodeNoSuchNamespace
|
|
}
|
|
msg := strings.ToLower(err.Error())
|
|
return strings.Contains(msg, "not found") || strings.Contains(msg, "no such table")
|
|
}
|
|
|
|
// cleanupStaleTableLocation purges any existing filer entry at the target
|
|
// table path inside the regular S3 bucket so that engines which verify an
|
|
// empty location (e.g. Trino CTAS) can proceed after a DROP. Callers must
|
|
// have confirmed via the catalog that no table is registered at this name —
|
|
// live tables must never be touched by this helper. Missing paths are not
|
|
// an error. A location for which a non-nil holdsFiles reports files the
|
|
// dropped entry did not write is left alone.
|
|
//
|
|
// The tablePath is validated to contain only safe, relative segments before
|
|
// being joined with the bucket prefix, so a maliciously crafted location
|
|
// (e.g. containing "..") cannot escape the bucket subtree and delete data
|
|
// outside of it.
|
|
func (s *Server) cleanupStaleTableLocation(ctx context.Context, bucketName, tablePath string, holdsFiles func(filer_pb.SeaweedFilerClient, string) (bool, error)) error {
|
|
tablePath = strings.Trim(tablePath, "/")
|
|
if bucketName == "" || tablePath == "" {
|
|
return nil
|
|
}
|
|
// Reject absolute paths and any traversal segments. path.Clean would
|
|
// silently collapse "foo/../bar" into "bar", masking an attempted
|
|
// escape, so we check each raw segment explicitly.
|
|
for _, segment := range strings.Split(tablePath, "/") {
|
|
if segment == "" || segment == "." || segment == ".." || strings.ContainsAny(segment, `\`) {
|
|
return fmt.Errorf("cleanupStaleTableLocation: refusing unsafe table path %q", tablePath)
|
|
}
|
|
}
|
|
parentDir := path.Join(s3_constants.DefaultBucketsPath, bucketName, path.Dir(tablePath))
|
|
name := path.Base(tablePath)
|
|
if name == "" || name == "." || name == ".." || name == "/" {
|
|
return fmt.Errorf("cleanupStaleTableLocation: refusing unsafe table path %q", tablePath)
|
|
}
|
|
return s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
checkUnclaimed := func() error {
|
|
roots, err := s3tables.CatalogRecordRoots(ctx, client, bucketName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if s3tables.RootClaimed(roots, "", path.Join(parentDir, name)) {
|
|
return s3tables.ErrLocationInUse
|
|
}
|
|
return nil
|
|
}
|
|
if err := checkUnclaimed(); err != nil {
|
|
return err
|
|
}
|
|
if holdsFiles != nil {
|
|
holds, err := holdsFiles(client, path.Join(parentDir, name))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if holds {
|
|
return fmt.Errorf("keeping %s: it holds files the dropped entry did not write", path.Join(parentDir, name))
|
|
}
|
|
// The scan takes time in proportion to the tree; a record that
|
|
// claimed the location meanwhile keeps it.
|
|
if err := checkUnclaimed(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
err := filer_pb.DoRemove(ctx, client, parentDir, name, true, true, true, false, nil)
|
|
if err == nil || errors.Is(err, filer_pb.ErrNotFound) {
|
|
return nil
|
|
}
|
|
return err
|
|
})
|
|
}
|
|
|
|
// newTableMetadata creates a new table.Metadata object with the given parameters.
|
|
// Uses iceberg-go's MetadataBuilder pattern for proper spec compliance.
|
|
func newTableMetadata(
|
|
tableUUID uuid.UUID,
|
|
location string,
|
|
schema *iceberg.Schema,
|
|
partitionSpec *iceberg.PartitionSpec,
|
|
sortOrder *table.SortOrder,
|
|
props iceberg.Properties,
|
|
) (table.Metadata, error) {
|
|
// Add schema - use provided or create empty schema
|
|
var s *iceberg.Schema
|
|
if schema != nil {
|
|
s = schema
|
|
} else {
|
|
s = iceberg.NewSchema(0)
|
|
}
|
|
|
|
// Add partition spec
|
|
var pSpec *iceberg.PartitionSpec
|
|
if partitionSpec != nil {
|
|
pSpec = partitionSpec
|
|
} else {
|
|
unpartitioned := iceberg.NewPartitionSpecID(0)
|
|
pSpec = &unpartitioned
|
|
}
|
|
|
|
// Add sort order
|
|
var so table.SortOrder
|
|
if sortOrder != nil {
|
|
so = *sortOrder
|
|
} else {
|
|
so = table.UnsortedSortOrder
|
|
}
|
|
|
|
// Create properties map if nil
|
|
if props == nil {
|
|
props = make(iceberg.Properties)
|
|
}
|
|
|
|
// Create metadata directly using the constructor which ensures spec compliance for V2
|
|
metadata, err := table.NewMetadataWithUUID(s, pSpec, so, location, props, tableUUID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// The constructor reassigns field ids, so the default name mapping must be
|
|
// derived from the final schema rather than the request's.
|
|
raw, err := json.Marshal(metadata)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if patched := refreshDefaultNameMapping(raw, metadata); !bytes.Equal(patched, raw) {
|
|
if withMapping, err := table.ParseMetadataBytes(patched); err == nil {
|
|
return withMapping, nil
|
|
}
|
|
}
|
|
return metadata, nil
|
|
}
|