mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* s3api: keep a long CopyObject/UploadPartCopy alive with whitespace, as AWS does CopyObject and UploadPartCopy copy every chunk and only then write the response. On a slow volume disk (~10 MB/s), or when the source is a remote-only file of a remote-mounted bucket that is fetched first, a copy of tens of MB sends no byte for 20-30 s. Clients with a low-speed check give up while the copy finishes: the AWS SDK for C++ (pyarrow, among others) sets libcurl's CURLOPT_LOW_SPEED_LIMIT to 1 byte/s over a few seconds, and the abandoned copy leaves an orphan. AWS S3's documented behaviour for long copies: answer 200 at once, keep the connection alive with whitespace, then send <CopyObjectResult> (or an <Error> document) in the body. This does the same: - Once every check that refuses with its own status has run (auth, missing source, preconditions, invalid arguments, ACL and lock headers, the remote-cache 503), a copy still running after 1 s commits to 200, application/xml and the XML declaration, then sends one space a second, flushed, until <CopyObjectResult>/<CopyPartResult> (checksum in the body) or an <Error> with the code the handler would have answered. A copy that ends sooner answers byte for byte as before. - Armed before a remote-only source is fetched into the cluster, which is the slow part on a remote-mounted bucket. - Never kept alive: the metadata-only self-copy; a destination with versioning Enabled (x-amz-version-id is known only after the copy); a part copy whose upload or request carries SSE (its response headers are known only after the copy). - One goroutine owns the ResponseWriter from arming until halt() returns; a client that leaves ends it without touching the copy. - s3err gains StartStreamingResponse, ErrorResponseFor and EncodeXMLBody, shared with WriteErrorResponse. Accepted: a slow failure is 200 + <Error>, as on AWS, and the request is counted as 200. Tests: s3api_object_handlers_copy_keepalive_test.go (slow success and failure, fast unchanged, a refusal keeps its status, part copy, versioned destination, SSE-C part, checksum in the body, remote fill covered, client gone under -race, slow lookup then bad tag = 400, self-copy 412 under the lock, part range on a remote-only source). With the keep-alive forced off, the slow-copy tests fail. * s3api: send a block of spaces per copy keep-alive tick libcurl rounds its measured rate down, so one byte a second sits right at the AWS SDK for C++'s 1 byte/s low-speed limit and jitter can trip it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: audit a kept-alive copy error at the 200 it was sent with Once the keep-alive has sent 200, the <Error> rides in that response, so the access log records 200 and the error code, as AWS server access logs do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: fill a conditional remote-only copy source before the keep-alive A source condition read the filled entry only after the keep-alive had committed 200, so a slow fill turned its 412 (or the 400 of a malformed date) into an <Error> inside a 200. With any x-amz-copy-source-if-* header the fill runs first, as it did before the keep-alive. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: fill a remote-only self-copy that moves data under the keep-alive Only a self-copy that can stay metadata-only needs its source filled before the keep-alive; one that re-encrypts takes the data path, so its fill is the slow part the keep-alive is for. A fill changes no encryption state, so the unfilled entry decides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: test that the copy keep-alive reaches a client mid-copy A ResponseRecorder keeps every write, flushed or not; over a real connection the declaration and the spaces must arrive while the copy is still held. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * s3api: bound the copy keep-alive streaming test with a request deadline Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
199 lines
6.6 KiB
Go
199 lines
6.6 KiB
Go
package s3err
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/xml"
|
|
"io"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
|
|
"github.com/gorilla/mux"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/util/request_id"
|
|
)
|
|
|
|
type mimeType string
|
|
|
|
const (
|
|
mimeNone mimeType = ""
|
|
MimeXML mimeType = "application/xml"
|
|
|
|
errorResponseBodyDrainTimeout = 30 * time.Second
|
|
)
|
|
|
|
func WriteAwsXMLResponse(w http.ResponseWriter, r *http.Request, statusCode int, result interface{}) {
|
|
var bytesBuffer bytes.Buffer
|
|
err := xmlutil.BuildXML(result, xml.NewEncoder(&bytesBuffer))
|
|
if err != nil {
|
|
WriteErrorResponse(w, r, ErrInternalError)
|
|
return
|
|
}
|
|
WriteResponse(w, r, statusCode, bytesBuffer.Bytes(), MimeXML)
|
|
}
|
|
|
|
func WriteXMLResponse(w http.ResponseWriter, r *http.Request, statusCode int, response interface{}) {
|
|
WriteResponse(w, r, statusCode, EncodeXMLResponse(response), MimeXML)
|
|
}
|
|
|
|
func WriteEmptyResponse(w http.ResponseWriter, r *http.Request, statusCode int) {
|
|
WriteResponse(w, r, statusCode, []byte{}, mimeNone)
|
|
PostLog(r, statusCode, ErrNone)
|
|
}
|
|
|
|
func WriteErrorResponse(w http.ResponseWriter, r *http.Request, errorCode ErrorCode) {
|
|
WriteErrorResponseWithMessage(w, r, errorCode, "")
|
|
}
|
|
|
|
// WriteErrorResponseWithMessage writes an S3 error response that uses the
|
|
// standard error code mapping (status + Code). When message is non-empty,
|
|
// it overrides the default Message field so the caller can surface why the
|
|
// request was rejected (e.g. which POST policy condition failed) instead
|
|
// of the generic APIError Description.
|
|
func WriteErrorResponseWithMessage(w http.ResponseWriter, r *http.Request, errorCode ErrorCode, message string) {
|
|
r, _ = request_id.Ensure(r)
|
|
apiError := GetAPIError(errorCode)
|
|
errorResponse := ErrorResponseFor(r, errorCode)
|
|
if message != "" {
|
|
errorResponse.Message = message
|
|
}
|
|
drainRequestBody(w, r)
|
|
WriteXMLResponse(w, r, apiError.HTTPStatusCode, errorResponse)
|
|
PostLog(r, apiError.HTTPStatusCode, errorCode)
|
|
}
|
|
|
|
// ErrorResponseFor builds the <Error> document WriteErrorResponse sends for
|
|
// errorCode, for a caller that has to write it into a response already begun.
|
|
func ErrorResponseFor(r *http.Request, errorCode ErrorCode) RESTErrorResponse {
|
|
r, reqID := request_id.Ensure(r)
|
|
vars := mux.Vars(r)
|
|
bucket := vars["bucket"]
|
|
object := vars["object"]
|
|
if strings.HasPrefix(object, "/") {
|
|
object = object[1:]
|
|
}
|
|
return getRESTErrorResponse(GetAPIError(errorCode), r.URL.Path, bucket, object, reqID)
|
|
}
|
|
|
|
// StartStreamingResponse sends the status line and the headers every response
|
|
// carries, without a Content-Length, for a body the caller writes in pieces.
|
|
func StartStreamingResponse(w http.ResponseWriter, r *http.Request, statusCode int, mType mimeType) {
|
|
setCommonHeaders(w, r)
|
|
if mType != mimeNone {
|
|
w.Header().Set("Content-Type", string(mType))
|
|
}
|
|
w.WriteHeader(statusCode)
|
|
}
|
|
|
|
func drainRequestBody(w http.ResponseWriter, r *http.Request) {
|
|
if r == nil || r.Body == nil || r.Body == http.NoBody {
|
|
return
|
|
}
|
|
rc := http.NewResponseController(w)
|
|
if err := rc.SetReadDeadline(time.Now().Add(errorResponseBodyDrainTimeout)); err == nil {
|
|
defer rc.SetReadDeadline(time.Time{})
|
|
}
|
|
_, _ = io.Copy(io.Discard, r.Body)
|
|
}
|
|
|
|
func getRESTErrorResponse(err APIError, resource string, bucket, object, requestID string) RESTErrorResponse {
|
|
return RESTErrorResponse{
|
|
Code: err.Code,
|
|
BucketName: bucket,
|
|
Key: object,
|
|
Message: err.Description,
|
|
Resource: resource,
|
|
RequestID: requestID,
|
|
}
|
|
}
|
|
|
|
// Encodes the response headers into XML format.
|
|
func EncodeXMLResponse(response interface{}) []byte {
|
|
return append([]byte(xml.Header), EncodeXMLBody(response)...)
|
|
}
|
|
|
|
// EncodeXMLBody encodes response without the XML declaration, for a body
|
|
// whose declaration was already sent.
|
|
func EncodeXMLBody(response interface{}) []byte {
|
|
var bytesBuffer bytes.Buffer
|
|
e := xml.NewEncoder(&bytesBuffer)
|
|
e.Encode(response)
|
|
return bytesBuffer.Bytes()
|
|
}
|
|
|
|
func setCommonHeaders(w http.ResponseWriter, r *http.Request) {
|
|
_, reqID := request_id.Ensure(r)
|
|
w.Header().Set(request_id.AmzRequestIDHeader, reqID)
|
|
w.Header().Set("Accept-Ranges", "bytes")
|
|
|
|
// Handle CORS headers for requests with Origin header
|
|
if r.Header.Get("Origin") != "" {
|
|
// Use mux.Vars to detect bucket-specific requests more reliably
|
|
vars := mux.Vars(r)
|
|
bucket := vars["bucket"]
|
|
isBucketRequest := bucket != ""
|
|
|
|
if !isBucketRequest {
|
|
// Service-level request (like OPTIONS /) - apply static CORS if none set
|
|
if w.Header().Get("Access-Control-Allow-Origin") == "" {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "*")
|
|
w.Header().Set("Access-Control-Allow-Headers", "*")
|
|
w.Header().Set("Access-Control-Expose-Headers", "*")
|
|
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
}
|
|
} else {
|
|
// Bucket-specific request - preserve existing CORS headers or set default
|
|
// This handles cases where CORS middleware set headers but auth failed
|
|
if w.Header().Get("Access-Control-Allow-Origin") == "" {
|
|
// No CORS headers were set by middleware, so this request doesn't match any CORS rule
|
|
// According to CORS spec, we should not set CORS headers for non-matching requests
|
|
// However, if the bucket has CORS config but request doesn't match,
|
|
// we still should not set headers here as it would be incorrect
|
|
}
|
|
// If CORS headers were already set by middleware, preserve them
|
|
}
|
|
}
|
|
}
|
|
|
|
// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
|
|
func bodyAllowedForStatus(status int) bool {
|
|
switch {
|
|
case status >= 100 && status <= 199:
|
|
return false
|
|
case status == http.StatusNoContent:
|
|
return false
|
|
case status == http.StatusNotModified:
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func WriteResponse(w http.ResponseWriter, r *http.Request, statusCode int, response []byte, mType mimeType) {
|
|
setCommonHeaders(w, r)
|
|
canHaveBody := bodyAllowedForStatus(statusCode)
|
|
if response != nil && canHaveBody {
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
|
|
}
|
|
if mType != mimeNone {
|
|
w.Header().Set("Content-Type", string(mType))
|
|
}
|
|
w.WriteHeader(statusCode)
|
|
if response != nil && canHaveBody && r.Method != http.MethodHead {
|
|
glog.V(4).Infof("status %d %s: %s", statusCode, mType, string(response))
|
|
_, err := w.Write(response)
|
|
if err != nil {
|
|
glog.V(1).Infof("write err: %v", err)
|
|
}
|
|
w.(http.Flusher).Flush()
|
|
}
|
|
}
|
|
|
|
// If none of the http routes match respond with MethodNotAllowed
|
|
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
|
|
glog.V(2).Infof("unsupported %s %s", r.Method, r.RequestURI)
|
|
WriteErrorResponse(w, r, ErrMethodNotAllowed)
|
|
}
|