mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-07-24 09:02:59 +00:00
* fix(s3tables/iceberg): make metadata spec-compliant and accept real-world manifest names
Two related issues prevent SeaweedFS S3 Tables from interoperating with
strict Iceberg clients (Java/Spark/Flink/Trino):
1. iceberg-go v0.5.0 serializes empty TableMetadata state by dropping
keys via `omitempty` on optional pointer/slice fields. The Iceberg
table spec, however, requires `current-snapshot-id`, `snapshots`,
`snapshot-log`, `metadata-log`, and `refs` to be present even when
empty (`current-snapshot-id` must be -1 for a table with no
snapshots). Java's TableMetadataParser uses JsonUtil.getLong on
`current-snapshot-id` and throws "Cannot parse missing long
current-snapshot-id" against responses produced by this server.
2. The Iceberg layout validator only accepts manifest filenames that
match Iceberg's internal naming (`{uuid}-m{n}.avro`,
`snap-{n}-{n}-{uuid}.avro`). Real writers — notably Flink's sink —
emit manifests like
`{flink-job-id}-{checkpoint}-{operator-id}-{n}.avro`, which the
validator rejects with 403, breaking INSERT commits.
Fixes:
* Add ensureMetadataSpecCompliance helper that backfills the five
spec-required empty-state fields when iceberg-go omits them or emits
explicit JSON null. Apply it on every code path that writes
v*.metadata.json to S3 or returns metadata to clients
(handlers_table create-table, handlers_commit, commit_helpers
create-on-commit, plus MarshalJSON on LoadTableResult and
CommitTableResponse). Real values from non-empty tables are never
overwritten.
* Add catch-all regex entries to metadataFilePatterns accepting any
*.avro / *.metadata.json filename composed of [A-Za-z0-9._-]. The
Iceberg spec does not mandate filename format; the strict patterns
remain for documentation. Metadata-directory subdirectory rejection
and the data-file path validation are unchanged.
No upstream dependencies are forked: iceberg-go stays at v0.5.0 and
go.mod is untouched. The compliance layer can be removed once upstream
emits spec-compliant output.
Tests (all pass under `go test -race`):
- metadata_compliance_test.go: 5 cases covering missing fields,
preserved real values, explicit null, invalid JSON, empty input.
- iceberg_layout_test.go: 3 groups (16 subtests) covering real-world
manifest names from Flink/Spark/Iceberg, security boundary
(subdirectories, bad extensions), and data-file regression.
* fix(s3tables/iceberg): preserve metadata key order and keep config field stable
Two small follow-ups on the spec-compliance fix:
* ensureMetadataSpecCompliance now splices missing keys in at the byte
level just before the closing brace, so iceberg-go's struct-declared
key order survives the backfill. The previous unmarshal/remarshal
through map[string]json.RawMessage silently alphabetized every key in
the document, which is spec-legal but breaks byte-equality fixtures
and any downstream hashing of the persisted metadata. The slower
remarshal path is kept for the rare explicit-null replacement case.
* LoadTableResult.MarshalJSON now serializes Config without omitempty,
matching the struct field tag. The custom marshaler had silently
flipped the tag to ,omitempty, which made the "config" key disappear
from the response whenever s3Endpoint was unset (since
buildFileIOConfig returned an empty but non-nil Properties map).
Tests:
- PreservesOriginalKeyOrder pins the byte-level output against
iceberg-go's emitted shape; would have caught the alphabetization
regression.
- EmptyObjectBackfilled covers the {} -> sentinels-only case (no
leading comma).
- AllPresentReturnsSameBytes confirms the no-op path returns input
bytes unchanged, with whitespace intact.
- iceberg_layout_test pins the catch-all $ anchor: metadata/file.avro.txt
must still be rejected.
* fix(s3tables/iceberg): guard ensureMetadataSpecCompliance against top-level null
json.Unmarshal of a JSON `null` literal succeeds but leaves the map nil.
The current byte-append path no-ops gracefully on this input, but the
slow remarshal path would panic with "assignment to entry in nil map"
if the input ever combined `null` with the explicit-null detection. Add
an explicit nil-map short-circuit so the safety property is obvious
from the source, and a test that pins the contract.
* test(s3tables/iceberg): assert full byte equality in AllPresentReturnsSameBytes
The prefix check only caught a missing "{\n " opener, so the test
would have passed even if the function silently reordered keys or
collapsed whitespace later in the document. Switch to a full string
comparison so any future regression in the no-op path is loud.
---------
Co-authored-by: Chris Lu <chris.lu@gmail.com>
215 lines
6.8 KiB
Go
215 lines
6.8 KiB
Go
package iceberg
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/apache/iceberg-go/table"
|
|
"github.com/google/uuid"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3tables"
|
|
)
|
|
|
|
const requirementAssertCreate = "assert-create"
|
|
|
|
type icebergRequestError struct {
|
|
status int
|
|
errType string
|
|
message string
|
|
}
|
|
|
|
type createOnCommitInput struct {
|
|
bucketARN string
|
|
markerBucket string
|
|
namespace []string
|
|
tableName string
|
|
identityName string
|
|
location string
|
|
tableUUID uuid.UUID
|
|
baseMetadata table.Metadata
|
|
baseMetadataLoc string
|
|
baseMetadataVer int
|
|
updates table.Updates
|
|
statisticsUpdates []statisticsUpdate
|
|
}
|
|
|
|
func isS3TablesConflict(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if errors.Is(err, s3tables.ErrVersionTokenMismatch) {
|
|
return true
|
|
}
|
|
var tableErr *s3tables.S3TablesError
|
|
return errors.As(err, &tableErr) && tableErr.Type == s3tables.ErrCodeConflict
|
|
}
|
|
|
|
func isS3TablesNotFound(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if strings.Contains(strings.ToLower(err.Error()), "not found") {
|
|
return true
|
|
}
|
|
var tableErr *s3tables.S3TablesError
|
|
return errors.As(err, &tableErr) &&
|
|
(tableErr.Type == s3tables.ErrCodeNoSuchTable || tableErr.Type == s3tables.ErrCodeNoSuchNamespace || strings.Contains(strings.ToLower(tableErr.Message), "not found"))
|
|
}
|
|
|
|
func hasAssertCreateRequirement(requirements table.Requirements) bool {
|
|
for _, requirement := range requirements {
|
|
if requirement.GetType() == requirementAssertCreate {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func isS3TablesAlreadyExists(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
if strings.Contains(strings.ToLower(err.Error()), "already exists") {
|
|
return true
|
|
}
|
|
var tableErr *s3tables.S3TablesError
|
|
return errors.As(err, &tableErr) &&
|
|
(tableErr.Type == s3tables.ErrCodeTableAlreadyExists || tableErr.Type == s3tables.ErrCodeNamespaceAlreadyExists || strings.Contains(strings.ToLower(tableErr.Message), "already exists"))
|
|
}
|
|
|
|
func (s *Server) finalizeCreateOnCommit(ctx context.Context, input createOnCommitInput) (*CommitTableResponse, *icebergRequestError) {
|
|
builder, err := table.MetadataBuilderFromBase(input.baseMetadata, input.baseMetadataLoc)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusInternalServerError,
|
|
errType: "InternalServerError",
|
|
message: "Failed to create metadata builder: " + err.Error(),
|
|
}
|
|
}
|
|
for _, update := range input.updates {
|
|
if err := update.Apply(builder); err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusBadRequest,
|
|
errType: "BadRequestException",
|
|
message: "Failed to apply update: " + err.Error(),
|
|
}
|
|
}
|
|
}
|
|
|
|
newMetadata, err := builder.Build()
|
|
if err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusBadRequest,
|
|
errType: "BadRequestException",
|
|
message: "Failed to build new metadata: " + err.Error(),
|
|
}
|
|
}
|
|
|
|
metadataVersion := input.baseMetadataVer + 1
|
|
if metadataVersion <= 0 {
|
|
metadataVersion = 1
|
|
}
|
|
metadataFileName := fmt.Sprintf("v%d.metadata.json", metadataVersion)
|
|
newMetadataLocation := fmt.Sprintf("%s/metadata/%s", strings.TrimSuffix(input.location, "/"), metadataFileName)
|
|
|
|
metadataBytes, err := json.Marshal(newMetadata)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusInternalServerError,
|
|
errType: "InternalServerError",
|
|
message: "Failed to serialize metadata: " + err.Error(),
|
|
}
|
|
}
|
|
metadataBytes, err = applyStatisticsUpdates(metadataBytes, input.statisticsUpdates)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusBadRequest,
|
|
errType: "BadRequestException",
|
|
message: "Failed to apply statistics updates: " + err.Error(),
|
|
}
|
|
}
|
|
// Same spec-compliance fixup we apply on create-table; ensures
|
|
// v{N}.metadata.json files written through this create-on-commit path are
|
|
// also readable by strict Iceberg clients reading directly from S3.
|
|
metadataBytes = ensureMetadataSpecCompliance(metadataBytes)
|
|
newMetadata, err = table.ParseMetadataBytes(metadataBytes)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusInternalServerError,
|
|
errType: "InternalServerError",
|
|
message: "Failed to parse committed metadata: " + err.Error(),
|
|
}
|
|
}
|
|
|
|
metadataBucket, metadataPath, err := parseS3Location(input.location)
|
|
if err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusInternalServerError,
|
|
errType: "InternalServerError",
|
|
message: "Invalid table location: " + err.Error(),
|
|
}
|
|
}
|
|
if err := s.saveMetadataFile(ctx, metadataBucket, metadataPath, metadataFileName, metadataBytes); err != nil {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusInternalServerError,
|
|
errType: "InternalServerError",
|
|
message: "Failed to save metadata file: " + err.Error(),
|
|
}
|
|
}
|
|
|
|
createReq := &s3tables.CreateTableRequest{
|
|
TableBucketARN: input.bucketARN,
|
|
Namespace: input.namespace,
|
|
Name: input.tableName,
|
|
Format: "ICEBERG",
|
|
Metadata: &s3tables.TableMetadata{
|
|
Iceberg: &s3tables.IcebergMetadata{
|
|
TableUUID: input.tableUUID.String(),
|
|
},
|
|
FullMetadata: metadataBytes,
|
|
},
|
|
MetadataVersion: metadataVersion,
|
|
MetadataLocation: newMetadataLocation,
|
|
}
|
|
createErr := s.filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
|
|
mgrClient := s3tables.NewManagerClient(client)
|
|
return s.tablesManager.Execute(ctx, mgrClient, "CreateTable", createReq, nil, input.identityName)
|
|
})
|
|
if createErr != nil {
|
|
if cleanupErr := s.deleteMetadataFile(ctx, metadataBucket, metadataPath, metadataFileName); cleanupErr != nil {
|
|
glog.V(1).Infof("Iceberg: failed to cleanup metadata file %s after create-on-commit failure: %v", newMetadataLocation, cleanupErr)
|
|
}
|
|
if isS3TablesConflict(createErr) || isS3TablesAlreadyExists(createErr) {
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusConflict,
|
|
errType: "CommitFailedException",
|
|
message: "Table was created concurrently",
|
|
}
|
|
}
|
|
glog.Errorf("Iceberg: CommitTable CreateTable error: %v", createErr)
|
|
return nil, &icebergRequestError{
|
|
status: http.StatusInternalServerError,
|
|
errType: "InternalServerError",
|
|
message: "Failed to commit table creation: " + createErr.Error(),
|
|
}
|
|
}
|
|
|
|
markerBucket := input.markerBucket
|
|
if markerBucket == "" {
|
|
markerBucket = metadataBucket
|
|
}
|
|
if markerErr := s.deleteStageCreateMarkers(ctx, markerBucket, input.namespace, input.tableName); 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)
|
|
}
|
|
|
|
return &CommitTableResponse{
|
|
MetadataLocation: newMetadataLocation,
|
|
Metadata: newMetadata,
|
|
}, nil
|
|
}
|