mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-10-29 16:30:44 +01:00
* s3: read regular copy sources from their write owner * filer: report mutation sentinel codes in ObjectTransaction responses A failed mutation only surfaced resp.Error text, so routed writers could not distinguish an existing-directory conflict from a generic failure and could not apply the prefix-object retry the plain CreateEntry path has. * s3api: retry a routed mkfile as a prefix object over a directory mkFile retries ErrExistingIsDirectory by marking the entry a prefix object; the routed path returned the conflict instead, so a routed write to a key that is also a prefix failed where the lock path succeeds. The filer now reports the code on the transaction response, making the retry recognizable. * s3api: commit copy destinations on the key's write owner An owner-routed source read still left the destination on the gateway's default filer, so a second copy resolved the first copy's destination on the owner, found nothing, and returned NoSuchKey. Write unversioned and suspended destinations through routedMkFile, and write the version file on the owner the finalize recomputes on. * s3api: cache remote objects on the filer that served the entry An owner-routed lookup can return a remote-only entry that has not replicated to the gateway's default filer; the cache RPC then cannot find it and the copy or read degrades to a 503. Ask the entry's write owner to cache it first, falling back to the default filer. * s3: read versioned object state from the key's write owner CopyObject destinations now commit version files and the .versions pointer on the owner's object-scope ring key, so versioned reads through the default filer could miss them until replication. Generalize the routed read to dir/name lookups and paginated lists scoped to the object's owner, and point the versioned read paths at it: getSpecificObjectVersion, doGetLatestObjectVersion, the .versions quick-checks in Get/Head/attributes, the self-heal rescans, tagging, delete conditionals, directory-marker history checks, rename destination, multipart completion checks, and the version-id format probe. Reads fall back to the default filer when no ring owner is resolvable, preserving single-filer deployments. * test(s3api): fake RECOMPUTE_LATEST/DELETE and cover versioned copy reads The ambiguous-PUT fake filer now creates parent directories on PUT (mirroring InsertEntry), applies DELETE mutations, and re-derives the .versions pointer for RECOMPUTE_LATEST the way applyRecomputeLatest does, so owner-vs-replica tests can exercise versioned writes. TestVersionedCopyDestinationReadsOnOwner copies into a versioned bucket whose writes commit on the owner while the gateway's default filer is a replica with no replication, then asserts reads by versionId, latest-version resolution, and a copy chained off the new version all resolve on the owner. * test(s3api): gofmt the versioned-copy coverage * s3: only swap in a cache fill of the resolved remote generation A cache response can come back from a filer holding an older generation of the key. Replacing the authorized source or swapping its chunks under a size and range computed for the resolved entry serves the wrong object or truncates the response. Match RemoteEntry identity and size before using a cached entry, in both the copy and streaming paths. * filer: keep directory attributes when an object lands as prefix object The object-onto-directory retry replaced the existing directory's mode, owner, and extended attributes with the object's. Preserve the directory identity; merge directory-held extended keys only when the old entry never held an object, so a prior generation's object metadata is not carried forward. * s3: keep marker lock checks on the filer that replaces the marker The object-lock precondition read the key's write owner while mkdir still replaces the marker on the default filer, so a locked marker not yet replicated to the owner could be overwritten. Read the entry where the replacement lands, in both PutObjectHandler and zip extraction. Also hash a trailing-slash marker key to the same route key as the object it names, so marker and object share one owner and one write lock. * s3: route tag writes to the owner tag reads resolve GetObjectTagging reads the key's write owner, but PutObjectTagging and DeleteObjectTagging still wrote through the default filer, so a successful change returned the owner's stale tags until replication. setTags, rmTags, and the versioned tag updates now write on the owner first, falling back to the default filer when no owner resolves. * s3: keep rename lookups on the filer that performs the move AtomicRenameEntry and the retry token it carries both execute on the default filer, but the source and destination reads went to the write owner — a completed rename's token was invisible to its own retry, and a source that only exists on the default filer looked absent. Read both ends on the default filer. * s3: send the .versions pointer repair with the object's route key The heal reads the .versions entry on the object's owner, but the conditional UpdateEntry is routed by the .versions path's own ring key, which can hash to a different filer — leaving the pointer the routed reads consult unchanged. Ship the CAS repair as a PATCH_EXTENDED ObjectTransaction on the object's route key instead. * filer: preserve only directory identity on a prefix-object write Merging the old directory's extended attributes could carry a marker's encryption, version, or etag fields onto the new plaintext object, since a directory's own keys cannot be told apart from the object it held. Keep only mode, uid, gid, user name and group names. * s3: also require matching size when a cache fill replaces the source The remote-generation check covers identity; size equality is the cheap guard that keeps the streamed or copied range consistent with what was resolved. * s3: lock the object path for a routed .versions pointer repair conditionalUpdateEntryRouted held the lock on the .versions path while version writes and deletes serialize on the object path, so a repair could pass IF_ENTRY_EQUAL and then apply over a pointer a writer had advanced in between. Lock the object path like the writers and keep the condition on the .versions entry via condition_key. * s3: do not replay an owner-side tag mutation on another filer withWriteOwnerFilerClient re-ran fn on the default filer after any owner error, so an authoritative not-found could update a stale replica entry and still report success, and a post-apply transport error could apply the mutation twice. The failover walk now ends on any error fn returns; only a channel that never came up moves to another filer. * filer: keep a directory's xattrs when a prefix object replaces it The prefix-object branch preserves the directory's identity but dropped its Extended map wholesale; FUSE xattrs live there under the xattr- prefix and belong to the directory, not to the object the marker held. * s3: delete null and specific versions on the filer that serves them On the default filer an absent entry deletes as success, so a version that only reached the write owner survived a reported success while owner-routed reads kept serving it. The suspended-versioning and lifecycle deletes now go through routedDeleteNullVersion and routedDeleteSpecificVersion when an owner resolves; an unsettled attempt keeps the lock path. * s3: route a lifecycle null-version delete to the object entry The "null" version is the regular object entry, not a .versions file, so it goes through routedDeleteNullVersion; only a real version id takes the .versions-file delete. * s3: repoint .versions only while it still names the deleted version routedDeleteSpecificVersion recomputed the latest pointer on every version delete, so removing a noncurrent version re-derived the pointer to the newest remaining file — resurrecting an older version over a cleared pointer (a suspended bucket's null write keeps it clear while the null object stays current) or over a pointer that moved on. The pointer is now read on the owner and repointed under an IF_ENTRY_EQUAL guard only while it still names the deleted version; a contested pointer is left for the self-heal path rather than overwritten by a stale scan. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: let lifecycle expiry keep its metadata-only deletes on routed paths The routed lifecycle deletes hardcoded IsDeleteData, so expiring an entry with a volume TTL queued per-chunk deletions instead of leaving the data for the volume to reclaim — extra work on the owner for deletes recordMetadataOnlyIf still counts as metadata-only. Pass the caller's cleanup choice through routedDeleteNullVersion and routedDeleteSpecificVersion; the interactive DELETE path keeps deleting data. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * filer: let RECOMPUTE_LATEST skip a pointer that moved on A version delete repoints .versions only while the pointer still names the deleted version, but the gateway cannot carry the pointer's current state into the transaction's condition — the condition slot is already spent on the version's WORM guards. only_if_current_name moves the check under the transaction lock: the filer compares the pointer's name_to_key value before scanning and skips the recompute when it moved (or was cleared by a suspended bucket's null write), so a noncurrent delete cannot resurrect an older version. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * s3: repoint inside the version's locked delete repointLatestBeforeVersionDelete ran in its own transaction ahead of the delete, so a version delete denied by retention or legal hold still moved the latest pointer — GET and HEAD went on serving the older version it rolled to. The repoint and the delete now ride one transaction behind the version's WORM guards, atomically gated by the new only_if_current_name recompute guard instead of a stale-read IF_ENTRY_EQUAL. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
366 lines
11 KiB
Go
366 lines
11 KiB
Go
package s3api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"encoding/xml"
|
|
"errors"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"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/s3err"
|
|
)
|
|
|
|
const maxPartsListDefault = 1000
|
|
|
|
// GetObjectAttributesResponse is the XML response for GetObjectAttributes.
|
|
type GetObjectAttributesResponse struct {
|
|
XMLName xml.Name `xml:"GetObjectAttributesResponse"`
|
|
ETag string `xml:"ETag,omitempty"`
|
|
Checksum *ObjectAttributesChecksum `xml:"Checksum,omitempty"`
|
|
ObjectParts *ObjectAttributesParts `xml:"ObjectParts,omitempty"`
|
|
StorageClass string `xml:"StorageClass,omitempty"`
|
|
ObjectSize *int64 `xml:"ObjectSize,omitempty"`
|
|
}
|
|
|
|
// ObjectAttributesChecksum holds checksum info for GetObjectAttributes.
|
|
type ObjectAttributesChecksum struct {
|
|
ChecksumResult
|
|
ChecksumType string `xml:"ChecksumType,omitempty"`
|
|
}
|
|
|
|
// ObjectAttributesParts holds parts info for GetObjectAttributes.
|
|
type ObjectAttributesParts struct {
|
|
IsTruncated bool `xml:"IsTruncated"`
|
|
MaxParts int `xml:"MaxParts"`
|
|
NextPartNumberMarker int `xml:"NextPartNumberMarker"`
|
|
PartNumberMarker int `xml:"PartNumberMarker"`
|
|
TotalPartsCount int `xml:"PartsCount"`
|
|
Parts []*ObjectAttributesPart `xml:"Part"`
|
|
}
|
|
|
|
// ObjectAttributesPart holds info for a single part.
|
|
type ObjectAttributesPart struct {
|
|
PartNumber int `xml:"PartNumber"`
|
|
Size int64 `xml:"Size"`
|
|
}
|
|
|
|
// parseObjectAttributes parses the X-Amz-Object-Attributes header.
|
|
func parseObjectAttributes(h http.Header) map[string]struct{} {
|
|
attrs := make(map[string]struct{})
|
|
for _, headerVal := range h.Values(s3_constants.AmzObjectAttributes) {
|
|
for _, v := range strings.Split(strings.TrimSpace(headerVal), ",") {
|
|
v = strings.TrimSpace(v)
|
|
if v != "" {
|
|
attrs[v] = struct{}{}
|
|
}
|
|
}
|
|
}
|
|
return attrs
|
|
}
|
|
|
|
// validateObjectAttributes checks that all requested attributes are valid.
|
|
func validateObjectAttributes(attrs map[string]struct{}) bool {
|
|
for attr := range attrs {
|
|
switch attr {
|
|
case "ETag", "Checksum", "StorageClass", "ObjectSize", "ObjectParts":
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// objectAttributesChecksum returns the additional checksum that PutObject or
|
|
// CompleteMultipartUpload stored with the object, or nil if it has none.
|
|
func objectAttributesChecksum(entry *filer_pb.Entry) *ObjectAttributesChecksum {
|
|
if entry == nil || entry.Extended == nil {
|
|
return nil
|
|
}
|
|
value := string(entry.Extended[s3_constants.ExtChecksumValue])
|
|
if value == "" {
|
|
return nil
|
|
}
|
|
checksum := &ObjectAttributesChecksum{ChecksumType: string(entry.Extended[s3_constants.ExtChecksumType])}
|
|
checksum.SetChecksum(string(entry.Extended[s3_constants.ExtChecksumAlgorithm]), value)
|
|
if checksum.ChecksumResult == (ChecksumResult{}) {
|
|
return nil
|
|
}
|
|
return checksum
|
|
}
|
|
|
|
func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *http.Request) {
|
|
bucket, object := s3_constants.GetBucketAndObject(r)
|
|
glog.V(3).Infof("GetObjectAttributesHandler %s %s", bucket, object)
|
|
|
|
// Parse and validate requested attributes
|
|
requestedAttrs := parseObjectAttributes(r.Header)
|
|
if len(requestedAttrs) == 0 || !validateObjectAttributes(requestedAttrs) {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidAttributeName)
|
|
return
|
|
}
|
|
|
|
// Parse optional pagination headers for ObjectParts
|
|
maxParts := maxPartsListDefault
|
|
if v := r.Header.Get(s3_constants.AmzMaxParts); v != "" {
|
|
parsed, err := strconv.Atoi(v)
|
|
if err != nil || parsed < 0 {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxParts)
|
|
return
|
|
}
|
|
maxParts = parsed
|
|
if maxParts > maxPartsListDefault {
|
|
maxParts = maxPartsListDefault
|
|
}
|
|
}
|
|
partNumberMarker := 0
|
|
if v := r.Header.Get(s3_constants.AmzPartNumberMarker); v != "" {
|
|
parsed, err := strconv.Atoi(v)
|
|
if err != nil || parsed < 0 {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPartNumberMarker)
|
|
return
|
|
}
|
|
partNumberMarker = parsed
|
|
}
|
|
|
|
// Check for specific version ID
|
|
versionId := r.URL.Query().Get("versionId")
|
|
if errCode := s3a.checkVersionIdConfigured(bucket, versionId); errCode != s3err.ErrNone {
|
|
s3err.WriteErrorResponse(w, r, errCode)
|
|
return
|
|
}
|
|
|
|
var (
|
|
entry *filer_pb.Entry
|
|
err error
|
|
)
|
|
|
|
versioningConfigured, err := s3a.isVersioningConfigured(bucket)
|
|
if err != nil {
|
|
if err == filer_pb.ErrNotFound {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
|
|
return
|
|
}
|
|
glog.Errorf("Error checking versioning for bucket %s: %v", bucket, err)
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
|
return
|
|
}
|
|
|
|
if versioningConfigured {
|
|
var targetVersionId string
|
|
|
|
if versionId != "" {
|
|
entry, err = s3a.getSpecificObjectVersion(bucket, object, versionId)
|
|
if err != nil {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
|
return
|
|
}
|
|
targetVersionId = versionId
|
|
} else {
|
|
bucketDir := s3a.bucketDir(bucket)
|
|
normalizedObject := s3_constants.NormalizeObjectKey(object)
|
|
versionsDir := normalizedObject + s3_constants.VersionsFolder
|
|
|
|
versionsEntry, versionsErr := s3a.getObjectScopedEntryRoutedByKey(bucket, normalizedObject, bucketDir, versionsDir)
|
|
if versionsErr == nil && versionsEntry != nil {
|
|
entry, err = s3a.getLatestObjectVersion(bucket, object)
|
|
if err != nil {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
|
return
|
|
}
|
|
} else if errors.Is(versionsErr, filer_pb.ErrNotFound) {
|
|
regularEntry, regularErr := s3a.getObjectEntryRoutedByKey(bucket, normalizedObject)
|
|
if regularErr == nil && regularEntry != nil {
|
|
entry = regularEntry
|
|
targetVersionId = "null"
|
|
} else {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
|
return
|
|
}
|
|
} else {
|
|
entry, err = s3a.getLatestObjectVersion(bucket, object)
|
|
if err != nil {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
|
return
|
|
}
|
|
}
|
|
|
|
if targetVersionId == "" {
|
|
if entry.Extended != nil {
|
|
if versionIdBytes, exists := entry.Extended[s3_constants.ExtVersionIdKey]; exists {
|
|
targetVersionId = string(versionIdBytes)
|
|
}
|
|
}
|
|
if targetVersionId == "" {
|
|
targetVersionId = "null"
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check for delete marker
|
|
if entry.Extended != nil {
|
|
if deleteMarker, exists := entry.Extended[s3_constants.ExtDeleteMarkerKey]; exists && string(deleteMarker) == "true" {
|
|
w.Header().Set(s3_constants.AmzDeleteMarker, "true")
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
|
return
|
|
}
|
|
}
|
|
|
|
w.Header().Set("x-amz-version-id", targetVersionId)
|
|
} else {
|
|
entry, err = s3a.fetchObjectEntry(bucket, object)
|
|
if err != nil {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
|
return
|
|
}
|
|
if entry == nil {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
|
|
return
|
|
}
|
|
}
|
|
|
|
action := s3_constants.S3_ACTION_GET_OBJECT_ATTRIBUTES
|
|
if versionId != "" {
|
|
action = s3_constants.S3_ACTION_GET_OBJECT_VERSION_ATTRIBUTES
|
|
}
|
|
if errCode := s3a.recheckPolicyWithObjectEntry(r, bucket, object, action, entry.Extended, "GetObjectAttributesHandler"); errCode != s3err.ErrNone {
|
|
s3err.WriteErrorResponse(w, r, errCode)
|
|
return
|
|
}
|
|
|
|
// AWS also asks for the version read grant on a versioned attributes
|
|
// request: s3:GetObjectVersionAttributes alone is not sufficient.
|
|
if versionId != "" {
|
|
if errCode := s3a.checkVersionReadGrant(r, bucket, object, versionId, entry.Extended); errCode != s3err.ErrNone {
|
|
s3err.WriteErrorResponse(w, r, errCode)
|
|
return
|
|
}
|
|
}
|
|
|
|
// Evaluate conditional headers against the resolved entry (after version resolution)
|
|
// This ensures conditions are checked against the correct version, not always the latest
|
|
if s3a.hasConditionalHeaders(r) {
|
|
headers, errCode := parseConditionalHeaders(r)
|
|
if errCode != s3err.ErrNone {
|
|
s3err.WriteErrorResponse(w, r, errCode)
|
|
return
|
|
}
|
|
result := s3a.validateConditionalHeadersForReads(r, headers, entry, bucket, object)
|
|
if result.ErrorCode != s3err.ErrNone {
|
|
glog.V(3).Infof("GetObjectAttributesHandler: Conditional header check failed for %s/%s with error %v", bucket, object, result.ErrorCode)
|
|
if result.ErrorCode == s3err.ErrNotModified && result.ETag != "" {
|
|
w.Header().Set("ETag", result.ETag)
|
|
}
|
|
s3err.WriteErrorResponse(w, r, result.ErrorCode)
|
|
return
|
|
}
|
|
}
|
|
|
|
if entry == nil {
|
|
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
|
return
|
|
}
|
|
|
|
// Build response with only requested attributes
|
|
resp := &GetObjectAttributesResponse{}
|
|
|
|
if _, ok := requestedAttrs["ETag"]; ok {
|
|
etag := s3a.getObjectETag(entry)
|
|
resp.ETag = strings.Trim(etag, `"`)
|
|
}
|
|
|
|
if _, ok := requestedAttrs["StorageClass"]; ok {
|
|
storageClass := "STANDARD"
|
|
if entry.Extended != nil {
|
|
if sc, exists := entry.Extended[s3_constants.AmzStorageClass]; exists && len(sc) > 0 {
|
|
storageClass = string(sc)
|
|
}
|
|
}
|
|
resp.StorageClass = storageClass
|
|
}
|
|
|
|
if _, ok := requestedAttrs["Checksum"]; ok {
|
|
resp.Checksum = objectAttributesChecksum(entry)
|
|
}
|
|
|
|
if _, ok := requestedAttrs["ObjectSize"]; ok {
|
|
var size int64
|
|
if entry.Attributes != nil {
|
|
size = int64(entry.Attributes.FileSize)
|
|
}
|
|
resp.ObjectSize = &size
|
|
}
|
|
|
|
if _, ok := requestedAttrs["ObjectParts"]; ok {
|
|
resp.ObjectParts = s3a.buildObjectAttributesParts(entry, maxParts, partNumberMarker)
|
|
}
|
|
|
|
// Set Last-Modified, remove Content-Type
|
|
if entry.Attributes != nil && entry.Attributes.Mtime > 0 {
|
|
w.Header().Set("Last-Modified", time.Unix(entry.Attributes.Mtime, 0).UTC().Format(http.TimeFormat))
|
|
}
|
|
w.Header().Del("Content-Type")
|
|
|
|
writeSuccessResponseXML(w, r, resp)
|
|
}
|
|
|
|
// buildObjectAttributesParts builds the ObjectParts section from multipart metadata.
|
|
func (s3a *S3ApiServer) buildObjectAttributesParts(entry *filer_pb.Entry, maxParts, partNumberMarker int) *ObjectAttributesParts {
|
|
if entry.Extended == nil {
|
|
return nil
|
|
}
|
|
|
|
boundariesJSON, exists := entry.Extended[s3_constants.SeaweedFSMultipartPartBoundaries]
|
|
if !exists {
|
|
return nil
|
|
}
|
|
|
|
var boundaries []PartBoundaryInfo
|
|
if err := json.Unmarshal(boundariesJSON, &boundaries); err != nil {
|
|
glog.Warningf("GetObjectAttributes: failed to unmarshal part boundaries: %v", err)
|
|
return nil
|
|
}
|
|
|
|
if len(boundaries) == 0 {
|
|
return nil
|
|
}
|
|
|
|
parts := &ObjectAttributesParts{
|
|
PartNumberMarker: partNumberMarker,
|
|
MaxParts: maxParts,
|
|
TotalPartsCount: len(boundaries),
|
|
}
|
|
|
|
chunks := entry.GetChunks()
|
|
for _, b := range boundaries {
|
|
if b.PartNumber <= partNumberMarker {
|
|
continue
|
|
}
|
|
if len(parts.Parts) >= maxParts {
|
|
parts.IsTruncated = true
|
|
break
|
|
}
|
|
|
|
var partSize int64
|
|
if b.EndOffset > b.StartOffset {
|
|
partSize = b.EndOffset - b.StartOffset
|
|
} else if b.StartChunk >= 0 && b.EndChunk >= 0 && b.StartChunk < len(chunks) && b.EndChunk <= len(chunks) && b.StartChunk < b.EndChunk {
|
|
for ci := b.StartChunk; ci < b.EndChunk; ci++ {
|
|
partSize += int64(chunks[ci].Size)
|
|
}
|
|
}
|
|
|
|
parts.NextPartNumberMarker = b.PartNumber
|
|
parts.Parts = append(parts.Parts, &ObjectAttributesPart{
|
|
PartNumber: b.PartNumber,
|
|
Size: partSize,
|
|
})
|
|
}
|
|
|
|
return parts
|
|
}
|