* Add Trino blog operations test * Update test/s3tables/catalog_trino/trino_blog_operations_test.go Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> * feat: add table bucket path helpers and filer operations - Add table object root and table location mapping directories - Implement ensureDirectory, upsertFile, deleteEntryIfExists helpers - Support table location bucket mapping for S3 access * feat: manage table bucket object roots on creation/deletion - Create .objects directory for table buckets on creation - Clean up table object bucket paths on deletion - Enable S3 operations on table bucket object roots * feat: add table location mapping for Iceberg REST - Track table location bucket mappings when tables are created/updated/deleted - Enable location-based routing for S3 operations on table data * feat: route S3 operations to table bucket object roots - Route table-s3 bucket names to mapped table paths - Route table buckets to object root directories - Support table location bucket mapping lookup * feat: emit table-s3 locations from Iceberg REST - Generate unique table-s3 bucket names with UUID suffix - Store table metadata under table bucket paths - Return table-s3 locations for Trino compatibility * fix: handle missing directories in S3 list operations - Propagate ErrNotFound from ListEntries for non-existent directories - Treat missing directories as empty results for list operations - Fixes Trino non-empty location checks on table creation * test: improve Trino CSV parsing for single-value results - Sanitize Trino output to skip jline warnings - Handle single-value CSV results without header rows - Strip quotes from numeric values in tests * refactor: use bucket path helpers throughout S3 API - Replace direct bucket path operations with helper functions - Leverage centralized table bucket routing logic - Improve maintainability with consistent path resolution * fix: add table bucket cache and improve filer error handling - Cache table bucket lookups to reduce filer overhead on repeated checks - Use filer_pb.CreateEntry and filer_pb.UpdateEntry helpers to check resp.Error - Fix delete order in handler_bucket_get_list_delete: delete table object before directory - Make location mapping errors best-effort: log and continue, don't fail API - Update table location mappings to delete stale prior bucket mappings on update - Add 1-second sleep before timestamp time travel query to ensure timestamps are in past - Fix CSV parsing: examine all lines, not skip first; handle single-value rows * fix: properly handle stale metadata location mapping cleanup - Capture oldMetadataLocation before mutation in handleUpdateTable - Update updateTableLocationMapping to accept both old and new locations - Use passed-in oldMetadataLocation to detect location changes - Delete stale mapping only when location actually changes - Pass empty string for oldLocation in handleCreateTable (new tables have no prior mapping) - Improve logging to show old -> new location transitions * refactor: cleanup imports and cache design - Remove unused 'sync' import from bucket_paths.go - Use filer_pb.UpdateEntry helper in setExtendedAttribute and deleteExtendedAttribute for consistent error handling - Add dedicated tableBucketCache map[string]bool to BucketRegistry instead of mixing concerns with metadataCache - Improve cache separation: table buckets cache is now separate from bucket metadata cache * fix: improve cache invalidation and add transient error handling Cache invalidation (critical fix): - Add tableLocationCache to BucketRegistry for location mapping lookups - Clear tableBucketCache and tableLocationCache in RemoveBucketMetadata - Prevents stale cache entries when buckets are deleted/recreated Transient error handling: - Only cache table bucket lookups when conclusive (found or ErrNotFound) - Skip caching on transient errors (network, permission, etc) - Prevents marking real table buckets as non-table due to transient failures Performance optimization: - Cache tableLocationDir results to avoid repeated filer RPCs on hot paths - tableLocationDir now checks cache before making expensive filer lookups - Cache stores empty string for 'not found' to avoid redundant lookups Code clarity: - Add comment to deleteDirectory explaining DeleteEntry response lacks Error field * go fmt * fix: mirror transient error handling in tableLocationDir and optimize bucketDir Transient error handling: - tableLocationDir now only caches definitive results - Mirrors isTableBucket behavior to prevent treating transient errors as permanent misses - Improves reliability on flaky systems or during recovery Performance optimization: - bucketDir avoids redundant isTableBucket call via bucketRoot - Directly use s3a.option.BucketsPath for regular buckets - Saves one cache lookup for every non-table bucket operation * fix: revert bucketDir optimization to preserve bucketRoot logic The optimization to directly use BucketsPath bypassed bucketRoot's logic and caused issues with S3 list operations on delimiter+prefix cases. Revert to using path.Join(s3a.bucketRoot(bucket), bucket) which properly handles all bucket types and ensures consistent path resolution across the codebase. The slight performance cost of an extra cache lookup is worth the correctness and consistency benefits. * feat: move table buckets under /buckets Add a table-bucket marker attribute, reuse bucket metadata cache for table bucket detection, and update list/validation/UI/test paths to treat table buckets as /buckets entries. * Fix S3 Tables code review issues - handler_bucket_create.go: Fix bucket existence check to properly validate entryResp.Entry before setting s3BucketExists flag (nil Entry should not indicate existing bucket) - bucket_paths.go: Add clarifying comment to bucketRoot() explaining unified buckets root path for all bucket types - file_browser_data.go: Optimize by extracting table bucket check early to avoid redundant WithFilerClient call * Fix list prefix delimiter handling * Handle list errors conservatively * Fix Trino FOR TIMESTAMP query - use past timestamp Iceberg requires the timestamp to be strictly in the past. Use current_timestamp - interval '1' second instead of current_timestamp. --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
177 lines
6.9 KiB
Go
177 lines
6.9 KiB
Go
package s3api
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
|
weed_server "github.com/seaweedfs/seaweedfs/weed/server"
|
|
)
|
|
|
|
// executeUnifiedCopyStrategy executes the appropriate copy strategy based on encryption state
|
|
// Returns chunks and destination metadata that should be applied to the destination entry
|
|
func (s3a *S3ApiServer) executeUnifiedCopyStrategy(entry *filer_pb.Entry, r *http.Request, srcBucket, dstBucket, srcObject, dstObject string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
|
// Detect encryption state (using entry-aware detection for multipart objects)
|
|
srcPath := fmt.Sprintf("%s/%s", s3a.bucketDir(srcBucket), srcObject)
|
|
dstPath := fmt.Sprintf("%s/%s", s3a.bucketDir(dstBucket), dstObject)
|
|
state := DetectEncryptionStateWithEntry(entry, r, srcPath, dstPath)
|
|
|
|
// Debug logging for encryption state
|
|
|
|
// Apply bucket default encryption if no explicit encryption specified
|
|
s3a.applyCopyBucketDefaultEncryption(state, dstBucket)
|
|
|
|
// Determine copy strategy
|
|
strategy, err := DetermineUnifiedCopyStrategy(state, entry.Extended, r)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
glog.V(2).Infof("Unified copy strategy for %s → %s: %v", srcPath, dstPath, strategy)
|
|
|
|
// Calculate optimized sizes for the strategy
|
|
sizeCalc := CalculateOptimizedSizes(entry, r, strategy)
|
|
glog.V(2).Infof("Size calculation: src=%d, target=%d, actual=%d, overhead=%d, preallocate=%v",
|
|
sizeCalc.SourceSize, sizeCalc.TargetSize, sizeCalc.ActualContentSize,
|
|
sizeCalc.EncryptionOverhead, sizeCalc.CanPreallocate)
|
|
|
|
// Execute strategy
|
|
switch strategy {
|
|
case CopyStrategyDirect:
|
|
chunks, err := s3a.copyChunks(entry, dstPath)
|
|
return chunks, nil, err
|
|
|
|
case CopyStrategyKeyRotation:
|
|
return s3a.executeKeyRotation(entry, r, state)
|
|
|
|
case CopyStrategyEncrypt:
|
|
return s3a.executeEncryptCopy(entry, r, state, dstBucket, dstPath)
|
|
|
|
case CopyStrategyDecrypt:
|
|
return s3a.executeDecryptCopy(entry, r, state, dstPath)
|
|
|
|
case CopyStrategyReencrypt:
|
|
return s3a.executeReencryptCopy(entry, r, state, dstBucket, dstPath)
|
|
|
|
default:
|
|
return nil, nil, fmt.Errorf("unknown unified copy strategy: %v", strategy)
|
|
}
|
|
}
|
|
|
|
// mapCopyErrorToS3Error maps various copy errors to appropriate S3 error codes
|
|
func (s3a *S3ApiServer) mapCopyErrorToS3Error(err error) s3err.ErrorCode {
|
|
if err == nil {
|
|
return s3err.ErrNone
|
|
}
|
|
|
|
// Check for read-only errors (quota enforcement)
|
|
// Uses errors.Is() to properly detect wrapped errors
|
|
if errors.Is(err, weed_server.ErrReadOnly) {
|
|
// Bucket is read-only due to quota enforcement or other configuration
|
|
// Return 403 Forbidden per S3 semantics (similar to MinIO's quota enforcement)
|
|
return s3err.ErrAccessDenied
|
|
}
|
|
|
|
// Check for KMS errors first
|
|
if kmsErr := MapKMSErrorToS3Error(err); kmsErr != s3err.ErrInvalidRequest {
|
|
return kmsErr
|
|
}
|
|
|
|
// Check for SSE-C errors
|
|
if ssecErr := MapSSECErrorToS3Error(err); ssecErr != s3err.ErrInvalidRequest {
|
|
return ssecErr
|
|
}
|
|
|
|
// Default to internal error for unknown errors
|
|
return s3err.ErrInternalError
|
|
}
|
|
|
|
// executeKeyRotation handles key rotation for same-object copies
|
|
func (s3a *S3ApiServer) executeKeyRotation(entry *filer_pb.Entry, r *http.Request, state *EncryptionState) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
|
// For key rotation, we only need to update metadata, not re-copy chunks
|
|
// This is a significant optimization for same-object key changes
|
|
|
|
if state.SrcSSEC && state.DstSSEC {
|
|
// SSE-C key rotation - need to handle new key/IV, use reencrypt logic
|
|
return s3a.executeReencryptCopy(entry, r, state, "", "")
|
|
}
|
|
|
|
if state.SrcSSEKMS && state.DstSSEKMS {
|
|
// SSE-KMS key rotation - return existing chunks, metadata will be updated by caller
|
|
return entry.GetChunks(), nil, nil
|
|
}
|
|
|
|
// Fallback to reencrypt if we can't do metadata-only rotation
|
|
return s3a.executeReencryptCopy(entry, r, state, "", "")
|
|
}
|
|
|
|
// executeEncryptCopy handles plain → encrypted copies
|
|
func (s3a *S3ApiServer) executeEncryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
|
if state.DstSSEC {
|
|
// Use existing SSE-C copy logic
|
|
return s3a.copyChunksWithSSEC(entry, r)
|
|
}
|
|
|
|
if state.DstSSEKMS {
|
|
// Use existing SSE-KMS copy logic - metadata is now generated internally
|
|
chunks, dstMetadata, err := s3a.copyChunksWithSSEKMS(entry, r, dstBucket, dstPath)
|
|
return chunks, dstMetadata, err
|
|
}
|
|
|
|
if state.DstSSES3 {
|
|
// Use chunk-by-chunk copy for SSE-S3 encryption (consistent with SSE-C and SSE-KMS)
|
|
glog.V(2).Infof("Plain→SSE-S3 copy: using unified multipart encrypt copy")
|
|
return s3a.copyMultipartCrossEncryption(entry, r, state, dstBucket, dstPath)
|
|
}
|
|
|
|
return nil, nil, fmt.Errorf("unknown target encryption type")
|
|
}
|
|
|
|
// executeDecryptCopy handles encrypted → plain copies
|
|
func (s3a *S3ApiServer) executeDecryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
|
// Use unified multipart-aware decrypt copy for all encryption types (consistent chunk-by-chunk)
|
|
if state.SrcSSEC || state.SrcSSEKMS || state.SrcSSES3 {
|
|
glog.V(2).Infof("Encrypted→Plain copy: using unified multipart decrypt copy")
|
|
return s3a.copyMultipartCrossEncryption(entry, r, state, "", dstPath)
|
|
}
|
|
|
|
return nil, nil, fmt.Errorf("unknown source encryption type")
|
|
}
|
|
|
|
// executeReencryptCopy handles encrypted → encrypted copies with different keys/methods
|
|
func (s3a *S3ApiServer) executeReencryptCopy(entry *filer_pb.Entry, r *http.Request, state *EncryptionState, dstBucket, dstPath string) ([]*filer_pb.FileChunk, map[string][]byte, error) {
|
|
// Use chunk-by-chunk approach for all cross-encryption scenarios (consistent behavior)
|
|
if state.SrcSSEC && state.DstSSEC {
|
|
return s3a.copyChunksWithSSEC(entry, r)
|
|
}
|
|
|
|
if state.SrcSSEKMS && state.DstSSEKMS {
|
|
// Use existing SSE-KMS copy logic - metadata is now generated internally
|
|
chunks, dstMetadata, err := s3a.copyChunksWithSSEKMS(entry, r, dstBucket, dstPath)
|
|
return chunks, dstMetadata, err
|
|
}
|
|
|
|
// All other cross-encryption scenarios use unified multipart copy
|
|
// This includes: SSE-C↔SSE-KMS, SSE-C↔SSE-S3, SSE-KMS↔SSE-S3, SSE-S3↔SSE-S3
|
|
glog.V(2).Infof("Cross-encryption copy: using unified multipart copy")
|
|
return s3a.copyMultipartCrossEncryption(entry, r, state, dstBucket, dstPath)
|
|
}
|
|
|
|
// applyCopyBucketDefaultEncryption applies the destination bucket's default encryption settings if no explicit encryption is specified
|
|
func (s3a *S3ApiServer) applyCopyBucketDefaultEncryption(state *EncryptionState, dstBucket string) {
|
|
if !state.IsTargetEncrypted() {
|
|
bucketMetadata, err := s3a.getBucketMetadata(dstBucket)
|
|
if err == nil && bucketMetadata != nil && bucketMetadata.Encryption != nil {
|
|
switch bucketMetadata.Encryption.SseAlgorithm {
|
|
case "aws:kms":
|
|
state.DstSSEKMS = true
|
|
case "AES256":
|
|
state.DstSSES3 = true
|
|
}
|
|
}
|
|
}
|
|
}
|