mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-01 00:27:07 +01:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d807dbfcbc | ||
|
|
480a1baa20 | ||
|
|
ac2efbac01 | ||
|
|
10381075f3 | ||
|
|
51d591e060 |
No files matched your search
@@ -73,6 +73,13 @@ jobs:
|
||||
echo "=== Running S3 Prefix Object Tests ==="
|
||||
go test -v -timeout=180s -run TestS3PrefixObjectKeys ./...
|
||||
|
||||
- name: Run S3 GetPart Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
run: |
|
||||
set -x
|
||||
go test -v -timeout=180s -run TestS3GetPart ./...
|
||||
|
||||
- name: Run IAM Integration Tests
|
||||
timeout-minutes: 15
|
||||
working-directory: test/s3/normal
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// getPart issues GetPart, which the SDK this suite pins predates, as a signed
|
||||
// raw request.
|
||||
func getPart(t *testing.T, cluster *TestCluster, creds *credentials.Credentials, bucket, key, uploadID string, partNumber int, header http.Header) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
query := url.Values{}
|
||||
query.Set("part", "")
|
||||
query.Set("partNumber", fmt.Sprint(partNumber))
|
||||
query.Set("uploadId", uploadID)
|
||||
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/%s?%s", cluster.s3Endpoint, bucket, key, query.Encode()), nil)
|
||||
require.NoError(t, err)
|
||||
for k, v := range header {
|
||||
req.Header[k] = v
|
||||
}
|
||||
_, err = v4.NewSigner(creds).Sign(req, nil, "s3", testRegion, time.Now())
|
||||
require.NoError(t, err)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return resp, body
|
||||
}
|
||||
|
||||
func errorCode(t *testing.T, body []byte) string {
|
||||
t.Helper()
|
||||
var e struct{ Code string }
|
||||
require.NoError(t, xml.Unmarshal(body, &e), string(body))
|
||||
return e.Code
|
||||
}
|
||||
|
||||
func TestS3GetPart(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
admin := client.Config.Credentials
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-")
|
||||
key := "media/clip.bin"
|
||||
|
||||
part1 := bytes.Repeat([]byte("a"), 5*1024*1024)
|
||||
part1Retry := bytes.Repeat([]byte("c"), 5*1024*1024)
|
||||
part2 := []byte("the last part, short")
|
||||
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
uploadID := aws.StringValue(created.UploadId)
|
||||
upload := func(n int64, data []byte) *s3.UploadPartOutput {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int64(n), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return out
|
||||
}
|
||||
upload(1, part1)
|
||||
retried := upload(1, part1Retry)
|
||||
uploaded2 := upload(2, part2)
|
||||
|
||||
t.Run("open upload serves the latest attempt", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "IN_PROGRESS", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(retried.ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, resp.Header.Get("Content-Range"))
|
||||
assert.True(t, bytes.Equal(part1Retry, body), "part 1 body is not the retried attempt")
|
||||
})
|
||||
|
||||
t.Run("open upload range counts within the part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=4-7"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
assert.Equal(t, fmt.Sprintf("bytes 4-7/%d", len(part2)), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[4:8]), string(body))
|
||||
})
|
||||
|
||||
t.Run("missing part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchPart", errorCode(t, body))
|
||||
})
|
||||
|
||||
t.Run("sse request header is rejected", func(t *testing.T) {
|
||||
resp, _ := getPart(t, cluster, admin, bucket, key, uploadID, 1, http.Header{"X-Amz-Server-Side-Encryption": {"AES256"}})
|
||||
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("open part returns its checksum when asked", func(t *testing.T) {
|
||||
data := []byte("checksummed part")
|
||||
sum := crc32.ChecksumIEEE(data)
|
||||
want := base64.StdEncoding.EncodeToString([]byte{byte(sum >> 24), byte(sum >> 16), byte(sum >> 8), byte(sum)})
|
||||
_, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
PartNumber: aws.Int64(5), Body: bytes.NewReader(data), ChecksumCRC32: aws.String(want),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 5, http.Header{"X-Amz-Checksum-Mode": {"ENABLED"}})
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, want, resp.Header.Get("x-amz-checksum-crc32"))
|
||||
})
|
||||
|
||||
t.Run("ListParts still answers without ?part", func(t *testing.T) {
|
||||
parts, err := client.ListParts(&s3.ListPartsInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID)})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, parts.Parts, 3)
|
||||
})
|
||||
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{
|
||||
{PartNumber: aws.Int64(1), ETag: retried.ETag},
|
||||
{PartNumber: aws.Int64(2), ETag: uploaded2.ETag},
|
||||
}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("completed upload serves the part from the object", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(uploaded2.ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed upload range counts within the part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=-4"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
n := len(part2)
|
||||
assert.Equal(t, fmt.Sprintf("bytes %d-%d/%d", n-4, n-1, n), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[n-4:]), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed upload has no such part", func(t *testing.T) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchPart", errorCode(t, body))
|
||||
})
|
||||
|
||||
t.Run("completed upload in a version that is no longer latest", func(t *testing.T) {
|
||||
vbucket := createTestBucket(t, cluster, "test-get-part-versioned-")
|
||||
_, err := client.PutBucketVersioning(&s3.PutBucketVersioningInput{
|
||||
Bucket: aws.String(vbucket), VersioningConfiguration: &s3.VersioningConfiguration{Status: aws.String("Enabled")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(vbucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(1), Body: bytes.NewReader(part2),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
done, err := client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: out.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = client.PutObject(&s3.PutObjectInput{Bucket: aws.String(vbucket), Key: aws.String(key), Body: strings.NewReader("newer")})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, body := getPart(t, cluster, admin, vbucket, key, aws.StringValue(created.UploadId), 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, aws.StringValue(done.VersionId), resp.Header.Get("x-amz-version-id"))
|
||||
assert.Equal(t, string(part2), string(body))
|
||||
})
|
||||
|
||||
t.Run("completed empty part", func(t *testing.T) {
|
||||
emptyKey := "media/empty-tail.bin"
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(emptyKey)})
|
||||
require.NoError(t, err)
|
||||
var parts []*s3.CompletedPart
|
||||
for n, data := range [][]byte{part1, nil} {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(int64(n + 1)), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
parts = append(parts, &s3.CompletedPart{PartNumber: aws.Int64(int64(n + 1)), ETag: out.ETag})
|
||||
}
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: parts},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
resp, body := getPart(t, cluster, admin, bucket, emptyKey, aws.StringValue(created.UploadId), 2, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.Equal(t, aws.StringValue(parts[1].ETag), resp.Header.Get("ETag"))
|
||||
assert.Empty(t, body)
|
||||
})
|
||||
|
||||
t.Run("aborted upload", func(t *testing.T) {
|
||||
other, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
_, err = client.AbortMultipartUpload(&s3.AbortMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: other.UploadId})
|
||||
require.NoError(t, err)
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, aws.StringValue(other.UploadId), 1, nil)
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
assert.Equal(t, "NoSuchUpload", errorCode(t, body))
|
||||
})
|
||||
}
|
||||
|
||||
// TestS3GetPartIncompleteUploadGrant checks that reading a part of an open
|
||||
// upload needs s3:GetIncompleteUpload on top of s3:GetObject, while a
|
||||
// completed upload's part needs only the read grant.
|
||||
func TestS3GetPartIncompleteUploadGrant(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-grant-")
|
||||
openKey, doneKey := "open.bin", "done.bin"
|
||||
|
||||
start := func(key string) (string, *s3.UploadPartOutput) {
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)})
|
||||
require.NoError(t, err)
|
||||
part, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(1), Body: strings.NewReader("only part"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return aws.StringValue(created.UploadId), part
|
||||
}
|
||||
openID, _ := start(openKey)
|
||||
doneID, donePart := start(doneKey)
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(doneKey), UploadId: aws.String(doneID),
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: donePart.ETag}}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
sess, err := session.NewSession(client.Config.Copy())
|
||||
require.NoError(t, err)
|
||||
iamClient := iam.New(sess)
|
||||
userName := "getpart-reader"
|
||||
_, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
key, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)})
|
||||
require.NoError(t, err)
|
||||
reader := credentials.NewStaticCredentials(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "")
|
||||
|
||||
grant := func(actions ...string) {
|
||||
policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["%s"],"Resource":["arn:aws:s3:::%s/*"]}]}`, strings.Join(actions, `","`), bucket)
|
||||
_, err := iamClient.PutUserPolicy(&iam.PutUserPolicyInput{UserName: aws.String(userName), PolicyName: aws.String("reader"), PolicyDocument: aws.String(policy)})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
expectStatus := func(t *testing.T, key, uploadID string, want int) {
|
||||
t.Helper()
|
||||
require.Eventually(t, func() bool {
|
||||
resp, _ := getPart(t, cluster, reader, bucket, key, uploadID, 1, nil)
|
||||
return resp.StatusCode == want
|
||||
}, 10*time.Second, 200*time.Millisecond)
|
||||
}
|
||||
|
||||
grant("s3:GetObject")
|
||||
t.Run("read grant alone reads a completed part", func(t *testing.T) {
|
||||
expectStatus(t, doneKey, doneID, http.StatusOK)
|
||||
})
|
||||
t.Run("read grant alone cannot read an open part", func(t *testing.T) {
|
||||
expectStatus(t, openKey, openID, http.StatusForbidden)
|
||||
})
|
||||
|
||||
grant("s3:GetObject", "s3:GetIncompleteUpload")
|
||||
t.Run("GetIncompleteUpload opens the part", func(t *testing.T) {
|
||||
expectStatus(t, openKey, openID, http.StatusOK)
|
||||
})
|
||||
}
|
||||
|
||||
// TestS3GetPartSSES3 reads SSE-S3 parts back decrypted, before and after the
|
||||
// upload completes.
|
||||
func TestS3GetPartSSES3(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
cluster, err := startMiniCluster(t)
|
||||
require.NoError(t, err)
|
||||
defer cluster.Stop()
|
||||
|
||||
client := cluster.s3Client
|
||||
admin := client.Config.Credentials
|
||||
bucket := createTestBucket(t, cluster, "test-get-part-sse-")
|
||||
key := "secret.bin"
|
||||
part1 := bytes.Repeat([]byte("0123456789"), 600*1024)
|
||||
part2 := []byte("encrypted tail")
|
||||
|
||||
created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), ServerSideEncryption: aws.String("AES256"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
var completed []*s3.CompletedPart
|
||||
for i, data := range [][]byte{part1, part2} {
|
||||
out, err := client.UploadPart(&s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
PartNumber: aws.Int64(int64(i + 1)), Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
completed = append(completed, &s3.CompletedPart{PartNumber: aws.Int64(int64(i + 1)), ETag: out.ETag})
|
||||
}
|
||||
uploadID := aws.StringValue(created.UploadId)
|
||||
|
||||
check := func(t *testing.T, status string) {
|
||||
resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
|
||||
assert.Equal(t, status, resp.Header.Get("x-amz-multipart-upload-status"))
|
||||
assert.True(t, bytes.Equal(part1, body), "part 1 does not decrypt to what was uploaded")
|
||||
|
||||
resp, body = getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=0-8"}})
|
||||
require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body))
|
||||
assert.Equal(t, fmt.Sprintf("bytes 0-8/%d", len(part2)), resp.Header.Get("Content-Range"))
|
||||
assert.Equal(t, string(part2[:9]), string(body))
|
||||
}
|
||||
t.Run("open", func(t *testing.T) { check(t, "IN_PROGRESS") })
|
||||
|
||||
_, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId,
|
||||
MultipartUpload: &s3.CompletedMultipartUpload{Parts: completed},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
t.Run("completed", func(t *testing.T) { check(t, "COMPLETED") })
|
||||
}
|
||||
@@ -56,6 +56,7 @@ func buildPolicyActionSuggestions() []string {
|
||||
s3_constants.S3_ACTION_UPLOAD_PART_COPY,
|
||||
s3_constants.S3_ACTION_LIST_PARTS,
|
||||
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS,
|
||||
s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD,
|
||||
s3_constants.S3_ACTION_CREATE_BUCKET,
|
||||
s3_constants.S3_ACTION_DELETE_BUCKET,
|
||||
s3_constants.S3_ACTION_LIST_BUCKET,
|
||||
|
||||
@@ -172,7 +172,7 @@ type LiveLock struct {
|
||||
isLocked int32 // 0 = unlocked, 1 = locked; use atomic operations
|
||||
self string
|
||||
lc *LockClient
|
||||
owner string
|
||||
owner atomic.Pointer[string] // read by other goroutines through LockOwner
|
||||
lockTTL time.Duration
|
||||
consecutiveFailures int // Track connection failures to trigger fallback
|
||||
}
|
||||
@@ -497,7 +497,7 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
lock.key, lock.hostFiler, lock.self)
|
||||
|
||||
previousHostFiler := lock.hostFiler
|
||||
previousOwner := lock.owner
|
||||
previousOwner := lock.LockOwner()
|
||||
|
||||
err = pb.WithGrpcFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, lock.lc.TokenSource, func(client filer_pb.SeaweedFilerClient) error {
|
||||
// Bound each attempt: a ring member that is reachable from the masters
|
||||
@@ -549,12 +549,12 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
if resp.LockOwner != "" && resp.LockOwner != previousOwner {
|
||||
// Only log if the owner actually changed
|
||||
glog.V(2).Infof("LOCK: Owner changed from %s to %s for key=%s", previousOwner, resp.LockOwner, lock.key)
|
||||
lock.owner = resp.LockOwner
|
||||
lock.owner.Store(&resp.LockOwner)
|
||||
} else if resp.LockOwner != "" {
|
||||
lock.owner = resp.LockOwner
|
||||
lock.owner.Store(&resp.LockOwner)
|
||||
} else if previousOwner != "" {
|
||||
glog.V(2).Infof("LOCK: Owner cleared for key=%s", lock.key)
|
||||
lock.owner = ""
|
||||
lock.owner.Store(nil)
|
||||
}
|
||||
}
|
||||
return err
|
||||
@@ -575,7 +575,10 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
|
||||
}
|
||||
|
||||
func (lock *LiveLock) LockOwner() string {
|
||||
return lock.owner
|
||||
if owner := lock.owner.Load(); owner != nil {
|
||||
return *owner
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Generation returns the fencing token for this lock.
|
||||
|
||||
@@ -327,7 +327,7 @@ type grantingLockFiler struct {
|
||||
}
|
||||
|
||||
func (s *grantingLockFiler) DistributedLock(ctx context.Context, req *filer_pb.LockRequest) (*filer_pb.LockResponse, error) {
|
||||
return &filer_pb.LockResponse{RenewToken: "tok"}, nil
|
||||
return &filer_pb.LockResponse{RenewToken: "tok", LockOwner: req.Owner}, nil
|
||||
}
|
||||
|
||||
type rotatingAuthLockFiler struct {
|
||||
@@ -819,3 +819,29 @@ func TestLiveLockIsLockedOnlyWithinLease(t *testing.T) {
|
||||
t.Fatal("a lock whose lease ran out must not read as locked")
|
||||
}
|
||||
}
|
||||
|
||||
// Other goroutines read the owner while renewals rewrite it.
|
||||
func TestLiveLockOwnerReadDuringRenewal(t *testing.T) {
|
||||
lock := newGrantingLockClient(t).NewShortLivedLock("test-key", "test-owner")
|
||||
if lock == nil {
|
||||
t.Fatal("lock not granted")
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := 0; i < 20; i++ {
|
||||
lock.AttemptToLock(5 * time.Second)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
if got := lock.LockOwner(); got != "test-owner" {
|
||||
t.Fatalf("owner = %q, want test-owner", got)
|
||||
}
|
||||
return
|
||||
default:
|
||||
_ = lock.LockOwner()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@ var baseS3ActionMap = map[string]string{
|
||||
// resolved request action.
|
||||
"ListBucketMultipartUploads": s3_constants.ACTION_LIST_MULTIPART_UPLOADS,
|
||||
"ListMultipartUploadParts": s3_constants.ACTION_LIST_PARTS,
|
||||
"GetIncompleteUpload": s3_constants.ACTION_GET_INCOMPLETE_UPLOAD,
|
||||
// Retention and legal hold operations
|
||||
"GetObjectRetention": s3_constants.ACTION_GET_OBJECT_RETENTION,
|
||||
"PutObjectRetention": s3_constants.ACTION_PUT_OBJECT_RETENTION,
|
||||
@@ -230,6 +231,8 @@ func MapToIdentitiesAction(action string) string {
|
||||
return "ListBucketMultipartUploads"
|
||||
case s3_constants.ACTION_LIST_PARTS:
|
||||
return "ListMultipartUploadParts"
|
||||
case s3_constants.ACTION_GET_INCOMPLETE_UPLOAD:
|
||||
return "GetIncompleteUpload"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -20,13 +20,18 @@ func (b *MessageQueueBroker) appendToFile(targetFile string, data []byte) error
|
||||
return b.appendToFileWithBufferIndex(targetFile, data, 0)
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) appendToFileWithBufferIndex(targetFile string, data []byte, bufferOffset int64, offsetArgs ...int64) error {
|
||||
// Extract optional offset parameters (minOffset, maxOffset)
|
||||
var minOffset, maxOffset int64
|
||||
if len(offsetArgs) >= 2 {
|
||||
minOffset = offsetArgs[0]
|
||||
maxOffset = offsetArgs[1]
|
||||
// offsetRange reads the optional (minOffset, maxOffset) of a flushed window.
|
||||
// A partition's first window starts at offset 0.
|
||||
func offsetRange(offsetArgs []int64) (minOffset, maxOffset int64, ok bool) {
|
||||
if len(offsetArgs) < 2 {
|
||||
return 0, 0, false
|
||||
}
|
||||
minOffset, maxOffset = offsetArgs[0], offsetArgs[1]
|
||||
return minOffset, maxOffset, minOffset >= 0 && maxOffset >= minOffset
|
||||
}
|
||||
|
||||
func (b *MessageQueueBroker) appendToFileWithBufferIndex(targetFile string, data []byte, bufferOffset int64, offsetArgs ...int64) error {
|
||||
minOffset, maxOffset, hasOffsetRange := offsetRange(offsetArgs)
|
||||
|
||||
fileId, uploadResult, err2 := b.assignAndUpload(targetFile, data)
|
||||
if err2 != nil {
|
||||
@@ -60,7 +65,7 @@ func (b *MessageQueueBroker) appendToFileWithBufferIndex(targetFile string, data
|
||||
}
|
||||
|
||||
// Add offset range metadata for Kafka integration
|
||||
if minOffset > 0 && maxOffset >= minOffset {
|
||||
if hasOffsetRange {
|
||||
if entry.Extended == nil {
|
||||
entry.Extended = make(map[string][]byte)
|
||||
}
|
||||
@@ -108,7 +113,7 @@ func (b *MessageQueueBroker) appendToFileWithBufferIndex(targetFile string, data
|
||||
}
|
||||
|
||||
// Update offset range metadata for existing files
|
||||
if minOffset > 0 && maxOffset >= minOffset {
|
||||
if hasOffsetRange {
|
||||
// Update minimum offset if this chunk has a lower minimum
|
||||
if existingMinData, exists := entry.Extended[mq.ExtendedAttrOffsetMin]; exists && len(existingMinData) == 8 {
|
||||
existingMin := int64(binary.BigEndian.Uint64(existingMinData))
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package broker
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestOffsetRangeIncludesFirstWindow(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
args []int64
|
||||
min, max int64
|
||||
ok bool
|
||||
}{
|
||||
{nil, 0, 0, false},
|
||||
{[]int64{0, 199}, 0, 199, true},
|
||||
{[]int64{0, 0}, 0, 0, true},
|
||||
{[]int64{200, 399}, 200, 399, true},
|
||||
{[]int64{5, 3}, 5, 3, false},
|
||||
{[]int64{-1, 3}, -1, 3, false},
|
||||
} {
|
||||
min, max, ok := offsetRange(tc.args)
|
||||
if min != tc.min || max != tc.max || ok != tc.ok {
|
||||
t.Errorf("offsetRange(%v) = %d, %d, %v; want %d, %d, %v", tc.args, min, max, ok, tc.min, tc.max, tc.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2078,6 +2078,9 @@ func multipartListingAction(r *http.Request, action Action) Action {
|
||||
query := r.URL.Query()
|
||||
_, object := s3_constants.GetBucketAndObject(r)
|
||||
if object != "" && object != "/" && query.Has("uploadId") {
|
||||
if query.Has("part") {
|
||||
return ""
|
||||
}
|
||||
return s3_constants.ACTION_LIST_PARTS
|
||||
}
|
||||
if query.Has("uploads") {
|
||||
|
||||
@@ -473,8 +473,8 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedEtagMismatch).Inc()
|
||||
continue
|
||||
}
|
||||
if len(entry.Chunks) == 0 && partNumber != maxPartNo {
|
||||
glog.Warningf("completeMultipartUpload %s empty chunks", entry.Name)
|
||||
if filer.FileSize(entry) == 0 && partNumber != maxPartNo {
|
||||
glog.Warningf("completeMultipartUpload %s empty part", entry.Name)
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedPartEmpty).Inc()
|
||||
continue
|
||||
}
|
||||
@@ -545,15 +545,24 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
partStartOffset := offset
|
||||
partETag := getEtagFromEntry(entry)
|
||||
|
||||
partSize := filer.FileSize(entry)
|
||||
if partSize > uint64(math.MaxInt64-offset) {
|
||||
return nil, nil, s3err.ErrEntityTooLarge
|
||||
}
|
||||
for _, chunk := range entry.GetChunks() {
|
||||
finalChunk, chunkErr := completedMultipartChunk(chunk, offset, sses3Info)
|
||||
if chunk.Offset < 0 || uint64(chunk.Offset) > partSize || chunk.Size > partSize-uint64(chunk.Offset) {
|
||||
return nil, nil, s3err.ErrInternalError
|
||||
}
|
||||
// Keep part-local offsets for encryption metadata derivation;
|
||||
// only the destination chunk's position is translated.
|
||||
finalChunk, chunkErr := completedMultipartChunk(chunk, partStartOffset+chunk.Offset, sses3Info)
|
||||
if chunkErr != nil {
|
||||
glog.Errorf("completeMultipartUpload %s %s SSE-S3 chunk metadata error: %v", *input.Bucket, *input.UploadId, chunkErr)
|
||||
return nil, nil, s3err.ErrInternalError
|
||||
}
|
||||
finalParts = append(finalParts, finalChunk)
|
||||
offset += int64(chunk.Size)
|
||||
}
|
||||
offset = partStartOffset + int64(partSize)
|
||||
|
||||
partEndChunk := len(finalParts)
|
||||
partBoundaries = append(partBoundaries, multipartPartBoundary{
|
||||
@@ -568,6 +577,13 @@ func (s3a *S3ApiServer) prepareMultipartCompletionState(r *http.Request, input *
|
||||
found = true
|
||||
}
|
||||
}
|
||||
// GET refuses a non-empty object with no chunks, so a layout of holes only
|
||||
// must not commit.
|
||||
if len(finalParts) == 0 && offset > 0 {
|
||||
glog.Warningf("completeMultipartUpload %s %s parts hold %d bytes of holes and no data", *input.Bucket, *input.UploadId, offset)
|
||||
stats.S3HandlerCounter.WithLabelValues(stats.ErrorCompletedPartEmpty).Inc()
|
||||
return nil, nil, s3err.ErrInvalidPart
|
||||
}
|
||||
|
||||
// Compute the object checksum from per-part checksums if the upload was
|
||||
// initiated with a checksum algorithm (stored in the upload dir entry).
|
||||
@@ -1260,7 +1276,7 @@ func (s3a *S3ApiServer) removeUploadDir(bucket, uploadId, object string) s3err.E
|
||||
glog.Errorf("bucket %s remove upload %s completed check: %v", bucket, uploadId, err)
|
||||
return s3err.ErrInternalError
|
||||
}
|
||||
if completed {
|
||||
if completed != nil {
|
||||
if err := s3a.uploadFiler(bucket, object).rm(context.Background(), s3a.genUploadsFolder(bucket), uploadId, false, true); err != nil {
|
||||
glog.V(1).Infof("bucket %s remove upload %s: %v", bucket, uploadId, err)
|
||||
return s3err.ErrInternalError
|
||||
@@ -1343,12 +1359,12 @@ func (s3a *S3ApiServer) uploadCommitPath(bucket, object string) (string, error)
|
||||
return dirName + "/" + entryName, nil
|
||||
}
|
||||
|
||||
// uploadCompleted reports whether the upload assembled into an object: the
|
||||
// object entry, or any version file under <key>.versions, still carries the
|
||||
// upload id completion stamps on it.
|
||||
func (s3a *S3ApiServer) uploadCompleted(bucket, uploadId, objectKey string) (bool, error) {
|
||||
// uploadCompleted returns the object the upload assembled into: the object
|
||||
// entry, or the version file under <key>.versions, that still carries the
|
||||
// upload id completion stamps on it; nil when there is none.
|
||||
func (s3a *S3ApiServer) uploadCompleted(bucket, uploadId, objectKey string) (*filer_pb.Entry, error) {
|
||||
if objectKey == "" {
|
||||
return false, nil
|
||||
return nil, nil
|
||||
}
|
||||
bucketDir := s3a.bucketDir(bucket)
|
||||
name := path.Base(objectKey)
|
||||
@@ -1360,25 +1376,25 @@ func (s3a *S3ApiServer) uploadCompleted(bucket, uploadId, objectKey string) (boo
|
||||
|
||||
entry, err := s3a.getObjectEntryRoutedByKey(bucket, objectKey)
|
||||
if err != nil && !isFilerNotFound(err) {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
if entry != nil && string(entry.Extended[s3_constants.SeaweedFSUploadId]) == uploadId {
|
||||
return true, nil
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
versions, _, err := s3a.listObjectScopedEntriesRoutedByKey(bucket, objectKey, objectDir+"/"+name+s3_constants.VersionsFolder, "", "", false, math.MaxInt32)
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) {
|
||||
return false, nil
|
||||
return nil, nil
|
||||
}
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
for _, version := range versions {
|
||||
if string(version.Extended[s3_constants.SeaweedFSUploadId]) == uploadId {
|
||||
return true, nil
|
||||
return version, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type ListMultipartUploadsResult struct {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
)
|
||||
|
||||
func TestCompleteMultipartUploadPreservesPartLogicalLayout(t *testing.T) {
|
||||
const etag = "5eb63bbbe01eeed093cb22bb8f5acdc3"
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
chunks []*filer_pb.FileChunk
|
||||
}{
|
||||
{"out_of_order", []*filer_pb.FileChunk{{FileId: "3,01637037d6", Offset: 4, Size: 2}, {FileId: "3,02637037d6", Size: 4}}},
|
||||
{"overlap", []*filer_pb.FileChunk{{FileId: "3,01637037d6", Offset: 2, Size: 4, ModifiedTsNs: 1}, {FileId: "3,02637037d6", Size: 4, ModifiedTsNs: 2}}},
|
||||
{"holes", []*filer_pb.FileChunk{{FileId: "3,01637037d6", Offset: 2, Size: 1}}},
|
||||
{"all_hole", nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &memCompleteFiler{entries: map[string]map[string]*filer_pb.Entry{}}
|
||||
s3a := newCompleteTestServer(t, f)
|
||||
uploadDir := s3a.genUploadsFolder("b") + "/u1"
|
||||
f.entries[uploadDir] = map[string]*filer_pb.Entry{}
|
||||
f.put(uploadDir, &filer_pb.Entry{Name: "0001.part", Attributes: &filer_pb.FuseAttributes{FileSize: multiPartMinSize}, Chunks: tc.chunks, Extended: map[string][]byte{s3_constants.ExtETagKey: []byte(etag)}})
|
||||
f.put(uploadDir, &filer_pb.Entry{Name: "0002.part", Attributes: &filer_pb.FuseAttributes{FileSize: 4}, Chunks: []*filer_pb.FileChunk{{FileId: "3,03637037d6", Offset: 1, Size: 2}}, Extended: map[string][]byte{s3_constants.ExtETagKey: []byte(etag)}})
|
||||
input := &s3.CompleteMultipartUploadInput{Bucket: aws.String("b"), Key: aws.String("a.bin"), UploadId: aws.String("u1")}
|
||||
parts := &CompleteMultipartUpload{Parts: []CompletedPart{{PartNumber: 1, ETag: etag}, {PartNumber: 2, ETag: etag}}}
|
||||
_, code := s3a.completeMultipartUpload(httptest.NewRequest("POST", "/b/a.bin?uploadId=u1", nil), input, parts)
|
||||
if code != s3err.ErrNone {
|
||||
t.Fatalf("complete: %v", code)
|
||||
}
|
||||
got := f.entries[s3a.bucketDir("b")]["a.bin"]
|
||||
if got == nil || got.GetAttributes().GetFileSize() != multiPartMinSize+4 {
|
||||
t.Fatalf("wrong logical size: %v", got)
|
||||
}
|
||||
if len(got.Chunks) != len(tc.chunks)+1 {
|
||||
t.Fatalf("wrong chunk count: %d", len(got.Chunks))
|
||||
}
|
||||
for i, source := range tc.chunks {
|
||||
dest := got.Chunks[i]
|
||||
if dest.Offset != source.Offset || dest.Size != source.Size || dest.ModifiedTsNs != source.ModifiedTsNs || dest.GetFileIdString() != source.GetFileIdString() {
|
||||
t.Errorf("part 1 chunk %d changed layout: %v", i, dest)
|
||||
}
|
||||
}
|
||||
if last := got.Chunks[len(got.Chunks)-1]; last.Offset != multiPartMinSize+1 || last.Size != 2 {
|
||||
t.Errorf("part 2 rebased incorrectly: %v", last)
|
||||
}
|
||||
// The real read planner must select the same bytes after completion.
|
||||
before, err := filer.ViewFromChunks(context.Background(), nil, tc.chunks, 0, 6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := filer.ViewFromChunks(context.Background(), nil, got.Chunks, 0, 6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, a := before.Front(), after.Front()
|
||||
for b != nil && a != nil {
|
||||
if b.StartOffset != a.StartOffset || b.StopOffset != a.StopOffset || b.Value.FileId != a.Value.FileId || b.Value.OffsetInChunk != a.Value.OffsetInChunk {
|
||||
t.Fatalf("read view changed: before=%+v after=%+v", b, a)
|
||||
}
|
||||
b, a = b.Next, a.Next
|
||||
}
|
||||
if b != nil || a != nil {
|
||||
t.Fatal("read view count changed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteMultipartUploadRejectsHoleOnlyObject(t *testing.T) {
|
||||
const etag = "5eb63bbbe01eeed093cb22bb8f5acdc3"
|
||||
for _, sizes := range [][]uint64{{4}, {multiPartMinSize, 4}} {
|
||||
f := &memCompleteFiler{entries: map[string]map[string]*filer_pb.Entry{}}
|
||||
s3a := newCompleteTestServer(t, f)
|
||||
uploadDir := s3a.genUploadsFolder("b") + "/u1"
|
||||
f.entries[uploadDir] = map[string]*filer_pb.Entry{}
|
||||
parts := &CompleteMultipartUpload{}
|
||||
for i, size := range sizes {
|
||||
f.put(uploadDir, &filer_pb.Entry{Name: fmt.Sprintf("%04d.part", i+1), Attributes: &filer_pb.FuseAttributes{FileSize: size}, Extended: map[string][]byte{s3_constants.ExtETagKey: []byte(etag)}})
|
||||
parts.Parts = append(parts.Parts, CompletedPart{PartNumber: i + 1, ETag: etag})
|
||||
}
|
||||
input := &s3.CompleteMultipartUploadInput{Bucket: aws.String("b"), Key: aws.String("a.bin"), UploadId: aws.String("u1")}
|
||||
_, code := s3a.completeMultipartUpload(httptest.NewRequest("POST", "/b/a.bin?uploadId=u1", nil), input, parts)
|
||||
if code != s3err.ErrInvalidPart {
|
||||
t.Errorf("%d hole-only parts: got %v, want InvalidPart", len(sizes), code)
|
||||
}
|
||||
if got := f.entries[s3a.bucketDir("b")]["a.bin"]; got != nil {
|
||||
t.Errorf("%d hole-only parts committed an object GET cannot serve: %v", len(sizes), got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,8 @@ func ResolveS3Action(r *http.Request, baseAction string, bucket string, object s
|
||||
s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG:
|
||||
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
s3_constants.ACTION_GET_INCOMPLETE_UPLOAD:
|
||||
return mapBaseActionToS3Format(baseAction)
|
||||
}
|
||||
|
||||
@@ -155,6 +156,9 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool)
|
||||
case http.MethodDelete:
|
||||
return s3_constants.S3_ACTION_ABORT_MULTIPART
|
||||
case http.MethodGet:
|
||||
if query.Has("part") {
|
||||
return s3_constants.S3_ACTION_GET_OBJECT
|
||||
}
|
||||
return s3_constants.S3_ACTION_LIST_PARTS
|
||||
}
|
||||
}
|
||||
@@ -417,6 +421,8 @@ func mapBaseActionToS3Format(baseAction string) string {
|
||||
return s3_constants.S3_ACTION_BYPASS_GOVERNANCE
|
||||
case s3_constants.ACTION_GET_OBJECT_RETENTION:
|
||||
return s3_constants.S3_ACTION_GET_OBJECT_RETENTION
|
||||
case s3_constants.ACTION_GET_INCOMPLETE_UPLOAD:
|
||||
return s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD
|
||||
case s3_constants.ACTION_PUT_OBJECT_RETENTION:
|
||||
return s3_constants.S3_ACTION_PUT_OBJECT_RETENTION
|
||||
case s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD:
|
||||
|
||||
@@ -69,6 +69,7 @@ const (
|
||||
SeaweedFSExpiresS3 = "X-Seaweedfs-Expires-S3"
|
||||
SeaweedFSVectorSearchMode = "x-seaweedfs-vector-search-mode"
|
||||
AmzMpPartsCount = "x-amz-mp-parts-count"
|
||||
AmzMultipartUploadStatus = "x-amz-multipart-upload-status"
|
||||
|
||||
// S3 ACL headers
|
||||
AmzCannedAcl = "X-Amz-Acl"
|
||||
|
||||
@@ -45,6 +45,7 @@ const (
|
||||
S3_ACTION_UPLOAD_PART_COPY = "s3:UploadPartCopy"
|
||||
S3_ACTION_LIST_PARTS = "s3:ListMultipartUploadParts"
|
||||
S3_ACTION_LIST_MULTIPART_UPLOADS = "s3:ListBucketMultipartUploads"
|
||||
S3_ACTION_GET_INCOMPLETE_UPLOAD = "s3:GetIncompleteUpload"
|
||||
|
||||
// Bucket operations
|
||||
S3_ACTION_CREATE_BUCKET = "s3:CreateBucket"
|
||||
|
||||
@@ -28,6 +28,8 @@ const (
|
||||
// these names must not widen into a general Read grant.
|
||||
ACTION_LIST_MULTIPART_UPLOADS = "ListBucketMultipartUploads"
|
||||
ACTION_LIST_PARTS = "ListMultipartUploadParts"
|
||||
// Checked on top of Read before a part of an open upload is served.
|
||||
ACTION_GET_INCOMPLETE_UPLOAD = "GetIncompleteUpload"
|
||||
|
||||
SeaweedStorageDestinationHeader = "x-seaweedfs-destination"
|
||||
MultipartUploadsFolder = ".uploads"
|
||||
|
||||
@@ -56,6 +56,20 @@ func TestListPartsActionMapping(t *testing.T) {
|
||||
expectedAction: "s3:ListMultipartUploadParts",
|
||||
description: "GET request with uploadId plus other multipart params should map to s3:ListMultipartUploadParts",
|
||||
},
|
||||
{
|
||||
name: "get_part",
|
||||
method: "GET",
|
||||
bucket: "test-bucket",
|
||||
objectKey: "test-object.txt",
|
||||
queryParams: map[string]string{
|
||||
"part": "",
|
||||
"partNumber": "1",
|
||||
"uploadId": "test-upload-id",
|
||||
},
|
||||
fallbackAction: s3_constants.ACTION_READ,
|
||||
expectedAction: "s3:GetObject",
|
||||
description: "GetPart reads part bytes, so a ListParts grant must not cover it",
|
||||
},
|
||||
{
|
||||
name: "get_object_with_versionId",
|
||||
method: "GET",
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"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 (
|
||||
multipartUploadStatusInProgress = "IN_PROGRESS"
|
||||
multipartUploadStatusCompleted = "COMPLETED"
|
||||
)
|
||||
|
||||
// GetPartHandler reads one part of a multipart upload: the latest attempt of
|
||||
// an open upload's part, or the bytes that part became in the object a
|
||||
// completed upload assembled.
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPart.html
|
||||
func (s3a *S3ApiServer) GetPartHandler(w http.ResponseWriter, r *http.Request) {
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
if errCode := s3a.checkBucket(r, bucket); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
partNumber, err := strconv.Atoi(query.Get("partNumber"))
|
||||
if err != nil || partNumber < 1 || partNumber > s3_constants.MaxS3MultipartParts {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
// GetPart decrypts SSE-S3/SSE-KMS parts on its own and never takes SSE-C
|
||||
if r.Header.Get(s3_constants.AmzServerSideEncryption) != "" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidArgument)
|
||||
return
|
||||
}
|
||||
if r.Header.Get(s3_constants.AmzServerSideEncryptionCustomerAlgorithm) != "" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
uploadID := query.Get("uploadId")
|
||||
if s3a.checkUploadId(object, uploadID) != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchUpload)
|
||||
return
|
||||
}
|
||||
|
||||
uploadEntry, err := s3a.uploadFiler(bucket, object).getEntry(s3a.genUploadsFolder(bucket), uploadID)
|
||||
if err != nil && !isFilerNotFound(err) {
|
||||
glog.Errorf("GetPart %s/%s upload %s: %v", bucket, object, uploadID, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if isMultipartUploadEntry(uploadEntry) {
|
||||
s3a.getOpenUploadPart(w, r, bucket, object, uploadID, partNumber)
|
||||
return
|
||||
}
|
||||
s3a.getCompletedUploadPart(w, r, bucket, object, uploadID, partNumber)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) getOpenUploadPart(w http.ResponseWriter, r *http.Request, bucket, object, uploadID string, partNumber int) {
|
||||
if errCode := s3a.checkIncompleteUploadGrant(r, bucket, object); errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
part, err := s3a.latestPartAttempt(bucket, object, uploadID, partNumber)
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchUpload)
|
||||
return
|
||||
}
|
||||
glog.Errorf("GetPart %s/%s upload %s part %d: %v", bucket, object, uploadID, partNumber, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if part == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchPart)
|
||||
return
|
||||
}
|
||||
sseType := s3a.detectPrimarySSEType(part)
|
||||
if sseType == s3_constants.SSETypeC {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set(s3_constants.AmzMultipartUploadStatus, multipartUploadStatusInProgress)
|
||||
setEtag(w, getEtagFromEntry(part))
|
||||
// setResponseHeaders leaves out the checksum on any partNumber read, but a
|
||||
// whole open part is exactly what its stored checksum covers.
|
||||
if r.Header.Get("Range") == "" && strings.EqualFold(r.Header.Get(s3_constants.AmzChecksumMode), "ENABLED") {
|
||||
if name, value := part.Extended[s3_constants.ExtChecksumAlgorithm], part.Extended[s3_constants.ExtChecksumValue]; len(name) > 0 && len(value) > 0 {
|
||||
w.Header().Set(string(name), string(value))
|
||||
}
|
||||
}
|
||||
s3a.streamPart(w, r, part, sseType, bucket, object, "")
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) getCompletedUploadPart(w http.ResponseWriter, r *http.Request, bucket, object, uploadID string, partNumber int) {
|
||||
entry, err := s3a.uploadCompleted(bucket, uploadID, object)
|
||||
if err != nil {
|
||||
glog.Errorf("GetPart %s/%s upload %s completed check: %v", bucket, object, uploadID, err)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
if entry == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchUpload)
|
||||
return
|
||||
}
|
||||
|
||||
versionId := string(entry.Extended[s3_constants.ExtVersionIdKey])
|
||||
var errCode s3err.ErrorCode
|
||||
if versionId != "" {
|
||||
errCode = s3a.checkVersionReadGrant(r, bucket, object, versionId, entry.Extended)
|
||||
} else {
|
||||
errCode = s3a.recheckPolicyWithObjectEntry(r, bucket, object, string(s3_constants.ACTION_READ), entry.Extended, "GetPartHandler")
|
||||
}
|
||||
if errCode != s3err.ErrNone {
|
||||
s3err.WriteErrorResponse(w, r, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
sseType := s3a.detectPrimarySSEType(entry)
|
||||
if sseType == s3_constants.SSETypeC {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Without recorded boundaries the part cannot be told apart from its
|
||||
// neighbours, and guessing one chunk per part would serve the wrong bytes.
|
||||
_, partInfo, _ := s3a.getMultipartInfo(entry, partNumber)
|
||||
if partInfo == nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchPart)
|
||||
return
|
||||
}
|
||||
if partInfo.EndChunk == partInfo.StartChunk && partInfo.EndOffset <= partInfo.StartOffset {
|
||||
if r.Header.Get("Range") != "" {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
|
||||
return
|
||||
}
|
||||
if versionId != "" {
|
||||
w.Header().Set("x-amz-version-id", versionId)
|
||||
}
|
||||
w.Header().Set(s3_constants.AmzMultipartUploadStatus, multipartUploadStatusCompleted)
|
||||
setEtag(w, partInfo.ETag)
|
||||
w.Header().Set("Content-Length", "0")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
partStart, partEnd, ok := partRange(partInfo, entry.Chunks)
|
||||
if !ok {
|
||||
glog.Errorf("GetPart %s/%s upload %s: part %d boundary out of range", bucket, object, uploadID, partNumber)
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
|
||||
return
|
||||
}
|
||||
readStart, readEnd := partStart, partEnd
|
||||
clientRange := r.Header.Get("Range")
|
||||
if clientRange != "" {
|
||||
if readStart, readEnd, err = adjustRangeForPart(partStart, partEnd, clientRange); err != nil {
|
||||
s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
|
||||
return
|
||||
}
|
||||
}
|
||||
r.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", readStart, readEnd))
|
||||
|
||||
if versionId != "" {
|
||||
w.Header().Set("x-amz-version-id", versionId)
|
||||
}
|
||||
w.Header().Set(s3_constants.AmzMultipartUploadStatus, multipartUploadStatusCompleted)
|
||||
setEtag(w, partInfo.ETag)
|
||||
pw := &partRangeWriter{
|
||||
ResponseWriter: w,
|
||||
ranged: clientRange != "",
|
||||
contentRange: fmt.Sprintf("bytes %d-%d/%d", readStart-partStart, readEnd-partStart, partEnd-partStart+1),
|
||||
}
|
||||
s3a.streamPart(pw, r, entry, sseType, bucket, object, versionId)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) streamPart(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType, bucket, object, versionId string) {
|
||||
if err := s3a.streamFromVolumeServersWithSSE(w, r, entry, sseType, bucket, object, versionId); err != nil {
|
||||
if streamCanceled(r.Context(), err) {
|
||||
logCanceledStream(r, "GetPartHandler", bucket, object, err)
|
||||
} else {
|
||||
glog.Errorf("GetPart %s/%s: %v", bucket, object, err)
|
||||
}
|
||||
writeStreamErrorResponse(w, r, err)
|
||||
}
|
||||
}
|
||||
|
||||
// latestPartAttempt returns the newest stored attempt of an open upload's
|
||||
// part, or nil when that part number was never uploaded.
|
||||
func (s3a *S3ApiServer) latestPartAttempt(bucket, object, uploadID string, partNumber int) (*filer_pb.Entry, error) {
|
||||
input := &s3.ListPartsInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(object),
|
||||
UploadId: aws.String(uploadID),
|
||||
MaxParts: aws.Int64(1),
|
||||
}
|
||||
var latest *filer_pb.Entry
|
||||
// "%04d" also prefixes the five-digit part number 10000 under part 1000
|
||||
name := fmt.Sprintf("%04d", partNumber)
|
||||
_, err := s3a.scanPartAttempts(input, name, name, func(n int) bool { return n == partNumber }, func(_ int, entry *filer_pb.Entry) bool {
|
||||
if latest == nil || compareLatestPartAttempt(entry, latest) < 0 {
|
||||
latest = entry
|
||||
}
|
||||
return false
|
||||
})
|
||||
return latest, err
|
||||
}
|
||||
|
||||
// checkIncompleteUploadGrant enforces s3:GetIncompleteUpload, which AWS
|
||||
// requires on top of the read grant before a part of an open upload is served.
|
||||
func (s3a *S3ApiServer) checkIncompleteUploadGrant(r *http.Request, bucket, object string) s3err.ErrorCode {
|
||||
if identity, ok := s3_constants.GetIdentityFromContext(r).(*Identity); ok && identity != nil {
|
||||
if errCode := s3a.iam.VerifyActionPermission(r, identity, s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, bucket, object); errCode != s3err.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
}
|
||||
return s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, nil, "GetPartHandler")
|
||||
}
|
||||
|
||||
// partRangeWriter answers a read of a completed upload's part the way GetPart
|
||||
// does: byte positions count from the part's start, and a read of the whole
|
||||
// part is a 200 rather than the object range it was served as.
|
||||
type partRangeWriter struct {
|
||||
http.ResponseWriter
|
||||
ranged bool
|
||||
contentRange string
|
||||
}
|
||||
|
||||
func (p *partRangeWriter) WriteHeader(code int) {
|
||||
if code == http.StatusPartialContent {
|
||||
if p.ranged {
|
||||
p.Header().Set("Content-Range", p.contentRange)
|
||||
} else {
|
||||
p.Header().Del("Content-Range")
|
||||
code = http.StatusOK
|
||||
}
|
||||
}
|
||||
p.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (p *partRangeWriter) Unwrap() http.ResponseWriter {
|
||||
return p.ResponseWriter
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func getPartRequest() *http.Request {
|
||||
req := &http.Request{
|
||||
Method: http.MethodGet,
|
||||
URL: &url.URL{Path: "/bucket/key", RawQuery: "part&partNumber=1&uploadId=abc"},
|
||||
}
|
||||
return mux.SetURLVars(req, map[string]string{"bucket": "bucket", "object": "key"})
|
||||
}
|
||||
|
||||
func TestGetPartIncompleteUploadActionIgnoresRequestShape(t *testing.T) {
|
||||
assert.Equal(t, s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD,
|
||||
ResolveS3Action(getPartRequest(), s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, "bucket", "key"))
|
||||
}
|
||||
|
||||
func TestGetPartIsNotAPartsListing(t *testing.T) {
|
||||
assert.Equal(t, Action(""), multipartListingAction(getPartRequest(), s3_constants.ACTION_READ))
|
||||
|
||||
withUploads := getPartRequest()
|
||||
withUploads.URL.RawQuery = "part&partNumber=1&uploadId=abc&uploads"
|
||||
assert.Equal(t, Action(""), multipartListingAction(withUploads, s3_constants.ACTION_READ))
|
||||
|
||||
listing := getPartRequest()
|
||||
listing.URL.RawQuery = "uploadId=abc"
|
||||
assert.Equal(t, Action(s3_constants.ACTION_LIST_PARTS), multipartListingAction(listing, s3_constants.ACTION_READ))
|
||||
}
|
||||
|
||||
func TestPartRangeWriter(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ranged bool
|
||||
wantStatus int
|
||||
wantRangeHdr string
|
||||
}{
|
||||
{"whole part answers 200", false, http.StatusOK, ""},
|
||||
{"ranged read counts within the part", true, http.StatusPartialContent, "bytes 2-5/10"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
w := &partRangeWriter{ResponseWriter: rec, ranged: c.ranged, contentRange: "bytes 2-5/10"}
|
||||
w.Header().Set("Content-Range", "bytes 102-105/4096")
|
||||
w.WriteHeader(http.StatusPartialContent)
|
||||
assert.Equal(t, c.wantStatus, rec.Code)
|
||||
assert.Equal(t, c.wantRangeHdr, rec.Header().Get("Content-Range"))
|
||||
})
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
(&partRangeWriter{ResponseWriter: rec}).WriteHeader(http.StatusInternalServerError)
|
||||
assert.Equal(t, http.StatusInternalServerError, rec.Code)
|
||||
}
|
||||
@@ -1100,6 +1100,8 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
|
||||
bucket.Methods(http.MethodPost).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.NewMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploads", "")
|
||||
// AbortMultipartUpload
|
||||
bucket.Methods(http.MethodDelete).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.AbortMultipartUploadHandler, ACTION_WRITE)), "DELETE")).Queries("uploadId", "{uploadId:.*}")
|
||||
// GetPart; partNumber is checked by the handler so a ?part request never falls through to ListParts
|
||||
bucket.Methods(http.MethodGet).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetPartHandler, ACTION_READ)), "GET")).Queries("part", "", "uploadId", "{uploadId:.*}")
|
||||
// ListObjectParts
|
||||
bucket.Methods(http.MethodGet).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectPartsHandler, ACTION_READ)), "GET")).Queries("uploadId", "{uploadId:.*}")
|
||||
// ListMultipartUploads
|
||||
|
||||
@@ -61,6 +61,7 @@ const (
|
||||
ErrNoSuchKey
|
||||
ErrNoSuchVersion
|
||||
ErrNoSuchUpload
|
||||
ErrNoSuchPart
|
||||
ErrInvalidBucketName
|
||||
ErrInvalidBucketState
|
||||
ErrInvalidDigest
|
||||
@@ -346,6 +347,11 @@ var errorCodeResponse = map[ErrorCode]APIError{
|
||||
Description: "The specified multipart upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed.",
|
||||
HTTPStatusCode: http.StatusNotFound,
|
||||
},
|
||||
ErrNoSuchPart: {
|
||||
Code: "NoSuchPart",
|
||||
Description: "The specified part does not exist. The part may not have been uploaded.",
|
||||
HTTPStatusCode: http.StatusNotFound,
|
||||
},
|
||||
ErrInternalError: {
|
||||
Code: "InternalError",
|
||||
Description: "We encountered an internal error, please try again.",
|
||||
|
||||
@@ -46,13 +46,13 @@ func NewBufferedQueue[T any](chunkSize int) *BufferedQueue[T] {
|
||||
// Enqueue adds a job to the queue
|
||||
func (q *BufferedQueue[T]) Enqueue(job T) error {
|
||||
|
||||
q.mutex.Lock()
|
||||
defer q.mutex.Unlock()
|
||||
|
||||
if q.isClosed {
|
||||
return fmt.Errorf("queue is closed")
|
||||
}
|
||||
|
||||
q.mutex.Lock()
|
||||
defer q.mutex.Unlock()
|
||||
|
||||
// If the tail chunk is full, create a new chunk (reusing empty chunks if available)
|
||||
if q.tail.tailIndex == q.chunkSize {
|
||||
if q.tail == q.last {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package buffered_queue
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEnqueueConcurrentCloseDrainsAcceptedItem(t *testing.T) {
|
||||
deadline := time.NewTimer(10 * time.Second)
|
||||
defer deadline.Stop()
|
||||
for trial := 0; trial < 1000; trial++ {
|
||||
q := NewBufferedQueue[int](2)
|
||||
start := make(chan struct{})
|
||||
var enqueueErr error
|
||||
var received []int
|
||||
var workers sync.WaitGroup
|
||||
workers.Add(3)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
enqueueErr = q.Enqueue(42)
|
||||
}()
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
q.CloseInput()
|
||||
}()
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
<-start
|
||||
for item, ok := q.Dequeue(); ok; item, ok = q.Dequeue() {
|
||||
received = append(received, item)
|
||||
}
|
||||
}()
|
||||
done := make(chan struct{})
|
||||
go func() { workers.Wait(); close(done) }()
|
||||
close(start)
|
||||
select {
|
||||
case <-done:
|
||||
case <-deadline.C:
|
||||
t.Fatalf("trial %d: enqueue, close, or drain did not finish", trial)
|
||||
}
|
||||
// Once the consumer observes closure, every successful enqueue must
|
||||
// already have been drained. No item may be accepted after it exits.
|
||||
if enqueueErr == nil {
|
||||
if len(received) != 1 || received[0] != 42 {
|
||||
t.Fatalf("trial %d: successful enqueue was not drained: %v", trial, received)
|
||||
}
|
||||
} else if len(received) != 0 {
|
||||
t.Fatalf("trial %d: rejected enqueue was consumed: %v", trial, received)
|
||||
}
|
||||
if size := q.Size(); size != 0 {
|
||||
t.Fatalf("trial %d: closed queue retained %d items after drain", trial, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueCloseOrdering(t *testing.T) {
|
||||
t.Run("enqueue_before_close", func(t *testing.T) {
|
||||
q := NewBufferedQueue[int](2)
|
||||
if err := q.Enqueue(42); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q.CloseInput()
|
||||
if got, ok := q.Dequeue(); !ok || got != 42 {
|
||||
t.Fatalf("drain got %v,%v", got, ok)
|
||||
}
|
||||
if _, ok := q.Dequeue(); ok {
|
||||
t.Fatal("queue not drained")
|
||||
}
|
||||
})
|
||||
t.Run("close_before_enqueue", func(t *testing.T) {
|
||||
q := NewBufferedQueue[int](2)
|
||||
q.CloseInput()
|
||||
if err := q.Enqueue(42); err == nil {
|
||||
t.Fatal("closed queue accepted item")
|
||||
}
|
||||
if _, ok := q.Dequeue(); ok {
|
||||
t.Fatal("closed queue yielded item")
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user